Example #1
0
        public async Task<IEnumerable<Album>> AlbumsFromCommaSeparatedValuesAndUserId(string albumsAsCommaSeparatedValues, string userId)
        {
            if (string.IsNullOrWhiteSpace(albumsAsCommaSeparatedValues))
            {
                return Enumerable.Empty<Album>();
            }

            var albumsValues = new HashSet<string>();

            albumsAsCommaSeparatedValues.Split(new[] { GlobalConstants.CommaSeparatedCollectionSeparator }, StringSplitOptions.RemoveEmptyEntries)
                .ToList()
                .ForEach(val =>
                {
                    albumsValues.Add(val.Trim());
                });

            var resultAlbum = await this.albums
                .All()
                .Where(a => (albumsValues.Contains(a.Name.ToLower()) ||
                                albumsValues.Contains(a.Id.ToString())) &&
                            a.Creator.Id == userId)
                .ToListAsync();

            (await this.albums
              .All()
              .Where(a => (albumsValues.Contains(a.Name.ToLower()) ||
                                albumsValues.Contains(a.Id.ToString())) &&
                            a.Creator.Id == userId)
              .Select(a => a.Name.ToLower())
              .ToListAsync())
              .ForEach(a => albumsValues.Remove(a));

            var idValues = new List<string>();

            albumsValues.ForEach(v =>
            {
                int id;
                var isId = int.TryParse(v, out id);
                if (isId)
                {
                    idValues.Add(v);
                }
            });

            idValues.ForEach(a => albumsValues.Remove(a));

            albumsValues.ForEach(tagName => resultAlbum.Add(new Album() { Name = tagName }));

            return resultAlbum;
        }
Example #2
0
 /// <summary>
 /// 正しく読み込めた棋譜のリストを保存します。
 /// </summary>
 public static void SavePathList(string filepath, HashSet<string> pathList)
 {
     using (var writer = new StreamWriter(filepath, false, Encoding.UTF8))
     {
         pathList.ForEach(_ => writer.WriteLine(_));
     }
 }
Example #3
0
        public async Task<IEnumerable<Tag>> TagsFromCommaSeparatedValues(string tagsAsCommaSeparatedValues)
        {
            if (string.IsNullOrWhiteSpace(tagsAsCommaSeparatedValues))
            {
                return Enumerable.Empty<Tag>();
            }

            var tagNames = new HashSet<string>();

            tagsAsCommaSeparatedValues.Split(new[] { GlobalConstants.CommaSeparatedCollectionSeparator }, StringSplitOptions.RemoveEmptyEntries)
                .ToList()
                .ForEach(tag =>
                {
                    tagNames.Add(tag.ToLower().Trim());
                });

            var resultTags = await this.tags
                .All()
                .Where(t => tagNames.Contains(t.Name))
                .ToListAsync();

            (await this.tags
              .All()
              .Where(t => tagNames.Contains(t.Name.ToLower()))
              .Select(t => t.Name.ToLower())
              .ToListAsync())
              .ForEach(t => tagNames.Remove(t));

            tagNames.ForEach(tagName => resultTags.Add(new Tag { Name = tagName }));

            return resultTags;
        }
        private void OnServerTestingFinished(object sender, EventArgs e)
        {
            var hashset = new HashSet<MissingProduct>();
            this.manager.Cache.MissingProductsPerServer.Values.ForEach(hashset.UnionWith);

            this.MissingProducts.Clear();
            hashset.ForEach(this.MissingProducts.Add);
        }
        /**
         * RelationshipDiscoverer Constructor
         */
        public RelationshipDiscoverer(HashSet<Type> Models)
        {
            this.Discovered = new List<Relation>();

            // Loop through all models in the context.
            Models.ForEach(model =>
            {
                // Loop through all mapped props of the model
                Model.Dynamic(model).MappedProps.ForEach(prop =>
                {
                    // Ignore primative types.
                    if (TypeMapper.IsClrType(prop.PropertyType))
                    {
                        return;
                    }

                    // Get the relationship discriptor.
                    Relation? relation;

                    if (TypeMapper.IsListOfEntities(prop))
                    {
                        if ((relation = this.IsManyToMany(prop)) == null)
                        {
                            if ((relation = this.IsManyToOne(prop)) == null)
                            {
                                throw new UnknownRelationshipException(prop);
                            }
                        }
                    }
                    else
                    {
                        // Make sure the type is a Graceful Model.
                        // If this exception throws, it probably means the
                        // TypeMapper has failed us.
                        if (!prop.PropertyType.IsSubclassOf(typeof(Model)))
                        {
                            throw new UnknownRelationshipException(prop);
                        }

                        if ((relation = this.IsOneToMany(prop)) == null)
                        {
                            if ((relation = this.IsOneToOne(prop)) == null)
                            {
                                throw new UnknownRelationshipException(prop);
                            }
                        }
                    }

                    // Add it to our discovered list.
                    this.Discovered.Add((Relation)relation);
                });
            });
        }
