Example #1
0
        public IDictionary<ReleaseRepository, IEnumerable<GitLogEntity>> GetGitLog(IEnumerable<ReleaseRepository> repositories)
        {
            if (repositories.IsNullOrEmpty())
                return null;

            Log.DebugFormat("Starting connecting to Gerrit throught SSH");
            using (var sshClient = SshClientFactory())
            {
                sshClient.Connect();
                Log.DebugFormat("Connection to Gerrit established, starting executing command");

                var results = new ConcurrentDictionary<ReleaseRepository, IEnumerable<GitLogEntity>>();
                Parallel.ForEach(repositories, repository =>
                {
                    if (sshClient == null) return;

                    var command = string.Format(GitLogCommandTemplate, repository.Repository,
                        repository.ChangesFrom, repository.ChangesTo);
                    Log.DebugFormat("Executing command  [{0}]", command);

                    var result = sshClient.ExecuteCommand(command);

                    if (!string.IsNullOrWhiteSpace(result)
                        && !results.TryAdd(repository, GitLogParser.Parse(result)
                        .Where(x => x.CommitType == CommitType.Typical).ToArray())) { }

                    Log.DebugFormat("Finished executing command  [{0}]", command);
                });

                return results;
            }
        }
Example #2
0
        public Reference(int rowNum, IEnumerable<ReferenceFields> order, IEnumerable<string> values)
        {
            if (values.IsNullOrEmpty()) throw new ArgumentException("values");
            if (order.IsNullOrEmpty()) throw new ArgumentException("order");

            RowNum = rowNum;
            var vs = values.ToArray();
            var fs = order.ToArray();

            if (vs.Length != fs.Length) throw new InvalidOperationException();

            var fillErrors = new List<ReferenceFields>();

            for (var i = 0; i < vs.Length; i++)
            {
                try
                {
                    SetValue(fs[i], vs[i]);
                }
                catch
                {
                    fillErrors.Add(fs[i]);
                }
            }

            if (fillErrors.Any())
            {
                throw new Exception("Error reading following fields: {0}".
                    Fill(fillErrors.Cast<String>().CommaSeparated()));
            }
        }
Example #3
0
        public static void SetInvocationList(this EventInfo evt, Object host, IEnumerable<Delegate> chain)
        {
            var combo = chain.IsNullOrEmpty() ? null : 
                chain.Aggregate((agg, curr) => agg == null ? curr : Delegate.Combine(agg, curr));

            var f = evt.GetUnderlyingField().AssertNotNull();
            f.SetValue(host, combo);
        }
        public ISignatureBuilder Append(IEnumerable<byte> bytes)
        {
            if (bytes.IsNullOrEmpty()) throw new ArgumentNullException("bytes");

            _bytes = _bytes.Concat(bytes);

            return this;
        }
        public string ExecuteMultipartQuery(ITwitterQuery twitterQuery, string contentId, IEnumerable<byte[]> binaries)
        {
            if (binaries.IsNullOrEmpty())
            {
                return ExecuteQuery(twitterQuery);
            }

            return _webRequestExecutor.ExecuteMultipartQuery(twitterQuery, contentId, binaries);
        }
        public void IsNullOrEmpty_ThreeItemsCollection_ReturnsFalse(IEnumerable<object> threeItemsEnumerable)
        {
            // arrange

            // act

            // assert
            Assert.False(threeItemsEnumerable.IsNullOrEmpty());
        }
        public string GetTweetsQuery(IEnumerable<long> tweetIds)
        {
            if (tweetIds.IsNullOrEmpty())
            {
                return null;
            }

            var idsParameter = string.Join("%2C", tweetIds);
            return string.Format(Resources.Tweet_Lookup, idsParameter);
        }
Example #8
0
        public Params(IEnumerable<string> args, TextWriter outputWriter)
        {
            _outputWriter = outputWriter;

            var showHelp = false;
            var p = new OptionSet
                        {
                            { "s|source=", "Source Word document (*.doc[x] file)", v => SourceFile = v },
                            { "d|destination=", "Processed document name", v => DestFile = v },
                            { "r|references=", "References spreadsheet (*.xls[x] file)", v => RefFile = v },
                            { "o|order=", "Sort order for references (alpha|mention)", v => Order = v.GetEnumValueOrDefault<ReferenceOrder>() },
                            { "h|help", "Show this message and exit", v => showHelp = (v != null) }
                        };

            if (args.IsNullOrEmpty())
            {
                showHelp = true;
            }
            else
            {
                try
                {
                    p.Parse(args);
                }
                catch (OptionException e)
                {
                    WriteMessage(e.Message);
                    Ready = false;
                    return;
                }
            }

            if (showHelp)
            {
                ShowHelp(p);
                Ready = false;
                return;
            }

            var noSource = SourceFile.IsNullOrBlank();
            var noRef = RefFile.IsNullOrBlank();

            if (noSource || noRef)
            {
                if (noSource) WriteMessage("Source file not specified");
                if (noRef) WriteMessage("Reference file not specified");
                Ready = false;
                return;
            }

            if (DestFile.IsNullOrBlank()) DestFile = GetDestinationFileName(SourceFile);

            Ready = true;
        }
		/// <summary>
		/// Formats the specified list of <see cref="ICommandLineParserError"/> to a <see cref="System.String"/> suitable for the end user.
		/// </summary>
		/// <param name="parserErrors">The errors to format.</param>
		/// <returns>A <see cref="System.String"/> describing the specified errors.</returns>
		public string Format(IEnumerable<ICommandLineParserError> parserErrors)
		{
			if (parserErrors.IsNullOrEmpty()) return null;

			var builder = new StringBuilder();

			foreach (var error in parserErrors)
			{
				builder.AppendLine(Format(error));
			}

			return builder.ToString();
		}
