public ThemedRazorViewEngine(string theme)
        {
            var additionalViewLocations = new[]{
            String.Format("~/Assets/themes/{0}/html/{{1}}/{{0}}.cshtml", theme),
            String.Format("~/Assets/themes/{0}/html/Shared/{{0}}.cshtml", theme)
              };

              ViewLocationFormats = additionalViewLocations.Union(ViewLocationFormats).ToArray();
              MasterLocationFormats = additionalViewLocations.Union(MasterLocationFormats).ToArray();
              PartialViewLocationFormats = additionalViewLocations.Union(PartialViewLocationFormats).ToArray();
        }
        protected void Application_Start()
        {
            System.Web.Mvc.RazorViewEngine rve = (RazorViewEngine)ViewEngines.Engines
              .Where(e => e.GetType() == typeof(RazorViewEngine))
              .FirstOrDefault();

            string[] customViewLocations = new[] {
                "~/Custom/Views/{1}/{0}.cshtml",
                "~/Custom/Views/Shared/{0}.cshtml"
            };

            if (rve != null)
            {
                rve.PartialViewLocationFormats = customViewLocations
                  .Union(rve.PartialViewLocationFormats)
                  .ToArray();

                rve.MasterLocationFormats = customViewLocations
                    .Union(rve.MasterLocationFormats)
                    .ToArray();

                rve.ViewLocationFormats = customViewLocations
                    .Union(rve.ViewLocationFormats)
                    .ToArray();
            }

            /*
            ViewEngines.Engines.Clear();
            var razorEngine = new RazorViewEngine();
            razorEngine.MasterLocationFormats = razorEngine.MasterLocationFormats
                .Concat(new[] {
                    "~/Custom/Views/{1}/{0}.cshtml",   // {1} = controller name
                    "~/Custom/Views/Shared/{0}.cshtml"
            }).ToArray();

            razorEngine.PartialViewLocationFormats = razorEngine.PartialViewLocationFormats
                .Concat(new[] {
                    "~/Custom/Views/{1}/{0}.cshtml",   // {1} = controller name
                    "~/Custom/Views/Shared/{0}.cshtml"
            }).ToArray();

            ViewEngines.Engines.Add(razorEngine);
            */

            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
 public static void Thumbnail(FileStoreInfo originalImageFileInfo, ThumbnailProperty thumbnailProperty, IThumbnailNameProvider thumbnailWriteProvider = null, params ThumbnailProperty[] thumbnailProperties)
 {
     var defaultThumbnailWriteProvider = thumbnailWriteProvider;
     if (originalImageFileInfo == null)
         throw new ArgumentNullException("originalImageFileInfo");
     if (string.IsNullOrEmpty(originalImageFileInfo.FileNameWithExtension))
         throw new ArgumentException("originalImageFileInfo.FileNameWithExtension不能为空");
     if (thumbnailProperty == null)
         throw new ArgumentNullException("thumbnailProperty");
     if (!File.Exists(originalImageFileInfo.FullFileName))
         throw new FileNotFoundException(string.Format("路径:{0}的不存在", originalImageFileInfo.FullFileName));
     if (thumbnailWriteProvider == null)
         defaultThumbnailWriteProvider = new DefaultThumbnailNameProvider();
     var unionThumbnailPropertyies = new[] { thumbnailProperty };
     if (thumbnailProperties != null)
     {
         unionThumbnailPropertyies = unionThumbnailPropertyies.Union(thumbnailProperties).ToArray();
     }
     var originalImage = System.Drawing.Image.FromFile(originalImageFileInfo.FullFileName);
     foreach (var property in unionThumbnailPropertyies)
     {
         var fileInfo = defaultThumbnailWriteProvider.GetThumbnailFileInfo(originalImageFileInfo, thumbnailProperty);
         var thumbnailImage = CreateThumbnailImage(originalImage, property);
         thumbnailImage.Save(fileInfo.FullFileName);
     }
 }
Example #4
0
        public static Assembly Compile(SyntaxTree tree, string dllName)
        {
            var myRefs =
                new[] {
                    "System", "System.Core", "mscorlib", "System.Runtime"
                }.Select(MetadataReference.CreateAssemblyReference);

            var obsRef = new MetadataFileReference(typeof(Observable).Assembly.Location);
            var synRef = new MetadataFileReference(typeof(CommonSyntaxTree).Assembly.Location);
            var comRef = new MetadataFileReference(typeof(CompilationOptions).Assembly.Location);

            myRefs = myRefs.Union(new[] { obsRef, synRef, comRef });

            var compiledCode = Compilation.Create(
                outputName: dllName,
                options: new CompilationOptions(OutputKind.DynamicallyLinkedLibrary),
                syntaxTrees: new[] { tree },
                references: myRefs);

            using (var stream = new MemoryStream())
            {
                var emitResult = compiledCode.Emit(stream);
                if (!emitResult.Success)
                {
                    var message = string.Join("\r\n", emitResult.Diagnostics);
                    throw new ApplicationException(message);
                }

                return Assembly.Load(stream.GetBuffer());
            }
        }
Example #5
0
        public void Fight()
        {
            // PART 1. Target selection

            // Clear objectives
            foreach (var groups in System.Union(Infect))
            {
                groups.AttackObjective = null;
                groups.IsTargeted      = false;
            }
            // System select their targets
            SelectTargets(System, Infect);

            // Infect select their targets
            SelectTargets(Infect, System);

            // PART 2. Attacking
            foreach (var group in System.Union(Infect).OrderByDescending(g => g.Initiative))
            {
                group.Attack();
            }

            // Clean
            System.Where(i => i.Units == 0).ToList().ForEach(i => System.Remove(i));
            Infect.Where(i => i.Units == 0).ToList().ForEach(i => Infect.Remove(i));
        }
Example #6
0
        public void When_getting_all_event_from_an_existing_event_source_the_result_should_be_all_events_stored_for_that_event_source()
        {
            var eventSourceId = Guid.NewGuid();
            var mock = new EventSourceMock();
            mock.EventSourceId = eventSourceId;

            var store = new InMemoryEventStore();

            var events1 = new[]{
                                  new SomethingDoneEvent(eventSourceId), new SomethingDoneEvent(eventSourceId),
                              };

            var events2 = new[]{
                                  new SomethingDoneEvent(eventSourceId), new SomethingDoneEvent(eventSourceId), new SomethingDoneEvent(eventSourceId)
                              };

            mock.GetUncommittedEventsStub = () => events1;
            store.Save(mock);

            mock.GetUncommittedEventsStub = () => events2;
            store.Save(mock);

            var events = store.GetAllEvents(eventSourceId);
            var unionOfStoredEvents = events1.Union(events2);

            events.Count().Should().Be(unionOfStoredEvents.Count());
            events.Should().BeEquivalentTo(unionOfStoredEvents);
        }
 public override IEnumerable<string> GetFieldNames()
 {
     var hardcodedAttributes = new[] {"name", "schema-name", "schema-id"};
     var elementAttributes = _source.Attributes().Select(xAttribute => xAttribute.Name.LocalName);
     var childAttributes = _source.Elements().Where(x=>x.Attribute("isDoc") == null).Select(xChild => xChild.Name.LocalName);
     return hardcodedAttributes.Union(elementAttributes).Union(childAttributes);
 }
Example #8
0
        public void Set(object target, object value, params object[] index)
        {
            IEnumerable<object> args = new[] { value };
            if (index != null) args = args.Union(index);
            if (target != null && !target.GetType().CanAssign(InternalMember.DeclaringType))
                throw new TargetException("Expected {0}".AsFormat(InternalMember.DeclaringType.GetRealClassName()));

            Cache.GetSetter(InternalMember)(target, args.ToArray());
        }
Example #9
0
        /// <summary>
        ///   Usefull for testing encryption refactoring so that I can generate the same signature twice
        /// </summary>
        /// <param name="nonce"> </param>
        /// <param name="localtime"> </param>
        /// <param name="kvp"> </param>
        /// <returns> </returns>
        public string Sign(string nonce, DateTime localtime, IEnumerable<KeyValuePair<string, string>> kvp)
        {
            var timestamp = LocalTimeToUnixTimestampSeconds(localtime);
            // ReSharper disable SpecifyACultureInStringConversionExplicitly
            var otherSignature = new[]{new KeyValuePair<string, string>("nonce", nonce), new KeyValuePair<string, string>("timestamp", timestamp.ToString())};
            // ReSharper restore SpecifyACultureInStringConversionExplicitly

            var urlEncoded = string.Join("&", otherSignature.Union(kvp).Select(item => HttpUtility.UrlEncode(item.Key) + "=" + HttpUtility.UrlEncode(item.Value)));
            return string.Format("{0}|{1}", Sign(urlEncoded), urlEncoded);
        }
        public void Can_union_two_lists()
        {
            // Arrange
            var first = new[] {new TestObject("a", "a"), new TestObject("a", "b")};
            var second = new[] {new TestObject("a", "b"), new TestObject("b", "a")};

            // Act
            var result = first.Union(second, (x, y) => x.One == y.One && x.Two == y.Two, x => (x.One ?? "").GetHashCode() ^ (x.Two ?? "").GetHashCode()).ToArray();

            // Assert
            Assert.AreEqual(3, result.Length);
        }
        public void Can_union_two_lists_with_overriden_gethashcode()
        {
            // Arrange
            var first = new[] {new Test2Object("a", "a"), new Test2Object("a", "b")};
            var second = new[] {new Test2Object("a", "b"), new Test2Object("b", "a")};

            // Act
            var result = first.Union(second, (x, y) => x.One == y.One && x.Two == y.Two).ToArray();

            // Assert
            Assert.AreEqual(3, result.Length);
        }
        public void ShouldGetAllLogFiles()
        {
            var fileSystem = new Moq.Mock<IFileSystem>();
            var logFiles = new[] { @"C:\Path\backup-1234567890.csv" };
            var nonLogFiles = new[] { @"C:\Path\no-match.csv" };
            fileSystem.Setup(x => x.GetCommonApplicationDataPath()).Returns(@"C:\Path");
            fileSystem.Setup(x => x.GetFiles(@"C:\Path\cache\logs")).Returns(logFiles.Union(nonLogFiles));
            var target = new JungleDiskLogFilesProvider(fileSystem.Object, new AutomaticLogFilePath(fileSystem.Object));

            var result = target.GetAllLogFiles();

            result.Should().Have.SameSequenceAs(logFiles);
        }
Example #13
0
 public static void Initialize(string path)
 {
     var dll = new[] 
     { 
         "HtmlAgilityPack.dll", 
         "lnE.dll",
     };
     var references = ConfigurationManager.AppSettings["references"];
     if (!String.IsNullOrWhiteSpace(references))
     {
         dll = dll.Union(references.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries)).ToArray();
     }
     assembly = AssemblyHelper.GetAssembly(dll, path);
     dishes = AssemblyHelper.GetTypes<DishAttribute>(assembly);
 }