Example #6
0
        void InitializeCategories(ISession session)
        {
            var categories = new HashSet<Category>
            {
                new Category {Name = "Backpacks", Description = "Backpacks"},
                new Category {Name = "Bikes", Description = "Bikes"},
                new Category {Name = "Boots", Description = "Boots"},
                new Category {Name = "Hats & Helmets", Description = "Hats & Helmets"},
                new Category {Name = "Hiking Gear", Description = "Hiking Gear"},
                new Category {Name = "Sunglasses", Description = "Sunglasses"}
            };

            categories.ForEach(category => session.Save(category));
            _categories = categories;
        }
 private void AddHighlightings()
 {
     var variables = new HashSet<IVariableDeclaration>();
     Graf.ReachableExits.ForEach(exit =>
     {
         var data = _elementDataStorage[exit.Source];
         if (data != null)
         {
             data.Status.ForEach(kvp =>
             {
                 if (kvp.Value == VariableDisposeStatus.NotDisposed || kvp.Value == VariableDisposeStatus.Both)
                     variables.Add(kvp.Key);
             });
         }
     });
     variables.ForEach(
         variableDeclaration =>
             _highlightings.Add(new HighlightingInfo(variableDeclaration.GetNameDocumentRange(),
                 new LocalVariableNotDisposed(variableDeclaration.DeclaredName))));
 }
Example #8
0
        public async Task<IEnumerable<Tag>> TagsFromCommaSeparatedValues(string tagsAsCommaSeparatedValues)
        {
            if (string.IsNullOrWhiteSpace(tagsAsCommaSeparatedValues))
            {
                return Enumerable.Empty<Tag>();
            }

            var existingTagIds = new HashSet<int>();
            var tagNames = new HashSet<string>();

            tagsAsCommaSeparatedValues.Split(new[] { TagSeparator }, StringSplitOptions.RemoveEmptyEntries)
                .ToList()
                .ForEach(tag =>
                {
                    int tagId;
                    if (int.TryParse(tag, out tagId))
                    {
                        existingTagIds.Add(tagId);
                    }
                    else
                    {
                        tagNames.Add(tag.ToLower());
                    }
                });

            var resultTags = await this.tags
                .All()
                .Where(t => existingTagIds.Contains(t.Id) || tagNames.Contains(t.Name))
                .ToListAsync();

            (await this.tags
                .All()
                .Where(t => tagNames.Contains(t.Name.ToLower()))
                .Select(t => t.Name.ToLower())
                .ToListAsync())
                .ForEach(t => tagNames.Remove(t));

            tagNames.ForEach(tagName => resultTags.Add(new Tag { Name = tagName, Type = TagType.UserSubmitted }));

            return resultTags;
        }
Example #9
0
        static void Main(string[] args)
        {
            var inputs = new List<CryptoHashInput>();
            var algorithms = new HashSet<CryptoHashAlgorithm>();

            var optionSet = new OptionSet
                {
                    { "h|?|help", s => PrintUsageAndExit() },
                    { "V|verbose", s => _verbose = true },
                    { "json", s => _json = true },
                    { "map", s => _map = true },
                    { "lower", s => _upper = false },
                    { "md5", s => algorithms.Add(new MD5Algorithm()) },
                    { "sha1", s => algorithms.Add(new SHA1Algorithm()) },
                    { "sha256", s => algorithms.Add(new SHA256Algorithm()) },
                    { "sha512", s => algorithms.Add(new SHA512Algorithm()) },
                };

            var paths = optionSet.Parse(args);

            if (!algorithms.Any())
            {
                algorithms.Add(new MD5Algorithm());
                algorithms.Add(new SHA1Algorithm());
                algorithms.Add(new SHA256Algorithm());
                algorithms.Add(new SHA512Algorithm());
            }

            algorithms.ForEach(algorithm => algorithm.UpperCase = _upper);

            var stdin = StdIn;
            if (stdin != null)
            {
                inputs.Add(new CryptoHashInput("stdin", stdin, algorithms));
            }

            inputs.AddRange(paths.Select(path => new CryptoHashInput(path, algorithms)));

            Print(inputs);
        }