Example #10
0
        public static bool ContainsAny(this string target, IEnumerable<string> strings)
        {
            if (target.IsNullOrEmpty() || strings.IsNullOrEmpty())
                return false;

            foreach (var s in strings)
            {
                if (target.Contains(s))
                    return true;
            }

            return false;
        }
Example #11
0
        public void AddCheckListQuestions(IEnumerable<BusinessCheckListQuestion> questions, Guid releaseWindowId)
        {
            if (questions.IsNullOrEmpty())
                return;

            CheckListQuestionRepository.Insert(questions
                .Select(x => new CheckListQuestion
                {
                    Content = x.Question,
                    ExternalId = x.ExternalId
                }));

            AssociateCheckListQuestionWithPackage(questions, releaseWindowId);
        }
Example #12
0
        /// <summary>
        /// Converts a LinkCategoryCollection into a single LinkCategory with its own LinkCollection.
        /// </summary>
        public static LinkCategory MergeLinkCategoriesIntoSingleLinkCategory(string title, CategoryType catType,
                                                                             IEnumerable<LinkCategory> links,
                                                                             BlogUrlHelper urlHelper, Blog blog)
        {
            if (!links.IsNullOrEmpty())
            {
                var mergedLinkCategory = new LinkCategory { Title = title };

                var merged = from linkCategory in links
                             select GetLinkFromLinkCategory(linkCategory, catType, urlHelper, blog);
                mergedLinkCategory.Links.AddRange(merged);
                return mergedLinkCategory;
            }

            return null;
        }
        /// <summary>
        /// The map from.
        /// </summary>
        /// <param name="userBlogs">
        /// The userBlogs.
        /// </param>
        /// <returns>
        /// The mapped blog user page view model.
        /// </returns>
        public BlogUserPageViewModel MapFrom(IEnumerable<Blog> userBlogs)
        {
            var model = new BlogUserPageViewModel
                {
                    Blogs = userBlogs
                        .ToList()
                        .MapAllUsing(this.blogSummaryViewModelMapper)
                        .OrderByDescending(x => x.CreationDate, new StringDateComparer())
                };

            if (!userBlogs.IsNullOrEmpty())
            {
                model.Author = userBlogs.First().Author.Username;
            }

            return model;
        }
Example #14
0
        private void PrintMethods(IEnumerable<MethodInfo> methods, string[] importedNamespaces)
        {
            if (!methods.IsNullOrEmpty())
            {
                _console.WriteLine("** Methods **");
                foreach (var method in methods)
                {
                    var methodParams = method.GetParametersWithoutExtensions()
                        .Select(p => string.Format("{0} {1}", GetPrintableType(p.ParameterType, importedNamespaces), p.Name));
                    var methodSignature = string.Format(" - {0} {1}({2})", GetPrintableType(method.ReturnType, importedNamespaces), method.Name,
                        string.Join(", ", methodParams));

                    _console.WriteLine(methodSignature);
                }
                _console.WriteLine();
            }
        }
        /// <summary>
        /// The map from.
        /// </summary>
        /// <param name="blogPosts">
        /// The input.
        /// </param>
        /// <returns>
        /// The mapped blog post archive page view model.
        /// </returns>
        public BlogPostArchivePageViewModel MapFrom(IEnumerable<BlogPost> blogPosts)
        {
            var model = new BlogPostArchivePageViewModel
                {
                    Results = blogPosts
                    .MapAllUsing(this.blogPostSummaryPageViewModelMapper)
                    .OrderByDescending(x => x.PostDate, new StringDateComparer()).ToList()
                };

            if (!blogPosts.IsNullOrEmpty())
            {
                var blog = blogPosts.First().Blog;
                model.ArchiveSectionViewModel = this.archiveSectionViewModelMapper.MapFrom(blog);
            }

            return model;
        }
        public JsonResult Save(HeroModel model, IEnumerable<HttpPostedFileBase> images) 
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var hero = new Hero();
                    var photos = new List<IPostedFile>();
                    Mapper.Map(model, hero);

                    if (!images.IsNullOrEmpty())
                    {
                        foreach (var image in images)
                        {
                            if (image.ContentLength > 0)
                            {
                                var file = new PostedFile(image);
                                if (image.FileName.Equals(model.Thumbnail, StringComparison.OrdinalIgnoreCase))
                                {
                                    file.Attributes.Add("IsThumbnail", "1");
                                }
                                file.Attributes.Add("FileName", string.Concat(Guid.NewGuid(), Path.GetExtension(image.FileName)));
                                photos.Add(file);
                            }
                        }
                    }
                    hero.UpdatedBy = AppUser.UserId;
                    if (model.IsNew)
                    {
                        hero.LanguageId = AppUser.LanguageId;
                        hero.HeroId = _heroRepository.CreateHero(hero, photos);
                    }
                    else
                    {
                        _heroRepository.UpdateHero(hero, photos);
                    }
                    return Json(new { Ok = true, HeroId = hero.HeroId });
                }
                catch (Exception)
                {                    
                }
            }
            return Json(new {Ok = false});
        }