Example #14
0
        public static void CollectionMath_Test()
        {
            var arr1 = new[] {1, 2, 3, 4, 5, 6};
            var arr2 = new[] {2, 9};
            var test1 = arr1.Intersect(arr2);
            var test2 = arr1.Union(arr2);
            var test3 = arr1.Except(arr2);

            Console.WriteLine(arr1.Select(x => x.ToString()).Aggregate((x, y) => x + "," + y));
            Console.WriteLine(arr2.Select(x => x.ToString()).Aggregate((x, y) => x + "," + y));
            Console.WriteLine("--------------------------------------------------------------");
            Console.WriteLine(test1.Select(x => x.ToString()).Aggregate((x, y) => x + "," + y));
            Console.WriteLine(test2.Select(x => x.ToString()).Aggregate((x, y) => x + "," + y));
            Console.WriteLine(test3.Select(x => x.ToString()).Aggregate((x, y) => x + "," + y));
        }
Example #15
0
        public void CollectionsAreUnioned()
        {
            var typeMapper = Mapper.CreateMapper<T1, T2>();
            typeMapper.Collection(t => t.IntCollection, () => new List<int>(), null).MapsTo(t => t.LongCollection, () => new List<long>(), null);

            var ints = new[] { 1, 2, 3 };
            var longs = new[] { 1L, 2L, 4L };
            T1 t1 = new T1() { IntCollection = ints };
            T2 t2 = new T2() { LongCollection = longs };
            Mapper.Map(t1, t2);

            var longUnion = longs.Union(ints.Select(i => (long)i));

            Assert.IsTrue(t2.LongCollection.SequenceEqual(longUnion));
        }
        public void InterfacesContainedInClassesNameAreBound()
        {
            var type = typeof(MultipleInterfaceCrazyService);
            var expectedInterfaces = new[]
                {
                    typeof(ICrazyService),
                    typeof(IMultipleInterfaceCrazyService), 
                    typeof(IService),
                    typeof(IService<int>),
                };
            var unexpectedInterfaces = new[] { typeof(IFoo), typeof(IBar) };
            var allInterfaces = expectedInterfaces.Union(unexpectedInterfaces).OrderBy(t => t.Name);
            this.bindableInterfaceSelectorMock.Setup(s => s.GetBindableInterfaces(type)).Returns(allInterfaces);

            this.testee.CreateBindings(type, this.kernelMock.Object).ToList();

            this.multiBindingCreatorMock.Verify(mbc => mbc.CreateBindings(
                this.kernelMock.Object,
                It.Is<IEnumerable<Type>>(t => t.SequenceEqual(expectedInterfaces)),
                type));
        }
        public void ProcessRequest(HttpContext context)
        {
            if (context.Session["Authentication"] == null)
                throw new Exception("Ошибка обновления");

            var shopId = Convert.ToInt32(context.Session["ShopId"]);
            var articleId = Convert.ToInt32(context.Request["articleId"]);

            using (var dc = new ReceiptClassDataContext(LocalService.LocalDBService.GetConnectionString()))
            {
                var info = dc.Склад_подробноs
                    .Single(x => x.Код == articleId);

                var q = dc.Склад_характеристикиs
                    .Where(s => s.Код_артикула == articleId)
                    .OrderBy(s => s.Характеристики.Название)
                    .Select(
                        s => new
                        {
                            Характеристика = s.Характеристики.Название,
                            Значение = dc.Характеристики_получить_строку(s.Код_характеристики, s.Код_значения)
                        })
                    .ToList()
                    .Select(x => new JProperty(x.Характеристика, x.Значение));

                var list =
                    new[]
                        {
                            new JProperty("Артикул", info.Артикул),
                            new JProperty("Описание", info.Описание),
                            new JProperty("Вид товара", info.Вид_товара),
                            new JProperty("Производитель", info.Производитель)
                            //new JProperty("Поставщик", info.Поставщик)
                        };

                var jObject = new JObject(list.Union(q));
                context.Response.ContentType = "application/json";
                context.Response.Write(jObject.ToString());
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="WordNetFileProvider"/> class.
        /// </summary>
        /// <param name="dataPath">The data path.</param>
        /// <exception cref="System.ArgumentNullException">dataPath</exception>
        /// <exception cref="System.IO.DirectoryNotFoundException">The data directory does not exist.</exception>
        /// <exception cref="System.IO.FileNotFoundException">A required WordNet file does not exist: [filename]</exception>
        public WordNetFileProvider(string dataPath) {
            if (string.IsNullOrEmpty(dataPath))
                throw new ArgumentNullException("dataPath");

            var dir = new DirectoryInfo(dataPath);

            if (!dir.Exists)
                throw new DirectoryNotFoundException("The data directory does not exist.");


            var dataPaths = new [] {
                new FileInfo(Path.Combine(dataPath, "data.adj")),
                new FileInfo(Path.Combine(dataPath, "data.adv")),
                new FileInfo(Path.Combine(dataPath, "data.noun")),
                new FileInfo(Path.Combine(dataPath, "data.verb"))
            };

            var indexPaths = new [] {
                new FileInfo(Path.Combine(dataPath, "index.adj")),
                new FileInfo(Path.Combine(dataPath, "index.adv")),
                new FileInfo(Path.Combine(dataPath, "index.noun")),
                new FileInfo(Path.Combine(dataPath, "index.verb"))
            };

            foreach (var file in dataPaths.Union(indexPaths).Where(file => !file.Exists))
                throw new FileNotFoundException("A required WordNet file does not exist: " + file.Name);

            index = new Dictionary<WordNetPos, Index>(4);
            foreach (var info in indexPaths) {
                index[GetFilePos(info.FullName)] = new Index(info);
            }

            data = new Dictionary<WordNetPos, StreamReader>(4);
            foreach (var info in dataPaths) {
                data[GetFilePos(info.FullName)] = new StreamReader(info.FullName);
            }
        }
Example #19
0
 public void CanDoUnionOnSingleItem()
 {
     var seq = new[] { 1, 2, 3 };
     seq.Union(4).Should().Have.SameSequenceAs(1, 2, 3, 4);
 }
Example #20
0
            public void ShouldAddReferenceToEachDestinationFile([Frozen] Mock<IScriptEngine> scriptEngine, [Frozen] Mock<IFileSystem> fileSystem,
                                                                                            [Frozen] Mock<IFilePreProcessor> preProcessor, ScriptExecutor scriptExecutor)
            {
                // arrange
                var defaultReferences = ScriptExecutor.DefaultReferences;
                preProcessor.Setup(x => x.ProcessFile(It.IsAny<string>())).Returns(new FilePreProcessorResult());

                var currentDirectory = @"C:\";
                var destinationFilePath1 = Path.Combine(currentDirectory, @"bin\fileName1.cs");
                var destinationFilePath2 = Path.Combine(currentDirectory, @"bin\fileName2.cs");
                var destinationFilePath3 = Path.Combine(currentDirectory, @"bin\fileName3.cs");
                var destinationFilePath4 = Path.Combine(currentDirectory, @"bin\fileName4.cs");

                var scriptName = "script.csx";

                fileSystem.Setup(fs => fs.CurrentDirectory).Returns(currentDirectory);
                fileSystem.Setup(fs => fs.GetWorkingDirectory(It.IsAny<string>())).Returns(currentDirectory);

                var destPaths = new string[] { "System", "System.Core", destinationFilePath1, destinationFilePath2, destinationFilePath3, destinationFilePath4 };

                scriptEngine.Setup(e => e.Execute(It.IsAny<string>(), It.IsAny<string[]>(), It.IsAny<AssemblyReferences>(), It.IsAny<IEnumerable<string>>(), It.IsAny<ScriptPackSession>()));

                scriptExecutor.AddReferences("a");
                scriptExecutor.AddReferences(new[] { "a", "a", "b", "c", "d" });
                scriptExecutor.AddReference<FactAttribute>();
                scriptExecutor.AddReferences(typeof(TheInitializeMethod));
                var explicitReferences = new[] { "a", "b", "c", "d", typeof(FactAttribute).Assembly.Location, typeof(TheInitializeMethod).Assembly.Location };

                // act
                scriptExecutor.Initialize(destPaths, Enumerable.Empty<IScriptPack>());
                scriptExecutor.Execute(scriptName);

                // assert
                scriptEngine.Verify(e => e.Execute(It.IsAny<string>(), It.IsAny<string[]>(), It.Is<AssemblyReferences>(x => x.PathReferences.SequenceEqual(defaultReferences.Union(explicitReferences.Union(destPaths)))), It.IsAny<IEnumerable<string>>(), It.IsAny<ScriptPackSession>()), Times.Once());
            }
        public void WhereFiltersNoneMatchingTypes()
        {
            var expectedTypes = new[] { typeof(int), typeof(object) };
            var types = expectedTypes.Union(new[] { typeof(DefaultConvention) });
            var generatorMock = new Mock<IBindingGenerator>();

            this.SetupTypeFilterGetTypes(types);

            this.testee.SelectAllTypesFrom(new Assembly[0]);
            this.testee.Where(t => t.FullName.StartsWith("System."));
            this.testee.BindWith(generatorMock.Object);

            this.VerifyAllBindingsCreated(expectedTypes, generatorMock);
        }
Example #22
0
        /// <summary>
        /// Visit the given context and return a collection of the resultant contexts.
        /// </summary>
        /// <returns>Zero or more <see cref="IRenderingContext"/> instances, determined by the outcome of this visit.</returns>
        /// <param name="context">The rendering context to visit.</param>
        public override IRenderingContext[] Visit(IRenderingContext context)
        {
            if(context == null)
              {
            throw new ArgumentNullException(nameof(context));
              }

              IEnumerable<IRenderingContext>
            output = new [] { context },
            newlyExposedElements = new RenderingContext[0];

              var macroAttribute = context.Element.GetMetalAttribute(ZptConstants.Metal.DefineMacroAttribute);
              if(macroAttribute != null)
              {
            context.TalModel.AddLocal(MACRONAME, macroAttribute.Value);
              }

              foreach(var handler in _handlers)
              {
            var handlingResult = new HashSet<AttributeHandlingResult>();

            foreach(var ctx in output)
            {
              var processedBatch = handler.Handle(ctx);
              handlingResult.Add(processedBatch);
            }

            newlyExposedElements = newlyExposedElements.Union(handlingResult.SelectMany(x => x.NewlyExposedContexts));
            output = handlingResult.Where(x => x.ContinueHandling).SelectMany(x => x.Contexts).ToArray();
              }

              output = output.Union(newlyExposedElements.SelectMany(x => this.Visit(x)));

              return output.ToArray();
        }
        /// <summary>
        /// Recursively gathers the list of all properties which depend
        /// on the provided property, whether directly or indirectly.
        /// Each dependent property will only be included once, so
        /// multiple or circular dependencies will not result in multiple
        /// <see cref="INotifyPropertyChanged.PropertyChanged"/> events.
        /// </summary>
        /// <param name="targetType">The object in which the properties reside.</param>
        /// <param name="propertyName">
        /// The name of the property for which to collect all dependent properties.
        /// </param>
        /// <returns>
        /// Returns the list of all properties which are directly or
        /// indirectly dependent on the original property.
        /// </returns>
        public static IEnumerable<PropertyInfo> GetAllDependants(Type targetType, string propertyName)
        {
            //Retrieve the Property Info for the specified property
            var propertyInfo = targetType.GetRuntimeProperties()
                .First(x => x.Name == propertyName);

            IEnumerable<PropertyInfo> oldResults = null;
            IEnumerable<PropertyInfo> results = new[] { propertyInfo };
            do
            {
                oldResults = results;

                var dependancies = from input in results
                                   from dependancy in GetDirectDependants(targetType, input.Name)
                                   select dependancy;

                //Create union of current results with "new" results,
                //making sure to remove duplicates
                results = results.Union(dependancies)
                    .GroupBy((x) => x.Name)
                    .Select(grp => grp.First());
            }
            while (results.Count() > oldResults.Count());

            //Return results not including the original property name
            return results.Where(x => (x.Name != propertyName));
        }
        public void AllBindableCBaseClassesAndServicesArePassedToTheSelector()
        {
            Type givenType = null;
            IEnumerable<Type> givenServiceTypes = null;
            var type = typeof(MultipleInterfaceCrazyService);
            var interfaces = new[] { typeof(IFoo), typeof(IBar), typeof(IService) };
            var baseClasses = new[] { typeof(IService<>), typeof(object) };
            
            this.bindableInterfaceSelectorMock.Setup(s => s.GetBindableInterfaces(type)).Returns(interfaces);
            this.bindableInterfaceSelectorMock.Setup(s => s.GetBindableBaseTypes(type)).Returns(baseClasses);

            var testee = this.bindingGeneratorFactory.CreateSelectorBindingGenerator(
                (implementationType, serviceTypes) =>
                {
                    givenServiceTypes = serviceTypes;
                    givenType = implementationType;
                    return new Type[0];
                });
            testee.CreateBindings(type, this.kernelMock.Object).ToList();

            givenType.Should().Be(type);
            givenServiceTypes.Should().BeEquivalentTo(interfaces.Union(baseClasses));
        }
Example #25
0
 public void UnionTest()
 {
     string[] k1 = new[] {"aa", "bb"};
     string[] k2 = new[] { "bb", "cc" };
     Trace.WriteLine(string.Join(",",k1.Union(k2)));
 }
Example #26
0
        public void Use_RFC_3986_Encoding_For_Auth_Signature_Base()
        {
            // reserved characters for 2396 and 3986
            var reserved2396Characters = new[] { ";", "/", "?", ":", "@", "&", "=", "+", "$", "," }; // http://www.ietf.org/rfc/rfc2396.txt
            var additionalReserved3986Characters = new[] { "!", "*", "'", "(", ")" };  // http://www.ietf.org/rfc/rfc3986.txt
            var reservedCharacterString = string.Join(string.Empty, reserved2396Characters.Union(additionalReserved3986Characters));

            // act
            var escapedString = OAuthTools.UrlEncodeRelaxed(reservedCharacterString);

            // assert
            Assert.Equal("%3B%2F%3F%3A%40%26%3D%2B%24%2C%21%2A%27%28%29", escapedString);
        }
        public void Run()
        {
            var fileSystem = A.Fake<IFileSystem>();
            var task = A.Fake<IncrementVersionNumbersInFiles>(x=>x.Wrapping(new IncrementVersionNumbersInFiles()));
            var goodData = new Dictionary<string, object>
                               {
                                   { "WorkingDirectory",""},
                                   {"CurrentVersion",new Version("3.0.0.0")},
                                   {"CurrentReleaseVersion",new Version("3.0.0.0")},
                                   {"CurrentTestVersion",new Version("3.0.0.0")},
                                   {"NewVersion", new Version("3.0.0.1")},
                                   {"Mode", "test"}
                               };

            var badData1 = new Dictionary<string, object>
                               {
                                   {"CurrentVersion",new Version("3.0.0.0")},
                                   {"NewVersion", new Version("3.0.0.1")},
                                   {"Mode", "test"}
                               };

            var badData2 = new Dictionary<string, object>
                               {
                                   {"CurrentVersion",new Version("3.0.0.0")},
                                   {"CurrentReleaseVersion",new Version("3.0.0.0")},
                                   {"NewVersion", new Version("3.0.0.1")},
                                   {"Mode", "test"}
                               };
            var badData3 = new Dictionary<string, object>
                               {
                                   { "WorkingDirectory",""},
                                   {"CurrentReleaseVersion",new Version("3.0.0.0")},
                                   {"NewVersion", new Version("3.0.0.1")},
                                   {"Mode", "test"}
                               };
            var badData4 = new Dictionary<string, object>
                               {
                                   { "WorkingDirectory",""},
                                   {"CurrentReleaseVersion",new Version("3.0.0.0")},
                                   {"CurrentVersion",new Version("3.0.0.0")},
                                   {"Mode","test"}
                               };
            var badData5 = new Dictionary<string, object>
                               {
                                   { "WorkingDirectory",""},
                                   {"CurrentVersion",new Version("3.0.0.0")},
                                   {"CurrentReleaseVersion",new Version("3.0.0.0")},
                                   {"NewVersion", new Version("3.0.0.1")},
                                   {"Mode", "test"}
                               };
            var goodContext = A.Fake<ITaskContext>(x=>x.Wrapping(new TaskContext(A.Fake<ILog>(),fileSystem,goodData)));
            var badContext2 = A.Fake<ITaskContext>(x=>x.Wrapping(new TaskContext(A.Fake<ILog>(),fileSystem,badData2)));
            var badContext3 = A.Fake<ITaskContext>(x=>x.Wrapping(new TaskContext(A.Fake<ILog>(),fileSystem,badData3)));
            var badContext4 = A.Fake<ITaskContext>(x=>x.Wrapping(new TaskContext(A.Fake<ILog>(),fileSystem,badData4)));
            var badContext5 = A.Fake<ITaskContext>(x=>x.Wrapping(new TaskContext(A.Fake<ILog>(),fileSystem,badData5)));

            var goodFiles = new[] { "c:\\asdf.txt", "c:\\face\\asdf.txt", "c:\\face\\brains\\asdf.txt" };
            var badFiles = new[] { "c:\\face.txt", "c:\\face2\\asdf.txt", "c:\\face","c:\\asdf" };

            A.CallTo(() => task.GetUpdateFiles(A<ITaskContext>.Ignored)).Returns(goodFiles);
            A.CallTo(
                () =>
                task.ProcessFile(A<ITaskContext>.Ignored, A<FileInfoBase>.Ignored, A<string>.Ignored, A<string>.Ignored, A<string>.Ignored, A<string>.Ignored)).DoesNothing();

            // Good data, grabs all files
            A.CallTo(
                () => fileSystem.Directory.GetFiles(A<string>.Ignored, A<string>.Ignored, SearchOption.AllDirectories))
             .Returns(goodFiles);
            Assert.DoesNotThrow(() => task.Run(this, goodContext));
            A.CallTo(
                () =>
                task.ProcessFile(A<ITaskContext>.Ignored, A<FileInfoBase>.Ignored, A<string>.Ignored, A<string>.Ignored, A<string>.Ignored, A<string>.Ignored))
                .MustHaveHappened(Repeated.Exactly.Times(3));

            // Inject bad files
            A.CallTo(
                () => fileSystem.Directory.GetFiles(A<string>.Ignored, A<string>.Ignored, SearchOption.AllDirectories))
             .Returns(goodFiles.Union(badFiles).ToArray());
            Assert.DoesNotThrow(() => task.Run(this, goodContext));
            A.CallTo(
                () =>
                task.ProcessFile(A<ITaskContext>.Ignored, A<FileInfoBase>.Ignored, A<string>.Ignored, A<string>.Ignored, A<string>.Ignored, A<string>.Ignored))
                .MustHaveHappened(Repeated.Exactly.Times(6));

            // bad data 1
            A.CallTo(
                () => fileSystem.Directory.GetFiles(A<string>.Ignored, A<string>.Ignored, SearchOption.AllDirectories))
             .Returns(goodFiles);
            Assert.Throws<KeyNotFoundException>(() => task.Run(this, badContext2));
            A.CallTo(
                () =>
                task.ProcessFile(A<ITaskContext>.Ignored, A<FileInfoBase>.Ignored, A<string>.Ignored, A<string>.Ignored, A<string>.Ignored, A<string>.Ignored))
                .MustHaveHappened(Repeated.Exactly.Times(6));

            // bad data 2
            A.CallTo(
                () => fileSystem.Directory.GetFiles(A<string>.Ignored, A<string>.Ignored, SearchOption.AllDirectories))
             .Returns(goodFiles);
            Assert.Throws<KeyNotFoundException>(() => task.Run(this, badContext2));
            A.CallTo(
                () =>
                task.ProcessFile(A<ITaskContext>.Ignored, A<FileInfoBase>.Ignored, A<string>.Ignored, A<string>.Ignored, A<string>.Ignored, A<string>.Ignored))
                .MustHaveHappened(Repeated.Exactly.Times(6));

            // bad data 3
            A.CallTo(
                () => fileSystem.Directory.GetFiles(A<string>.Ignored, A<string>.Ignored, SearchOption.AllDirectories))
             .Returns(goodFiles);
            Assert.Throws<KeyNotFoundException>(() => task.Run(this, badContext3));
            A.CallTo(
                () =>
                task.ProcessFile(A<ITaskContext>.Ignored, A<FileInfoBase>.Ignored, A<string>.Ignored, A<string>.Ignored, A<string>.Ignored, A<string>.Ignored))
                .MustHaveHappened(Repeated.Exactly.Times(6));

            // bad data 4
            A.CallTo(
                () => fileSystem.Directory.GetFiles(A<string>.Ignored, A<string>.Ignored, SearchOption.AllDirectories))
             .Returns(goodFiles);
            Assert.Throws<KeyNotFoundException>(() => task.Run(this, badContext4));
            A.CallTo(
                () =>
                task.ProcessFile(A<ITaskContext>.Ignored, A<FileInfoBase>.Ignored, A<string>.Ignored, A<string>.Ignored, A<string>.Ignored, A<string>.Ignored))
                .MustHaveHappened(Repeated.Exactly.Times(6));

            // bad data 4
            A.CallTo(
                () => fileSystem.Directory.GetFiles(A<string>.Ignored, A<string>.Ignored, SearchOption.AllDirectories))
             .Returns(goodFiles);
            Assert.Throws<KeyNotFoundException>(() => task.Run(this, badContext5));
            A.CallTo(
                () =>
                task.ProcessFile(A<ITaskContext>.Ignored, A<FileInfoBase>.Ignored, A<string>.Ignored, A<string>.Ignored, A<string>.Ignored, A<string>.Ignored))
                .MustHaveHappened(Repeated.Exactly.Times(6));
        }
        private string createPatch(string path, out UrlAnalyzeResult analyzeResult)
        {
            string originUrl = "http://github.com/" + path;
            analyzeResult = urlAnalyzer().Analyze(new Uri(originUrl));

            string originDiffUrl = analyzeResult.CompareUrl + ".diff";

            string patchContents;
            patchContents = new WebClient().DownloadString(originDiffUrl);

            var lines = new[]
                            {
                                "Online: " + analyzeResult.PermaLink,
                                "Download: " + analyzeResult.DownloadUrl,
                                "View: " + analyzeResult.ViewUrl,
                                "Based on r" + analyzeResult.SvnRevision + " in " + analyzeResult.SvnUrl,
                                "",
                                "Included commits:"
                            };

            var changes =
                analyzeResult.Changes.Select(
                    c => string.Format(" - {0} (by {1} on {2})", c.message, c.author.name + "<" + c.author.email + ">", c.authored_date))
                    .SelectMany(m => m.Replace("\n", "\n   ").Replace("\r", "").Split('\n'));

            lines = lines
                .Union(changes)
                .ToArray();

            var prependInfoHeader = new PrependInfoHeader(lines);
            IEnumerable<IConversionStep> steps = new IConversionStep[]
                                                     {
                                                         prependInfoHeader,
                                                         new RemoveLeadingFilePathStep(),
                                                         new InsertTortoiseSegmentationLineStep(),
                                                         new CorrectNullReferencesStep()
                                                     };

            patchContents = steps.Aggregate(patchContents,
                                            (current, conversionStep) => conversionStep.Convert(current));
            return patchContents;
        }
Example #29
0
 public void CanDoUnionOnTwoItems()
 {
     var seq = new[] { 1, 2, 3 };
     seq.Union(4, 6).Should().Have.SameSequenceAs(1, 2, 3, 4, 6);
 }
Example #30
0
        public LightsModule()
            : base("/lights/")
        {
            Get["/all/", true] = async (_, token) =>
              {
            var client = HueHelper.GetClient();

            var lights = await client.GetLightsAsync();

            var lightsData = from l in lights
                         let state = l.State
                         select new
                         {
                           id = l.Id,
                           name = l.Name,
                           state = new
                           {
                             brightness = state.Brightness,
                             @on = state.On,
                             saturation = state.Saturation,
                             hue = state.Hue,
                             hex = state.ToHex()
                           }
                         };

            var anyOn = lightsData.Any(l => l.state.on);

            var brightestLight = lightsData.Where(l => l.state.on).OrderByDescending(l => l.state.brightness).FirstOrDefault();

            var allLight = new[]
            {
              new
              {
            id = "all",
            name = "All",
            state = new
            {
              brightness = brightestLight != null ? brightestLight.state.brightness : (byte)0,
              @on = anyOn,
              saturation = brightestLight != null ? brightestLight.state.saturation : 0,
              hue = brightestLight != null ? brightestLight.state.hue : 0,
              hex = brightestLight != null ? brightestLight.state.hex : "000000"
            }
              }
            };

            var data = allLight.Union(lightsData);

            return data;
              };

              Post["/all/toggle", true] = async (_, token) =>
              {
            var client = HueHelper.GetClient();

            var lights = await client.GetLightsAsync();

            var anyOn = lights.Any(l => l.State.On);

            bool turnOff = anyOn;

            var command = new LightCommand();
            command.On = !turnOff;
            await client.SendCommandAsync(command, lights.Select(l => l.Id));

            var hub = GlobalHost.ConnectionManager.GetHubContext<LightsHub>();

            hub.Clients.All.lightsChanged();

            return new
            {
              success = true
            };
              };

              Post["/{id}/state/apply/", true] = async (p, token) =>
              {
            var data = this.Bind<StateData>();

            var client = HueHelper.GetClient();

            var id = (string)p.id;

            var command = new LightCommand();

            checked
            {
              command.Hue = data.Hue;
              command.Saturation = data.Saturation;
              command.Brightness = (byte?)data.Brightness;
              command.On = data.On;

              if (data.Hex != null)
              {
            command.SetColor(data.Hex);
              }

              if (id == "all")
              {
            await client.SendCommandAsync(command);
              }
              else
              {
            await client.SendCommandAsync(command, new[] { id });
              }
            }

            var hub = GlobalHost.ConnectionManager.GetHubContext<LightsHub>();

            hub.Clients.All.lightsChanged();

            return new
            {
              success = true
            };
              };
        }
Example #31
0
 public void CanDoUnionOnArrayOfItems()
 {
     var seq = new[] { 1, 2, 3 };
     var seq2 = new[] { 4, 5, 6 };
     seq.Union(seq2).Should().Have.SameSequenceAs(1, 2, 3, 4, 5, 6);
 }