Example #10
0
 void InitializeProducts(ISession session)
 {
     var products = new HashSet<Product>
     {
         new Product{Name = "Hiking Backpack", ProductCode = "Backpack1_1", Category = _categories.First(x => x.Name == "Backpacks"), Price = 50},
         new Product{Name = "Wide-base Backpack", ProductCode = "Backpack2_1", Category = _categories.First(x => x.Name == "Backpacks"), Price = 50},
         new Product{Name = "Short Backpack", ProductCode = "Backpack3_1", Category = _categories.First(x => x.Name == "Backpacks"), Price = 40},
         new Product{Name = "Mountaineering Backpack", ProductCode = "Backpack4_1", Category = _categories.First(x => x.Name == "Backpacks"), Price = 130},
         new Product{Name = "Sprint 500 Bike", ProductCode = "Bike1_1", Category = _categories.First(x => x.Name == "Bikes"), Price = 460},
         new Product{Name = "Escape 3.0 Bike", ProductCode = "Bike2_1", Category = _categories.First(x => x.Name == "Bikes"), Price = 680},
         new Product{Name = "Scoop Cruiser", ProductCode = "Bike3_1", Category = _categories.First(x => x.Name == "Bikes"), Price = 380},
         new Product{Name = "Sierra Leather Hiking Boots", ProductCode = "Boots1_1", Category = _categories.First(x => x.Name == "Boots"), Price = 90},
         new Product{Name = "Rainier Leather Hiking Boots", ProductCode = "Boots2_1", Category = _categories.First(x => x.Name == "Boots"), Price = 110},
         new Product{Name = "Cascade Fur-Lined Hiking Boots", ProductCode = "Boots3_1", Category = _categories.First(x => x.Name == "Boots"), Price = 130},
         new Product{Name = "Adirondak Fur-Lined Hiking Boots", ProductCode = "Boots4_1", Category = _categories.First(x => x.Name == "Boots"), Price = 60},
         new Product{Name = "Olympic Hiking Boots", ProductCode = "Boots5_1", Category = _categories.First(x => x.Name == "Boots"), Price = 90},
         new Product{Name = "Weathered Lether Baseball Cap", ProductCode = "Hat1_1", Category = _categories.First(x => x.Name == "Hats & Helmets"), Price = 13},
         new Product{Name = "Colorful Straw hat", ProductCode = "Hat2_1", Category = _categories.First(x => x.Name == "Hats & Helmets"), Price = 10},
         new Product{Name = "Summertime Straw Hat", ProductCode = "Hat3_1", Category = _categories.First(x => x.Name == "Hats & Helmets"), Price = 23},
         new Product{Name = "Bicycle Safety Helmet", ProductCode = "Helmet1_1", Category = _categories.First(x => x.Name == "Hats & Helmets"), Price = 80},
         new Product{Name = "Fusion Helmet", ProductCode = "Helmet2_1", Category = _categories.First(x => x.Name == "Hats & Helmets"), Price = 150},
         new Product{Name = "Fire Helmet", ProductCode = "Helmet3_1", Category = _categories.First(x => x.Name == "Hats & Helmets"), Price = 125},
         new Product{Name = "Bicycle Safety Helmet", ProductCode = "Helmet1_1", Category = _categories.First(x => x.Name == "Hats & Helmets"), Price = 80},
         new Product{Name = "Sentinel Locking Carbiner", ProductCode = "Carbiner1_1", Category = _categories.First(x => x.Name == "Hiking Gear"), Price = 16},
         new Product{Name = "Guardian Locking Carbiner", ProductCode = "Carbiner2_1", Category = _categories.First(x => x.Name == "Hiking Gear"), Price = 6},
         new Product{Name = "Trailhead Locking Carbiner", ProductCode = "Carbiner3_1", Category = _categories.First(x => x.Name == "Hiking Gear"), Price = 80},
         new Product{Name = "Traiguide Compass", ProductCode = "Compass1_1", Category = _categories.First(x => x.Name == "Hiking Gear"), Price = 30},
         new Product{Name = "Northstar Compass", ProductCode = "Compass2_1", Category = _categories.First(x => x.Name == "Hiking Gear"), Price = 18},
         new Product{Name = "Sundial Compass", ProductCode = "Compass3_1", Category = _categories.First(x => x.Name == "Hiking Gear"), Price = 12},
         new Product{Name = "Polar Start Compass", ProductCode = "Compass4_1", Category = _categories.First(x => x.Name == "Hiking Gear"), Price = 15},
         new Product{Name = "Compass Necklace", ProductCode = "Compass5_1", Category = _categories.First(x => x.Name == "Hiking Gear"), Price = 16},
         new Product{Name = "Battery Operated Flashlight", ProductCode = "Flashlight1_1", Category = _categories.First(x => x.Name == "Hiking Gear"), Price = 8},
         new Product{Name = "Heavy-Duty Flashlight", ProductCode = "Flashlight2_1", Category = _categories.First(x => x.Name == "Hiking Gear"), Price = 13},
         new Product{Name = "Retro Flashlight", ProductCode = "Flashlight3_1", Category = _categories.First(x => x.Name == "Hiking Gear"), Price = 24},
         new Product{Name = "Northwind Traders Arizona Sunglasses", ProductCode = "Sunglasses1_1", Category = _categories.First(x => x.Name == "Sunglasses"), Price = 35},
         new Product{Name = "Northwind Traders Eclipse Sunglasses", ProductCode = "Sunglasses2_1", Category = _categories.First(x => x.Name == "Sunglasses"), Price = 55},
     };
     products.ForEach(product => session.Save(product));
 }
Example #11
0
            /// <summary>
            /// Convert calls to methods marked with InlineAttribute.
            /// </summary>
            public void Convert(ReachableContext reachableContext)
            {
                this.reachableContext = reachableContext;

                // Collect all names
                var methodsWithBody = reachableContext.ReachableTypes.SelectMany(x => x.Methods).Where(m => m.HasBody).ToList();
                if (methodsWithBody.Count == 0)
                    return;

                // Find all methods marked with InlineAttribute
                var inlineMethods = new HashSet<MethodDefinition>(methodsWithBody.Where(x =>x.HasCustomAttributes &&
                        x.CustomAttributes.Any(c => (c.AttributeType.Name == AttributeConstants.InlineAttributeName) &&
                                                    (c.AttributeType.Namespace == AttributeConstants.Dot42AttributeNamespace))));
                if (inlineMethods.Count == 0)
                    return;

                // Prepare inline methods
                inlineMethods.ForEach(x => x.Body.SimplifyMacros());

                // Now inline all applicable calls
                var notAlwaysConverted = new HashSet<MethodDefinition>();
                foreach (var method in methodsWithBody)
                {
                    if (!inlineMethods.Contains(method))
                    {
                        Convert(method.Body, inlineMethods, notAlwaysConverted);
                    }
                }

                // Mark all methods that have been inlined in all calls not reachable.
                /*foreach (var method in inlineMethods)
                {
                    if (!notAlwaysConverted.Contains(method))
                    {
                        //method.SetNotReachable();
                    }
                }*/
            }