Example #17
0
        public void AssociateCheckListQuestionWithPackage(IEnumerable<BusinessCheckListQuestion> questions, Guid releaseWindowId)
        {
            if (questions.IsNullOrEmpty())
                return;

            var window = ReleaseWindowRepository.GetSatisfiedBy(w => w.ExternalId == releaseWindowId);
            if (window == null)
                throw new EntityNotFoundException(typeof(ReleaseWindow), releaseWindowId);

            var packageIds = window.ReleaseProducts.Select(x => x.ProductId).ToArray();

            var questionExternalIds = questions.Select(x => x.ExternalId).ToArray();

            var dataQuestions = CheckListQuestionRepository
                .GetAllSatisfiedBy(c => questionExternalIds.Any(id => id == c.ExternalId))
                .ToArray();

            var questionsToAdd = packageIds.SelectMany(x => dataQuestions, (id, q) => new {PackageId = id, Question = q})
                .Where(x => !CheckListQuestionToProductRepository.Entities
                    .Any(c => c.ProductId == x.PackageId && c.CheckListQuestionId == x.Question.CheckListQuestionId))
                .Select(x => new CheckListQuestionToProduct
                {
                    ProductId = x.PackageId,
                    CheckListQuestionId = x.Question.CheckListQuestionId,
                })
                .ToArray();

            CheckListQuestionToProductRepository.Insert(questionsToAdd);

            var checkListItemsToAdd = (from bq in questions
                join dq in dataQuestions on bq.ExternalId equals dq.ExternalId
                where window.CheckList.All(x => x.CheckListQuestionId != dq.CheckListQuestionId)
                select new CheckList
                {
                    ExternalId = bq.CheckListId,
                    ReleaseWindowId = window.ReleaseWindowId,
                    CheckListQuestionId = dq.CheckListQuestionId,
                }).ToArray();

            CheckListRepository.Insert(checkListItemsToAdd);
        }
Example #18
0
    public bool HasUniqueKey(IEnumerable<string> keyNames)
    {
        Assert.IsTrue(!keyNames.IsNullOrEmpty(), "No key name");
        Assert.IsTrue(!keyNames.HasDuplication(), string.Format("Has duplicated keys in {0} \n {1}", filePath, keyNames.ToStringList(", ")));
        Assert.IsTrue(keyNames.All(x => columnInfo.ContainsKey(x)), string.Format("Has unknown key in {0} \n {1}", filePath, keyNames.ToStringList(", ")));

        var tempList = new List<RowData>(rows);
        return rows.All(delegate(RowData currRow)
        {
            bool result = tempList.Remove(currRow);
            Assert.IsTrue(result);
            IEnumerable<int> indexes = (from key in keyNames select columnInfo.IndexOf(key));
            bool notHaveSameKey = tempList.TrueForAll(x => !currRow.HasSameValueInAll(x, indexes));
            if (!notHaveSameKey)
            {
                List<RowData> errDatas = tempList.FindAll(x => currRow.HasSameValueInAll(x, indexes));
                Debug.LogError((from row in errDatas select row.Dump().RemoveWhiteSpace()).ToStringList("\n"));
            }
            return notHaveSameKey;
        });
    }
Example #19
0
        private static void ValidateReferences(IEnumerable<Reference> refs)
        {
            if (refs.IsNullOrEmpty())
            {
                throw new Exception("Got no references.");
            }

            var errorMessages = new List<string>();

            foreach (var reference in refs)
            {
                ICollection<string> errors;
                if (!ReferenceValidator.Validate(reference, out errors))
                {
                    errorMessages.Add("Row {0}: {1}".Fill(reference.RowNum, errors.SemicolonSeparated()));
                }
            }

            if(errorMessages.Any())
            {
                throw new Exception("Invalid records data found:\n" + errorMessages.JoinWith("\n"));
            }
        }