Example #12
0
 public void RemoteRouter_must_deploy_its_children_on_remote_host_driven_by_programmatic_definition()
 {
     var probe = CreateTestProbe(masterSystem);
     var router = masterSystem.ActorOf(new RemoteRouterConfig(
         new RoundRobinPool(2),
         new[] { new Address("akka.tcp", sysName, "127.0.0.1", port) })
         .Props(EchoActorProps), "blub2");
     var replies = CollectRouteePaths(probe, router, 5);
     var childred = new HashSet<ActorPath>(replies);
     childred.Should().HaveCount(2);
     childred.Select(x => x.Parent).Distinct().Should().HaveCount(1);
     childred.ForEach(x => x.Address.Should().Be(intendedRemoteAddress));
     masterSystem.Stop(router);
 }
        //private DependencyGraph Sample(DependencyGraph aGraph, List<OutputEntry> aWarnings, int percent)
        //{
        //    var rand = new Random();
        //    var selected = new HashSet<Library>(aWarnings.SelectMany(w => w.Projects)
        //        .Concat(aGraph.Vertices.Where(v => rand.Next(100) < percent)));
        //    var result = new DependencyGraph();
        //    result.AddVertexRange(selected);
        //    result.AddEdgeRange(aGraph.Edges.Where(e => selected.Contains(e.Source) && selected.Contains(e.Target)));
        //    return result;
        //}
        private string GenerateDot()
        {
            var result = new DotStringBuilder("Dependencies");

            result.AppendConfig("concentrate", "true");

            int clusterIndex = 1;

            foreach (var group in graph.Vertices.Where(a => a.GroupElement != null)
                .GroupBy(a => a.GroupElement.Name))
            {
                var groupName = @group.Key;
                var clusterName = "cluster" + clusterIndex++;

                var groupInfo = new GroupInfo(clusterName + "_top", clusterName + "_bottom");
                groupInfos.Add(groupName, groupInfo);

                result.StartSubgraph(clusterName);

                result.AppendConfig("label", groupName);
                result.AppendConfig("color", "lightgray");
                result.AppendConfig("style", "filled");
                result.AppendConfig("fontsize", "20");

                result.AppendSpace();

                AppendGroupNode(result, "min", groupInfo.TopNode);

                result.AppendSpace();

                var projs = new HashSet<Library>(group);

                projs.ForEach(a => AppendProject(result, a));

                result.AppendSpace();

                graph.Edges.Where(e => projs.Contains(e.Source) && projs.Contains(e.Target))
                    .ForEach(d => AppendDependency(result, d));

                result.AppendSpace();

                AppendGroupNode(result, "max", groupInfo.BottomNode);

                result.EndSubgraph();

                result.AppendSpace();
            }

            graph.Vertices.Where(a => a.GroupElement == null)
                .ForEach(a => AppendProject(result, a));

            result.AppendSpace();

            graph.Edges.Where(e => AreFromDifferentGroups(e.Source, e.Target))
                .ForEach(d => AppendDependency(result, d));

            result.AppendSpace();

            AddDependenciesBetweenGroups(result);

            return result.ToString();
        }
        /// <summary>
        /// Process the remainder of the beams
        /// </summary>
        /// <param name="Beams">The full list of beams to process</param>
        /// <param name="Members">The empty list of members</param>
        private void ProcessBeams(HashSet<Beam> Beams, HashSet<Member> Members)
        {
            int memberCount = Members.Count;
            double totalBeams = Beams.Count;

            // Process the remaining beams
            while (Beams.Any())
            {
                Beam currentBeam = Beams.First();
                Member newMember;

                List<Beam> beams;
                beams = GatherMemberBeams(currentBeam, false);
                beams.AddRange(GatherMemberBeams(currentBeam, true));
                beams = new HashSet<Beam>(beams).ToList();

                // Generate new member. This needs to be generated with the model beams and not with the cloned list!
                newMember = this.GenerateNewMember(++memberCount, this.StaadModel.Beams.Where(o => beams.Contains(o)).ToList());
                Members.Add(newMember);

                // Remove processed beam and node. This needs to be removed from the cloned list and not the model!
                beams.ForEach(b => Beams.Remove(b));

                // Fire status update event
                this.OnStatusUpdate(new MemberGeneratorStatusUpdateEventArgs("Generating members...", 1 - (Beams.Count / totalBeams), newMember));

                // Select the latest member if required
                if (SelectIndividualMembersDuringCreation)
                    this.StaadModel.Staad.Geometry.SelectMultipleBeams(newMember.Beams.Select(o => o.ID).ToArray());
            }
        }
        private void UpdateInstructorCourses(string[] selectedCourses, Instructor instructor)
        {
            if (selectedCourses == null)
            {
                var condition = new PredicateGroup { Operator = GroupOperator.And, Predicates = new List<IPredicate>() };

                condition.Predicates.Add(Predicates.Field<CourseInstructor>(s => s.InstructorId, Operator.Eq, instructor.InstructorId));

                instructor.Courses.ForEach(c =>
                {
                    condition.Predicates.Add(Predicates.Field<CourseInstructor>(s => s.CourseId, Operator.Eq, c.CourseId));
                });

                _connection.Delete<CourseInstructor>(condition);
            }
            else
            {
                var selectedCourseHs = new HashSet<string>(selectedCourses);
                var instructorCourses = new HashSet<int>(
                    instructor.Courses.Select(s => s.CourseId));

                var courseLst = new List<int>();

                selectedCourses.ToList().ForEach(s =>
                {
                    courseLst.Add(Convert.ToInt32(s));
                });

                instructorCourses.ForEach(s =>
                {
                    courseLst.Add(s);
                });

                foreach (var course in courseLst)
                {
                    if (selectedCourseHs.Contains(course.ToString()))
                    {
                        if (!instructorCourses.Contains(course))
                        {
                            var courseInstructor = new CourseInstructor
                            {
                                InstructorId = instructor.InstructorId,
                                CourseId = course
                            };
                            _connection.Insert(courseInstructor);
                        }
                    }
                    else
                    {
                        if (instructorCourses.Contains(course))
                        {
                            var condition = new PredicateGroup { Operator = GroupOperator.And, Predicates = new List<IPredicate>() };
                            condition.Predicates.Add(Predicates.Field<CourseInstructor>(f => f.InstructorId, Operator.Eq, instructor.InstructorId));
                            condition.Predicates.Add(Predicates.Field<CourseInstructor>(f => f.CourseId, Operator.Eq, course));
                            _connection.Delete<CourseInstructor>(condition);
                        }
                    }
                }
            }
        }
        public ActionResult Edit(CourseInputModel model)
        {
            if (model != null && ModelState.IsValid)
            {
                var currentUserId = this.UserProfile.Id;
                var updatedArticle = this.Mapper.Map<Course>(model);
                var imageUploader = new ImageUplouder();
                var images = new HashSet<Image>();
                string folderPath = Server.MapPath(WebConstants.ImagesMainPathMap + currentUserId);

                if (model.Files != null && model.Files.Count() > 0)
                {
                    foreach (var file in model.Files)
                    {
                        if (file != null
                            && (file.ContentType == WebConstants.ContentTypeJpg || file.ContentType == WebConstants.ContentTypePng)
                            && file.ContentLength < WebConstants.MaxImageFileSize)
                        {
                            images.Add(imageUploader.UploadImage(file, folderPath, currentUserId));
                        }
                    }
                }

                images.ForEach(x => updatedArticle.Images.Add(x));

                this.courses.Update(model.Id, updatedArticle);

                return this.RedirectToAction("Course", "School", new { area = "", id = model.Id });
            }

            return this.View(model);
        }