Example #20
0
 /// <summary>
 ///     Gets Or Adds a PropertyValue with the given label and collection.
 /// </summary>
 /// <param name="label"> </param>
 /// <param name="collections"> </param>
 /// <returns> </returns>
 public override PropertyValue GetPropertyValue(string label, IEnumerable<string> collections = null) {
     var result = _propertyValues.FirstOrDefault(each => each.Label == label);
     if (result == null) {
         _propertyValues.Add(result = new PropertyValue(this, label, collections.IsNullOrEmpty() ? null : collections));
     }
     return result;
 }
Example #21
0
        private IEnumerable<GraphDBType> GetTypes(DBContext myDBContext, IEnumerable<String> myTypes)
        {
            #region GetTypeToDump

            IEnumerable<GraphDBType> typesToDump;
            if (myTypes.IsNullOrEmpty())
            {
                typesToDump = myDBContext.DBTypeManager.GetAllTypes(false);
            }
            else
            {
                var typesToDumpHash = new HashSet<GraphDBType>();
                foreach (var stringType in myTypes)
                {
                    var type = myDBContext.DBTypeManager.GetTypeByName(stringType);
                    if (type == null)
                    {
                        throw new GraphDBException(new Errors.Error_TypeDoesNotExist(stringType));
                    }

                    //typesToDumpHash.UnionWith(myDBContext.DBTypeManager.GetAllParentTypes(type, true, false));
                    AddTypeAndAttributesRecursivly(myDBContext, type, ref typesToDumpHash);

                }
                typesToDump = typesToDumpHash;
            }

            #endregion

            return typesToDump;
        }
Example #22
0
        private bool TryGetAllItems(out IEnumerable<Stream> results)
        {
            string cacheKey = "aditi:gis:arm:data:stream-all";
            if (!cache.TryGet(cacheKey, out results))
            {
                CommonService<StreamModel, Stream> service = new CommonService<StreamModel, Stream>();
                results = service.GetList();
                if (results.IsNullOrEmpty())
                {
                    results = null;
                    return false;
                }

                cache.Set(cacheKey, results);
            }

            return true;
        }
Example #23
0
        private bool TryGetItemEmployees(long id, out IEnumerable<Employee> results)
        {
            string cacheKey = "aditi:gis:arm:data:stream-" + id.ToString() + "-employee";
            if (!cache.TryGet(cacheKey, out results))
            {
                JoinTableRepository<EmployeeModel, StreamModel> repository = new JoinTableRepository<EmployeeModel, StreamModel>();
                IEnumerable<EmployeeModel> employees = repository.GetLeft(id);
                results = AutoMapper.MapCollection<EmployeeModel, Employee>(employees);
                if (results.IsNullOrEmpty())
                {
                    results = null;
                    return false;
                }

                cache.Set(cacheKey, results, InMemoryCache.OneDay);
            }

            return true;
        }
Example #24
0
        public override Boolean RemoveUUID(IEnumerable<ObjectUUID> myObjectUUIDs)
        {
            if (!myObjectUUIDs.IsNullOrEmpty())
            {
                foreach (var aUUID in myObjectUUIDs)
                {
                    _ObjectUUIDs.Remove(aUUID);
                }

                return true;
            }

            return false;
        }
Example #25
0
        /// <summary>
        /// Select implementation. The public method automatically remaps a selector with the knowledge
        /// that the context is external (and not part of a chain)
        /// </summary>
        ///
        /// <exception cref="ArgumentNullException">
        /// Thrown when one or more required arguments are null.
        /// </exception>
        ///
        /// <param name="context">
        /// The context in which the selector applies. If null, the selector is run against the entire
        /// Document. If not, the selector is run against this sequence of elements.
        /// </param>
        ///
        /// <returns>
        /// A list of elements. This method returns a list (rather than a sequence) because the sequence
        /// must be enumerated to ensure that end-users don't cause the selector to be rerun repeatedly,
        /// and that the values are not mutable (e.g. if the underlying source changes).
        /// </returns>

        public IList<IDomObject> Select(IEnumerable<IDomObject> context)
        {
            // this holds the final output

            HashSet<IDomObject> output = new HashSet<IDomObject>();

            if (Selector == null )
            {
                throw new ArgumentNullException("The selector cannot be null.");
            }

            if (Selector.Count == 0)
            {
                return EmptyEnumerable().ToList();
            }

            ActiveSelectors = new List<SelectorClause>(Selector);

            // First just check if we ended up here with an HTML selector; if so, hand it off.
            
            var firstSelector = ActiveSelectors[0];
            if (firstSelector.SelectorType == SelectorType.HTML)
            {
                return CsQuery.Implementation.
                    DomDocument.Create(firstSelector.Html, HtmlParsingMode.Fragment)
                        .ChildNodes
                        .ToList();
            } 

            // this holds any results that carried over from the previous loop for chaining

            IEnumerable<IDomObject> lastResult = null;

            // this is the source from which selections are made in a given iteration; it could be the DOM
            // root, a context, or the previous result set. 
            
            IEnumerable<IDomObject> selectionSource=null;

            // Disable the index if there is no context (e.g. disconnected elements)
            // or if the first element is not indexed, or the context is not from the same
            // document as this selector is bound.

            bool useIndex = context.IsNullOrEmpty() || 
                (!context.First().IsDisconnected && context.First().IsIndexed && context.First().Document==Document);


            for (activeSelectorId = 0; activeSelectorId < ActiveSelectors.Count; activeSelectorId++)
            {

                var selector = ActiveSelectors[activeSelectorId].Clone();

                if (lastResult != null && 
                    (selector.CombinatorType == CombinatorType.Root || selector.CombinatorType == CombinatorType.Context))
                {
                    // we will alter the selector during each iteration to remove the parts that have already been
                    // parsed, so use a copy. This is a selector that was chained with the selector grouping
                    // combinator "," -- we always output the results so far when beginning a new group. 
                    
                    output.AddRange(lastResult);
                    lastResult = null;
                }

                // For "and" combinator types, we want to leave everything as it was -- the results of this
                // selector should compound with the prior. This is not an actual CSS combinator, this is the
                // equivalent of grouping parenthesis. That is, in CSS there's no way to say "(input[submit],
                // button):visible" - that is group the results on selector part and apply a filter to it. But
                // we need to do exactly this for certain selector types (for example the jQuery :button
                // selector). 

                if (selector.CombinatorType != CombinatorType.Grouped)
                {

                    selectionSource = GetSelectionSource(selector, context, lastResult);
                    lastResult = null;
                }
                
                string key = "";
                SelectorType removeSelectorType = 0;

                if (useIndex && !selector.NoIndex)
                {

#if DEBUG_PATH

                    if (selector.SelectorType.HasFlag(SelectorType.AttributeValue) 
                        && selector.AttributeSelectorType != AttributeSelectorType.NotExists
                        && selector.AttributeSelectorType != AttributeSelectorType.NotEquals)
                    {
                        key = "!" + selector.AttributeName.ToLower();

                        // AttributeValue must still be matched manually - so remove this flag only if the
                        // selector is conclusive without further checking
                        
                        if (selector.AttributeSelectorType == AttributeSelectorType.Exists)
                        {
                            removeSelectorType = SelectorType.AttributeValue;
                        }
                    }
                    else if (selector.SelectorType.HasFlag(SelectorType.Tag))
                    {
                        key = "+"+selector.Tag.ToLower();
                        removeSelectorType=SelectorType.Tag;
                    }
                    else if (selector.SelectorType.HasFlag(SelectorType.ID))
                    {
                        key = "#" + selector.ID;
                        removeSelectorType=SelectorType.ID;
                    }
                    else if (selector.SelectorType.HasFlag(SelectorType.Class))
                    {
                        key = "." + selector.Class;
                        removeSelectorType=SelectorType.Class;
                    }

#else
                    // We don't want to use the index for "NotEquals" selectors because a missing attribute
                    // is considered a valid match
                    
                    if (selector.SelectorType.HasFlag(SelectorType.AttributeValue)
                        && selector.AttributeSelectorType != AttributeSelectorType.NotExists
                        && selector.AttributeSelectorType != AttributeSelectorType.NotEquals)
                    {
                        key = "!" + (char)HtmlData.Tokenize(selector.AttributeName);

                        // AttributeValue must still be matched manually - so remove this flag only if the
                        // selector is conclusive without further checking
                        
                        if (selector.AttributeSelectorType == AttributeSelectorType.Exists)
                        {
                            removeSelectorType = SelectorType.AttributeValue;
                        }
                    }
                    else if (selector.SelectorType.HasFlag(SelectorType.Tag))
                    {
                        key = "+" + (char)HtmlData.Tokenize(selector.Tag);
                        removeSelectorType=SelectorType.Tag;
                    }
                    else if (selector.SelectorType.HasFlag(SelectorType.ID))
                    {
                        key = "#" + (char)HtmlData.TokenizeCaseSensitive(selector.ID);
                        removeSelectorType=SelectorType.ID;
                    }
                    else if (selector.SelectorType.HasFlag(SelectorType.Class))
                    {
                        key = "." + (char)HtmlData.TokenizeCaseSensitive(selector.Class);
                        removeSelectorType=SelectorType.Class;
                    }
#endif
                }

                // If part of the selector was indexed, key will not be empty. Return initial set from the
                // index. If any selectors remain after this they will be searched the hard way.

                IEnumerable<IDomObject> result = null;

                if (key != String.Empty)
                {
                    // This is the main index access point: if we have an index key, we'll get as much as we can from the index.
                    // Anything else will be handled manually.

                    int depth = 0;
                    bool descendants = true;
                    
                    switch (selector.TraversalType)
                    {
                        case TraversalType.Child:
                            depth = selector.ChildDepth;
                            descendants = false;
                            break;
                        case TraversalType.Filter:
                        case TraversalType.Adjacent:
                        case TraversalType.Sibling:
                            depth = 0;
                            descendants = false;
                            break;
                        case TraversalType.Descendent:
                            depth = 1;
                            descendants = true;
                            break;
                        // default: fall through with default values set above.
                    }
       
                    if (selectionSource == null)
                    {
                        result = Document.DocumentIndex.QueryIndex(key + HtmlData.indexSeparator, depth, descendants);
                    }
                    else
                    {
                        HashSet<IDomObject> elementMatches = new HashSet<IDomObject>();
                        result = elementMatches;

                        foreach (IDomObject obj in selectionSource)
                        {
                            elementMatches.AddRange(Document.DocumentIndex.QueryIndex(key + HtmlData.indexSeparator + obj.Path,
                                    depth, descendants));
                        }
                    }

                    selector.SelectorType &= ~removeSelectorType;

                    // Special case for attribute selectors: when Attribute Value attribute selector is present, we
                    // still need to filter for the correct value afterwards. But we need to change the traversal
                    // type because any nodes with the correct attribute type have already been selected. 
                    
                    if (selector.SelectorType.HasFlag(SelectorType.AttributeValue))
                    {
                        selector.TraversalType = TraversalType.Filter;
                    }
                    
                }
                else if (selector.SelectorType.HasFlag(SelectorType.Elements))
                {
                    HashSet<IDomObject> elementMatches = new HashSet<IDomObject>();
                    result = elementMatches;
                    foreach (IDomObject obj in GetAllChildOrDescendants(selector.TraversalType,selectionSource))
                    {

                        //key = HtmlData.indexSeparator + obj.Path;
                        HashSet<IDomObject> srcKeys = new HashSet<IDomObject>(Document.DocumentIndex.QueryIndex(HtmlData.indexSeparator + obj.Path));
                        foreach (IDomObject match in selector.SelectElements)
                        {
                            if (srcKeys.Contains(match))
                            {
                                elementMatches.Add(match);
                            }
                        }
                    }

                    selector.SelectorType &= ~SelectorType.Elements;
                }

                // If any selectors were not handled via the index, match them manually
                
                if (selector.SelectorType != 0)
                {
      
                    // if there are no temporary results (b/c there was no indexed selector) then use selection
                    // source instead (e.g. start from the same point that the index would have) 

                    result = GetMatches(result ?? selectionSource ?? Document.ChildElements, selector);
                }
                
                lastResult = lastResult == null ?
                    result : lastResult.Concat(result); 
                
            }

            // After the loop has finished, output any results from the last iteration.

            output.AddRange(lastResult);

            // Return the results as a list so that any user will not cause the selector to be run again
            
            return output.OrderBy(item => item.Path, StringComparer.Ordinal).ToList();

        }