Example #17
0
        public void RemoteRouter_must_let_remote_deployment_be_overridden_by_remote_configuration()
        {
            var probe = CreateTestProbe(masterSystem);
            var router = masterSystem.ActorOf(
                new RoundRobinPool(2)
                .Props(EchoActorProps)
                .WithDeploy(new Deploy(new RemoteScope(intendedRemoteAddress))), "remote-override");

            router.Path.Address.Should().Be(intendedRemoteAddress);

            var replies = CollectRouteePaths(probe, router, 5);
            var childred = new HashSet<ActorPath>(replies);
            childred.Should().HaveCount(4);

            var parents = childred.Select(x => x.Parent).Distinct().ToList();
            parents.Should().HaveCount(1);
            parents.Head().Address.Should().Be(router.Path.Address);

            childred.ForEach(x => x.Address.Should().Be(intendedRemoteAddress));
            masterSystem.Stop(router);
        }
Example #18
0
        public void RemoteRouter_must_let_remote_deployment_be_overridden_by_local_configuration()
        {
            var probe = CreateTestProbe(masterSystem);
            var router = masterSystem.ActorOf(
                new RoundRobinPool(2)
                .Props(EchoActorProps)
                .WithDeploy(new Deploy(new RemoteScope(intendedRemoteAddress))), "local-blub");
            router.Path.Address.ToString().Should().Be(string.Format("akka://{0}", masterSystem.Name));

            var replies = CollectRouteePaths(probe, router, 5);
            var childred = new HashSet<ActorPath>(replies);
            childred.Should().HaveCount(2);

            var parents = childred.Select(x => x.Parent).Distinct().ToList();
            parents.Should().HaveCount(1);
            parents.Head().Address.Should().Be(new Address("akka.tcp", sysName, "127.0.0.1", port));

            childred.ForEach(x => x.Address.Should().Be(intendedRemoteAddress));
            masterSystem.Stop(router);
        }
Example #19
0
        public void RemoteRouter_must_deploy_remote_routers_based_on_configuration()
        {
            var probe = CreateTestProbe(masterSystem);
            var router = masterSystem.ActorOf(FromConfig.Instance.Props(EchoActorProps), "remote-blub");
            router.Path.Address.Should().Be(intendedRemoteAddress);

            var replies = CollectRouteePaths(probe, router, 5);
            var childred = new HashSet<ActorPath>(replies);
            childred.Should().HaveCount(2);

            var parents = childred.Select(x => x.Parent).Distinct().ToList();
            parents.Should().HaveCount(1);
            parents.Head().Should().Be(router.Path);

            childred.ForEach(x => x.Address.Should().Be(intendedRemoteAddress));
            masterSystem.Stop(router);
        }
Example #20
0
 public void RemoteRouter_must_deploy_its_children_on_remote_host_driven_by_configuration()
 {
     var probe = CreateTestProbe(masterSystem);
     var router = masterSystem.ActorOf(new RoundRobinPool(2).Props(EchoActorProps), "blub");
     var replies = CollectRouteePaths(probe, router, 5);
     var childred = new HashSet<ActorPath>(replies);
     childred.Should().HaveCount(2);
     childred.Select(x => x.Parent).Distinct().Should().HaveCount(1);
     childred.ForEach(x => x.Address.Should().Be(intendedRemoteAddress));
     masterSystem.Stop(router);
 }
        protected override async Task<HttpResponseMessage> SendAsync(
            HttpRequestMessage request,
            CancellationToken cancellationToken) {

            var resourceKey = GetResourceKey(request.RequestUri, _varyHeaders, request);
            CacheableEntity cacheableEntity = null;
            var cacheControlHeader = new CacheControlHeaderValue {
                Private = true,
                MustRevalidate = true,
                MaxAge = TimeSpan.FromSeconds(0)
            };

            if (request.Method == HttpMethod.Get) {

                var eTags = request.Headers.IfNoneMatch;
                var modifiedSince = request.Headers.IfModifiedSince;
                var anyEtagsFromTheClientExist = eTags.Any();
                var doWeHaveAnyCacheableEntityForTheRequest =
                    _eTagCacheDictionary.TryGetValue(resourceKey, out cacheableEntity);

                if (anyEtagsFromTheClientExist) {

                    if (doWeHaveAnyCacheableEntityForTheRequest) {
                        if (eTags.Any(x => x.Tag == cacheableEntity.EntityTag.Tag)) {

                            var tempResp = new  HttpResponseMessage(HttpStatusCode.NotModified);
                            tempResp.Headers.CacheControl = cacheControlHeader;
                            return tempResp;
                        }
                    }
                }
                else if (modifiedSince.HasValue) {

                    if (doWeHaveAnyCacheableEntityForTheRequest) {
                        if (cacheableEntity.IsValid(modifiedSince.Value)) {

                            var tempResp = new HttpResponseMessage(HttpStatusCode.NotModified);
                            tempResp.Headers.CacheControl = cacheControlHeader;
                            return tempResp;
                        }
                    }
                }
            }

            HttpResponseMessage response;
            try {

                response = await base.SendAsync(request, cancellationToken);
            }
            catch (Exception ex) {
                
                response = request.CreateErrorResponse(
                    HttpStatusCode.InternalServerError, ex);
            }

            if (response.IsSuccessStatusCode) {

                if (request.Method == HttpMethod.Get &&
                    !_eTagCacheDictionary.TryGetValue(resourceKey, out cacheableEntity)) { 

                    cacheableEntity = new CacheableEntity(resourceKey);
                    cacheableEntity.EntityTag = GenerateETag();
                    cacheableEntity.LastModified = DateTimeOffset.Now;

                    _eTagCacheDictionary.AddOrUpdate(
                        resourceKey, cacheableEntity, (k, e) => cacheableEntity);
                }

                if (request.Method == HttpMethod.Put || 
                    request.Method == HttpMethod.Post || 
                    request.Method == HttpMethod.Delete) {

                    HashSet<string> invalidCaches = new HashSet<string>();
                    invalidCaches.Add(GetRequestUri(request.RequestUri));

                    CacheInvalidationStore.ForEach(
                        func => func(GetRequestUri(request.RequestUri))
                            .ForEach(uri => invalidCaches.Add(uri)));

                    invalidCaches.ForEach(invalidCacheUri => {

                        var cacheEntityKeys = _eTagCacheDictionary.Keys.Where(
                            x => x.StartsWith(
                                string.Format("{0}:", invalidCacheUri), 
                                StringComparison.InvariantCultureIgnoreCase));

                        cacheEntityKeys.ForEach(key => {
                            if (!string.IsNullOrEmpty(key)) {

                                CacheableEntity outVal = null;
                                _eTagCacheDictionary.TryRemove(key, out outVal);
                            }
                        });
                    });
                }
                else {

                    response.Headers.CacheControl = cacheControlHeader;
                    response.Headers.ETag = cacheableEntity.EntityTag;
                    response.Content.Headers.LastModified = cacheableEntity.LastModified;

                    _varyHeaders.ForEach(
                        varyHeader => response.Headers.Vary.Add(varyHeader));
                }
            }

            return response;
        }