Example #26
0
        public override bool RemoveUUID(IEnumerable<ObjectUUID> myObjectUUIDs)
        {
            if (!myObjectUUIDs.IsNullOrEmpty())
            {
                weightedSet.RemoveWhere(item => myObjectUUIDs.Contains(item.ObjectUUID));
                return false;
            }

            return false;
        }
Example #27
0
        //检查库存信息
        private static void CheckStock(IEnumerable<ProductColor> lstProductColor, DataRow drNew)
        {
            if (!lstProductColor.IsNullOrEmpty())
            {
                var settings = new JsonSerializerSettings();

                string result = JsonConvert.SerializeObject(lstProductColor, Formatting.Indented, settings);
                //需要注意的是,如果返回的是一个集合,那么还要在它的上面再封装一个类。否则客户端收到会出错的。
                //转回为对象
                //var pcList = JsonConvert.DeserializeObject<List<ProductColor>>(result);

                drNew["SKU"] = result;
                drNew["库存"] = lstProductColor.Sum(productColor => productColor.AvlNumForColor);
                drNew["售完"] = 0;
            }
            else
            {
                drNew["售完"] = 1;
                drNew["库存"] = 0;
            }
        }
        /// <summary>
        /// Select from DOM using index. First non-class/tag/id selector will result in this being passed off to GetMatches
        /// </summary>
        /// <param name="document"></param>
        /// <returns></returns>
        public IEnumerable<IDomObject> Select(IDomDocument document, IEnumerable<IDomObject> context)
        {
            if (Selectors == null )
            {
                throw new ArgumentException("No selectors provided.");
            }
            if (Selectors.Count == 0)
            {
                yield break;
            }
            Document = document;
            IEnumerable<IDomObject> lastResult = null;
            HashSet<IDomObject> output = new HashSet<IDomObject>();
            IEnumerable<IDomObject> selectionSource = context;

            // Disable the index if there is no context (e.g. disconnected elements)
            bool useIndex = context.IsNullOrEmpty() || !context.First().IsDisconnected;

            // Copy the list because it may change during the process
            ActiveSelectors = new List<Selector>(Selectors);

            for (activeSelectorId = 0; activeSelectorId < ActiveSelectors.Count; activeSelectorId++)
            {
                var selector = ActiveSelectors[activeSelectorId];
                CombinatorType combinatorType = selector.CombinatorType;
                SelectorType selectorType = selector.SelectorType;
                TraversalType traversalType = selector.TraversalType;

                // Determine what kind of combining method we will use with previous selection results

                if (activeSelectorId != 0)
                {
                    switch (combinatorType)
                    {
                        case CombinatorType.Cumulative:
                            // do nothing
                            break;
                        case CombinatorType.Root:
                            selectionSource = context;
                            if (lastResult != null)
                            {
                                output.AddRange(lastResult);
                                lastResult = null;
                            }
                            break;
                        case CombinatorType.Chained:
                            selectionSource = lastResult;
                            lastResult = null;
                            break;
                        // default (chained): leave lastresult alone
                    }
                }

                HashSet<IDomObject> tempResult = null;
                IEnumerable<IDomObject> interimResult = null;

                string key = "";
                if (useIndex && !selector.NoIndex)
                {

            #if DEBUG_PATH

                    if (type.HasFlag(SelectorType.Attribute))
                    {
                        key = "!" + selector.AttributeName;
                        type &= ~SelectorType.Attribute;
                        if (selector.AttributeValue != null)
                        {
                            InsertAttributeValueSelector(selector);
                        }
                    }
                    else if (type.HasFlag(SelectorType.Tag))
                    {
                        key = "+"+selector.Tag;
                        type &= ~SelectorType.Tag;
                    }
                    else if (type.HasFlag(SelectorType.ID))
                    {
                        key = "#" + selector.ID;
                        type &= ~SelectorType.ID;
                    }
                    else if (type.HasFlag(SelectorType.Class))
                    {
                        key = "." + selector.Class;
                        type &= ~SelectorType.Class;
                    }

            #else
                    if (selectorType.HasFlag(SelectorType.Attribute))
                    {
                        key = "!" + (char)DomData.TokenID(selector.AttributeName);
                        selectorType &= ~SelectorType.Attribute;
                        if (selector.AttributeValue != null)
                        {
                            InsertAttributeValueSelector(selector);
                        }
                    }
                    else if (selectorType.HasFlag(SelectorType.Tag))
                    {
                        key = "+" + (char)DomData.TokenID(selector.Tag, true);
                        selectorType &= ~SelectorType.Tag;
                    }
                    else if (selectorType.HasFlag(SelectorType.ID))
                    {
                        key = "#" + (char)DomData.TokenID(selector.ID);
                        selectorType &= ~SelectorType.ID;
                    }
                    else if (selectorType.HasFlag(SelectorType.Class))
                    {
                        key = "." + (char)DomData.TokenID(selector.Class);
                        selectorType &= ~SelectorType.Class;
                    }
            #endif
                }

                // If part of the selector was indexed, key will not be empty. Return initial set from the
                // index. If any selectors remain after this they will be searched the hard way.

                if (key != String.Empty)
                {
                    int depth = 0;
                    bool descendants = true;

                    switch (traversalType)
                    {
                        case TraversalType.Child:
                            depth = selector.ChildDepth; ;
                            descendants = false;
                            break;
                        case TraversalType.Filter:
                            depth = 0;
                            descendants = false;
                            break;
                        case TraversalType.Descendent:
                            depth = 1;
                            descendants = true;
                            break;
                    }

                    if (selectionSource == null)
                    {
                        interimResult = document.QueryIndex(key + DomData.indexSeparator, depth, descendants);
                    }
                    else
                    {
                        interimResult = new HashSet<IDomObject>();
                        foreach (IDomObject obj in selectionSource)
                        {
                            ((HashSet<IDomObject>)interimResult)
                                .AddRange(document.QueryIndex(key + DomData.indexSeparator + obj.Path,
                                    depth, descendants));
                        }
                    }
                }
                else if (selectorType.HasFlag(SelectorType.Elements))
                {
                    selectorType &= ~SelectorType.Elements;
                    HashSet<IDomObject> source = new HashSet<IDomObject>(selectionSource);
                    interimResult = new HashSet<IDomObject>();

                    foreach (IDomObject obj in selectionSource)
                    {
                        key = DomData.indexSeparator + obj.Path;
                        HashSet<IDomObject> srcKeys = new HashSet<IDomObject>(document.QueryIndex(key));
                        foreach (IDomObject match in selector.SelectElements)
                        {
                            if (srcKeys.Contains(match))
                            {
                                ((HashSet<IDomObject>)interimResult).Add(match);
                            }
                        }
                    }
                }
                // TODO - GetMatch should work if passed with no selectors (returning nothing), now it returns everything
                // 12/10/11 - this todo is not verified, much has changed since it was written. TODO confirm this and
                // fix if needed. If having the conversation with self again, remove comments and forget it. This is
                // an example of why comments can do more harm than good.

                if ((selectorType & ~(SelectorType.SubSelectorNot | SelectorType.SubSelectorHas)) != 0)
                {
                    IEnumerable<IDomObject> finalSelectWithin =
                        interimResult
                        ?? (combinatorType == CombinatorType.Chained ? lastResult : null)
                        ?? selectionSource
                        ?? document.ChildElements;

                    // if there are no temporary results (b/c there was no indexed selector) then use the whole set
                    interimResult = GetMatches(finalSelectWithin, selector);

                }

                // Deal with subselectors: has() and not() test for the presence of a selector within the children of
                // an element. This is essentially similar to the manual selection above.

                if (selectorType.HasFlag(SelectorType.SubSelectorHas)
                    || selectorType.HasFlag(SelectorType.SubSelectorNot))
                {
                    bool isHasSelector = selectorType.HasFlag(SelectorType.SubSelectorHas);

                    IEnumerable<IDomObject> subSelectWithin = interimResult
                        ?? (combinatorType == CombinatorType.Chained ? lastResult : null)
                        ?? selectionSource;

                    // subselects are a filter. start a new interim result.

                    HashSet<IDomObject> filteredResults = new HashSet<IDomObject>();

                    foreach (IDomObject obj in subSelectWithin)
                    {
                        bool match = true;
                        foreach (var sub in selector.SubSelectors)
                        {
                            List<IDomObject> listOfOne = new List<IDomObject>();
                            listOfOne.Add(obj);

                            bool has = !sub.Select(document, listOfOne).IsNullOrEmpty();

                            match &= isHasSelector == has;
                        }
                        if (match)
                        {
                            filteredResults.Add(obj);
                        }
                    }
                    interimResult = filteredResults;
                }
                tempResult = new HashSet<IDomObject>();
                if (lastResult != null)
                {
                    tempResult.AddRange(lastResult);
                }
                if (interimResult != null)
                {
                    tempResult.AddRange(interimResult);
                }
                lastResult = tempResult;
            }

            if (lastResult != null)
            {
                output.AddRange(lastResult);
            }

            if (output.IsNullOrEmpty())
            {
                yield break;
            }
            else
            {
                // Selectors always return in DOM order. Selections may end up in a different order but
                // we always sort here.

                foreach (IDomObject item in output.OrderBy(item => item.Path, StringComparer.Ordinal))
                {
                    yield return item;
                }
            }
            ActiveSelectors.Clear();
        }