Example #22
0
        public static List<Node> LayOutSiblingNodes(ISet<Node> toBeGrouped)
        {
            if (toBeGrouped.Count <= 1)
                return toBeGrouped.ToList();
            var groupedNodes = new List<Node>();
            var hasBeenAdded = new HashSet<Node>();
            var nextGroupTarget = toBeGrouped;

            //Remove nodes that does not depend on anything and is never referenced
            var unreferenced = toBeGrouped.Where(x => !x.SiblingDependencies.Any()
                                                       && !toBeGrouped.SiblingDependencies().Contains(x)).ToHashSet();
            nextGroupTarget.ExceptWith(unreferenced);
            while (toBeGrouped.Any())
            {
                if (!nextGroupTarget.Any())
                {
                    nextGroupTarget = toBeGrouped;
                }
                while (nextGroupTarget.Any())
                {
                    var currentLayer = GetFacadeNodes(nextGroupTarget);
                    nextGroupTarget = currentLayer.SiblingDependencies().ToHashSet();
                    if (nextGroupTarget.Any())
                    {
                        //Get the next layer to check if any of the dependencies are unique to a node of the current layer
                        var nextLayer = GetFacadeNodes(nextGroupTarget);

                        //Check if any nodes that have not been added yet has dependencies on the unique ones, in this case they arent really unique
                        var leftForNextBatch = toBeGrouped.Except(currentLayer.Union(nextLayer));
                        nextLayer.RemoveAll(x => leftForNextBatch.SiblingDependencies().Contains(x));

                        var uniqueDependencies =
                            nextLayer.Where(x => !currentLayer.All(n => n.SiblingDependencies.Contains(x)))
                                .Distinct()
                                .ToList();

                        //If there are unique dependencies, vertical layers are created to separate the unique dependency from layers that dont depend on it
                        if (uniqueDependencies.Any())
                        {
                            while (true)
                            {
                                //Check if any nodes that have not been added yet has dependencies on the unique ones, in this case they arent really unique
                                leftForNextBatch = toBeGrouped.Except(currentLayer.Union(nextLayer));
                                nextLayer.RemoveAll(x => leftForNextBatch.Any(y => y.IndirectlyDependsOn(x)));
                                var groupsToCreate = FindDependencyPatterns(currentLayer, nextLayer);
                                var toBeShared = new HashSet<Node>();
                                toBeGrouped.ExceptWith(currentLayer);

                                foreach (var dependencyGroup in groupsToCreate)
                                {
                                    var referencers = dependencyGroup.Referencers;
                                    currentLayer.RemoveRange(referencers.ToList());
                                    var dependants = dependencyGroup.Dependants.ToList();
                                    nextGroupTarget.ExceptWith(dependants);
                                    toBeGrouped.ExceptWith(dependants);
                                    hasBeenAdded.UnionWith(dependants);
                                    hasBeenAdded.UnionWith(referencers);
                                    // Add dependant to the vertical layer
                                    var depNode = CreateHorizontalLayer(dependants);
                                    // Add references to the vertical layer
                                    var referenceNode = CreateHorizontalLayer(referencers);
                                    var newList = new List<Node> {depNode, referenceNode};
                                    //Get ALL the possible candidates for the vertical layer
                                    var verticalCandidates =
                                        referencers.SelectMany(x => x.IndirectSiblingDependencies())
                                            .Except(dependants)
                                            .Union(
                                                dependants.SelectMany(x => x.IndirectSiblingDependencies()))
                                            .Distinct()
                                            .Except(hasBeenAdded).Intersect(toBeGrouped)
                                            .ToHashSet();

                                    //Get all the nodes in this current call depth
                                    var otherGroups = groupsToCreate.Except(dependencyGroup);
                                    var nodesInOtherGroups = otherGroups.
                                        SelectMany(x => x.Dependants.Union(x.Referencers)).ToHashSet();
                                    var otherNodes =
                                        toBeGrouped.Union(currentLayer)
                                            .Union(nodesInOtherGroups)
                                            .Except(verticalCandidates)
                                            .ToHashSet();

                                    var siblingDepsRelevantForNewNode = new HashSet<Node>();
                                    //If any of the other nodes depends on the vertical candidate the candidate is removed and will be placed in a later iteration of this call (it is still left in toBeGrouped)
                                    foreach (var candidate in verticalCandidates.ToList())
                                    {
                                        var otherNodesDependantOnCandidate =
                                            otherNodes.Where(x => x.IndirectlyDependsOn(candidate)).ToHashSet();
                                        if (toBeShared.Contains(candidate) || otherNodesDependantOnCandidate.Any())
                                        {
                                            verticalCandidates.Remove(candidate);
                                            toBeShared.Add(candidate);
                                        }
                                    }

                                    if (verticalCandidates.Any())
                                    {
                                        toBeGrouped.ExceptWith(verticalCandidates);
                                        nextGroupTarget.ExceptWith(verticalCandidates);
                                        hasBeenAdded.UnionWith(verticalCandidates);

                                        var allDepsOfVerticalCandidates =
                                            verticalCandidates.SiblingDependencies().ToHashSet();
                                        siblingDepsRelevantForNewNode = allDepsOfVerticalCandidates;
                                        var dependenciesOfNestedNodes =
                                            allDepsOfVerticalCandidates.Intersect(verticalCandidates).ToHashSet();
                                        //Remove dependencies of nodes that are outside the new group that will be layouted
                                        foreach (var candidate in verticalCandidates)
                                            candidate.SiblingDependencies.RemoveWhere(
                                                x => !verticalCandidates.Contains(x));
                                        //Remove all nodes from this levels stack that should be added by the recursive call
                                        // If they dont at all depend on each other!!
                                        List<Node> newNodes;
                                        if (!dependenciesOfNestedNodes.Any())
                                            newNodes = new List<Node> {CreateHorizontalLayer(verticalCandidates)};
                                        else
                                            newNodes = GroupNodes(verticalCandidates);
                                        newList.InsertRange(0, newNodes);
                                    }
                                    siblingDepsRelevantForNewNode.UnionWith(
                                        referencers.Union(dependants).SiblingDependencies());
                                    siblingDepsRelevantForNewNode.ExceptWith(
                                        verticalCandidates.Union(referencers).Union(dependants));
                                    var verticalNode = new VerticalSiblingHolderNode(newList);
                                    siblingDepsRelevantForNewNode.ForEach(x => verticalNode.SiblingDependencies.Add(x));
                                    currentLayer.Add(verticalNode);
                                }
                                if (toBeShared.Any())
                                    nextLayer = GetFacadeNodes(nextGroupTarget);
                                else
                                    break;
                            }
                            nextGroupTarget = toBeGrouped;
                        }
                        else
                        {
                            toBeGrouped.ExceptWith(currentLayer);
                        }
                    }
                    else
                        toBeGrouped.ExceptWith(currentLayer);
                    groupedNodes.Add(CreateHorizontalLayer(currentLayer));
                }
            }
            //TODO: Add if only one layer
            //if (unreferenced.Any())
            //    newChildOrder.Add(CreateHorizontalLayer(unreferenced));

            groupedNodes.Reverse();
            return groupedNodes;
        }
Example #23
0
        public override void LoadModelParameters(string parameters)
        {
            var urlParser = new UrlParser(parameters);

            UpdateAvailableIndexes();
            ClearCurrentQuery();

            if (urlParser.GetQueryParam("mode") == "dynamic")
            {
                var collection = urlParser.GetQueryParam("collection");

                IsDynamicQuery = true;
                DatabaseCommands.GetTermsAsync("Raven/DocumentsByEntityName", "Tag", "", 100)
                    .ContinueOnSuccessInTheUIThread(collections =>
                    {
                        DynamicOptions.Match(new[] { "AllDocs" }.Concat(collections).ToArray());

                        string selectedOption = null;
                        if (!string.IsNullOrEmpty(collection))
                            selectedOption = DynamicOptions.FirstOrDefault(s => s.Equals(collection));

                        if (selectedOption == null)
                            selectedOption = DynamicOptions[0];

                        DynamicSelectedOption = selectedOption;
                        DocumentsResult.SetChangesObservable(null);
                    });

                return;
            }

            IsDynamicQuery = false;
            var newIndexName = urlParser.Path.Trim('/');

            if (string.IsNullOrEmpty(newIndexName))
            {
                if (AvailableIndexes.Any())
                {
                    NavigateToIndexQuery(AvailableIndexes.FirstOrDefault());
                    return;
                }
            }

            IndexName = newIndexName;

	        if (Database.Value.Statistics.Value.Errors.Any(error => error.Index == IndexName))
	        {
		        QueryErrorMessage.Value = "The index " + IndexName + " has errors";
		        IsErrorVisible.Value = true;
	        }

	        DatabaseCommands.GetIndexAsync(IndexName)
                .ContinueOnUIThread(task =>
                {
                    if (task.IsFaulted || task.Result == null)
                    {
                        if (AvailableIndexes.Any())
                        {

                            NavigateToIndexQuery(AvailableIndexes.FirstOrDefault());
                        }
                        else
                        {
                            NavigateToIndexesList();
                        }
                        return;
                    }

                    var fields = task.Result.Fields;
                    QueryIndexAutoComplete = new QueryIndexAutoComplete(fields, IndexName, QueryDocument);

	                var regex1 = new Regex(@"(?:SpatialIndex\.Generate|SpatialGenerate)");
	                var regex2 = new Regex(@"(?:SpatialIndex\.Generate|SpatialGenerate)\(@?\""([^\""]+)\""");

	                var strs = task.Result.Maps.ToList();
					if (task.Result.Reduce != null)
						strs.Add(task.Result.Reduce);
					
					var legacyFields = new HashSet<string>();
					foreach (var map in task.Result.Maps)
					{
						var count = regex1.Matches(map).Count;
						var matches = regex2.Matches(map).Cast<Match>().Select(x => x.Groups[1].Value).ToList();
						if (matches.Count < count)
							legacyFields.Add(Constants.DefaultSpatialFieldName);

						matches.ForEach(x => legacyFields.Add(x));
					}

					var spatialFields = task.Result.SpatialIndexes
						.Select(x => new SpatialQueryField
						{
							Name = x.Key,
							IsGeographical = x.Value.Type == SpatialFieldType.Geography,
							Units = x.Value.Units
						})
						.ToList();

					legacyFields.ForEach(x => spatialFields.Add(new SpatialQueryField
						{
							Name = x,
							IsGeographical = true,
							Units = SpatialUnits.Kilometers
						}));

					UpdateSpatialFields(spatialFields);

                    HasTransform = !string.IsNullOrEmpty(task.Result.TransformResults);

                    DocumentsResult.SetChangesObservable(
                        d => d.IndexChanges
                                 .Where(n =>n.Name.Equals(indexName,StringComparison.InvariantCulture))
                                 .Select(m => Unit.Default));
		
                    SetSortByOptions(fields);
                    RestoreHistory();
                }).Catch();


        }
Example #24
0
 public void RemoteRouter_must_deploy_dynamic_resizable_number_of_children_on_remote_host_driven_by_configuration()
 {
     var probe = CreateTestProbe(masterSystem);
     var router = masterSystem.ActorOf(FromConfig.Instance.Props(EchoActorProps), "elastic-blub");
     var replies = CollectRouteePaths(probe, router, 5);
     var childred = new HashSet<ActorPath>(replies);
     childred.Should().HaveCount(2);
     childred.Select(x => x.Parent).Distinct().Should().HaveCount(1);
     childred.ForEach(x => x.Address.Should().Be(intendedRemoteAddress));
     masterSystem.Stop(router);
 }