Example #29
0
    public IEnumerable<int> IndexesOf(IEnumerable<string> keyNames)
    {
        Assert.IsTrue(!keyNames.IsNullOrEmpty());
        Assert.IsTrue(!keyNames.HasDuplication());
        Assert.IsTrue(keyNames.All(x => columnInfo.ContainsKey(x)), "Has unknown keyName in \n" + keyNames.ToStringList(","));

        return keyNames.Select(x => columnInfo.IndexOf(x));
    }
Example #30
0
        internal void CreateAssemblyPolicies()
        {
            // -----------------------------------------------------------------------------------------------------------------------------------
            // Step 5 : Build Assembly Manifests, catalog files and policy files
            var policyRule = Source.CompatabilityPolicyRules.FirstOrDefault();
            if (policyRule == null) {
                return;
            }

            // figure out what major/minor versions we need are overriding.
            var minimum = (FourPartVersion)policyRule["minimum"].Value;
            var maximum = (FourPartVersion)policyRule["maximum"].Value;

            if (minimum != 0 && maximum == 0) {
                maximum = Version - 1;
            }

            _versionRedirects = policyRule["versions"].Values.Select(each => (TwoPartVersion)each);

            if (_versionRedirects.IsNullOrEmpty()) {
                // didn't specify versions explicitly.
                // we can check for overriding versions.
                // TODO: SOON
            }

            if (maximum > 0L) {
                BindingPolicy = new BindingPolicy {
                    Minimum = minimum,
                    Maximum = maximum
                };

                CreateNativeAssemblyPolicies();
                CreateManagedAssemblyPolicies();
            }
        }