Esempio n. 1
0
 public static void ArgumentNotEmpty(IEnumerable source, [InvokerParameterName] String name, String message)
 {
     if (source.IsEmpty())
     {
         throw new ArgumentException(message, name);
     }
 }
        public IDbCommandResult Convert(IEnumerable values)
        {
            if (values.IsEmpty())
            {
                return new QueryResult();
            }
            var type = values.GetTypeOfValues();

            if (type.IsValueType || type == typeof(string))
            {
                return QueryResultOfValues(values, type);
            }
            if (type == typeof(DynamicRecord))
            {
                return QueryResultOfDynamicRecord(values.Cast<DynamicRecord>());
            }
            if (type == typeof(DynamicDataRow))
            {
                return QueryResultOfDynamicDataRow(values.Cast<DynamicDataRow>());
            }
            if (type.IsAssignableFrom(typeof(IDictionary)))
            {
                return QueryResultOfDictionary((IEnumerable<IDictionary>)values);
            }

            return QueryResultOfType(values, type);
        }
Esempio n. 3
0
 public static void ArgumentNotEmpty(IEnumerable source, [InvokerParameterName] String name)
 {
     if (source.IsEmpty())
     {
         throw new ArgumentException(Resources.ArgumentCannotBeEmpty, name);
     }
 }
Esempio n. 4
0
        internal AlignTokensOperation(SyntaxToken baseToken, IEnumerable<SyntaxToken> tokens, AlignTokensOption option)
        {
            Contract.ThrowIfNull(tokens);
            Debug.Assert(!tokens.IsEmpty());

            this.Option = option;
            this.BaseToken = baseToken;
            this.Tokens = tokens;
        }
Esempio n. 5
0
        /// <summary>
        /// Initializes an instance of <see cref="TextChangeEventArgs"/>.
        /// </summary>
        /// <param name="oldText">The text before the change.</param>
        /// <param name="newText">The text after the change.</param>
        /// <param name="changes">A non-empty set of ranges for the change.</param>
        public TextChangeEventArgs(SourceText oldText, SourceText newText, IEnumerable<TextChangeRange> changes)
        {
            if (changes == null || changes.IsEmpty())
            {
                throw new ArgumentException("changes");
            }

            this.OldText = oldText;
            this.NewText = newText;
            this.Changes = changes.ToImmutableArray();
        }
Esempio n. 6
0
        public string ExecuteMultipartQuery(ITwitterQuery twitterQuery, string contentId, IEnumerable<IMedia> medias)
        {
            if (medias == null || medias.IsEmpty())
            {
                return ExecuteQuery(twitterQuery);
            }

            var webRequest = _twitterRequestGenerator.GenerateMultipartWebRequest(twitterQuery, contentId, medias);
            var result = _webRequestExecutor.ExecuteMultipartRequest(webRequest);

            return result;
        }
Esempio n. 7
0
        public static void AddDependencies(this IFigure figure, IEnumerable<IFigure> dependencies)
        {
            if (figure == null || dependencies.IsEmpty())
            {
                return;
            }

            foreach (var dependency in dependencies)
            {
                dependency.Dependents.Add(figure);
            }
        }
        public static Directory Build(IEnumerable<WeaveHistoryItem> weaveHistoryItems)
        {
            if (weaveHistoryItems.IsEmpty())
            {
                return new Directory("All History", "history");
            }
            else
            {
                // Today
                var todayQuery = from b in weaveHistoryItems
                                 let dateTime = b.Visits!= null ? b.Visits.First().Date : DateTime.MinValue
                                 where IsToday(dateTime)
                                 orderby dateTime
                                 select b;

                Directory today = new Directory("Today", "today");
                foreach (WeaveHistoryItem historyItem in todayQuery)
                    today.Bookmarks.Add(new Bookmark(historyItem.Title, historyItem.Uri));

                // Yesterday
                var yesterdayQuery = from b in weaveHistoryItems
                                     let dateTime = b.Visits != null ? b.Visits.First().Date : DateTime.MinValue
                                     where IsYesterday(dateTime)
                                     orderby dateTime
                                     select b;

                Directory yesterday = new Directory("Yesterday", "yesterday");
                foreach (WeaveHistoryItem historyItem in yesterdayQuery)
                    yesterday.Bookmarks.Add(new Bookmark(historyItem.Title, historyItem.Uri));

                // This Month
                var thisMonthQuery = from b in weaveHistoryItems
                                     let dateTime = b.Visits != null ? b.Visits.First().Date : DateTime.MinValue
                                     where IsThisMonth(dateTime)
                                     orderby dateTime
                                     select b;

                Directory thisMonth = new Directory("This Month", "thismonth");
                foreach (WeaveHistoryItem historyItem in thisMonthQuery)
                    thisMonth.Bookmarks.Add(new Bookmark(historyItem.Title, historyItem.Uri));

                // History
                Directory history = new Directory("All History", "history");
                history.Directories.Add(today);
                history.Directories.Add(yesterday);
                history.Directories.Add(thisMonth);

                return history;
            }
        }
Esempio n. 9
0
        public IEnumerable<CorrelatedResult> Join(IEnumerable<RunResult> sourceResults,
                                                  IEnumerable<RunResult> targetResults)
        {
            var sourceArray = (sourceResults ?? Enumerable.Empty<RunResult>()).ToArray();
            var targetArray = (targetResults ?? Enumerable.Empty<RunResult>()).ToArray();

            if (targetArray.IsEmpty())
                return Enumerable.Empty<CorrelatedResult>();

            if (sourceResults.IsEmpty())
                return targetArray.Select(x => new CorrelatedResult(new NullResult(), x));

            return joinTwoNonEmptyCollections(sourceArray, targetArray);
        }
Esempio n. 10
0
		/// <summary>
		/// Initialize <see cref="StrategyReport"/>.
		/// </summary>
		/// <param name="strategies">Strategies, requiring the report generation.</param>
		/// <param name="fileName">The name of the file, in which the report is generated.</param>
		protected StrategyReport(IEnumerable<Strategy> strategies, string fileName)
		{
			if (strategies == null)
				throw new ArgumentNullException(nameof(strategies));

			if (strategies.IsEmpty())
				throw new ArgumentOutOfRangeException(nameof(strategies));

			if (fileName.IsEmpty())
				throw new ArgumentNullException(nameof(fileName));

			Strategies = strategies;
			FileName = fileName;
		}
Esempio n. 11
0
        public static LayoutElement NewRow(IEnumerable<LayoutElement> nodes, 
            LayoutElementType type = LayoutElementType.Row)
        {
            RectangleF dummyBounds = new RectangleF(0,0,1,1);
            var e = new LayoutElement(type, dummyBounds, null, nodes);

            // set bounds
            if (!nodes.IsEmpty())
            {
                e.Text = nodes.Select(x => x.Text).Where(x => !String.IsNullOrEmpty(x)).ElementsToStringS(delim: " ");
                e.SetBoundsFromNodes(false);
            }

            return e;
        }
Esempio n. 12
0
        public string GetMultipleRelationshipsQuery(IEnumerable<long> targetUsersId)
        {
            if (targetUsersId == null)
            {
                throw new ArgumentNullException("Target user ids parameter cannot be null.");
            }

            if (targetUsersId.IsEmpty())
            {
                throw new ArgumentException("Target user ids parameter cannot be empty.");
            }

            string userIds = _userQueryParameterGenerator.GenerateListOfIdsParameter(targetUsersId);
            string userIdsParameter = string.Format("user_id={0}", userIds);
            return string.Format(Resources.Friendship_GetRelationships, userIdsParameter);
        }
Esempio n. 13
0
        public string GetMultipleRelationshipsQuery(IEnumerable<string> targetUsersScreenName)
        {
            if (targetUsersScreenName == null)
            {
                throw new ArgumentNullException("Target user screen names parameter cannot be null.");
            }

            if (targetUsersScreenName.IsEmpty())
            {
                throw new ArgumentException("Target user screen names parameter cannot be empty.");
            }

            string userScreenNames = _userQueryParameterGenerator.GenerateListOfScreenNameParameter(targetUsersScreenName);
            string userScreenNamesParameter = string.Format("screen_name={0}", userScreenNames);
            return string.Format(Resources.Friendship_GetRelationships, userScreenNamesParameter);
        }
Esempio n. 14
0
 private IEnumerable<IScopeContext> LoadItemsFromConfig(Type type, IEnumerable<IScopeContext> items)
 {
     items = ConfigurationResolver.GetTypeBindingsFromConfig(type);
     if (items.IsEmpty())
     {
         Optimizer.AddBaseTypeIfNonExisting(type);
     }
     else
     {
         foreach (var scopeContext in items)
         {
             Optimizer.SetImplementationType(type, scopeContext, scopeContext.ImplementationKey);
         }
     }
     return items;
 }
        private IDbCommandResult QueryResultOfDynamicDataRow(IEnumerable<DynamicDataRow> values)
        {
            var result = new QueryResult();
            if (values.IsEmpty())
            {
                return result;
            }

            var columns = values.First().Columns;
            columns.Each(c => result.AddColumn(c, typeof(string)));
            foreach (var record in values)
            {
                var theRecord = record;
                result.AddRow(columns.Select(c => theRecord[c]));
            }
            return result;
        }
Esempio n. 16
0
        private IDictionary<string, double> ExtractTagRank(string text, IEnumerable<string> allowPos)
        {
            if (allowPos.IsEmpty())
            {
                allowPos = DefaultPosFilter;
            }

            var g = new UndirectWeightedGraph();
            var cm = new Dictionary<string, int>();
            var words = PosSegmenter.Cut(text).ToList();

            for (var i = 0; i < words.Count(); i++)
            {
                var wp = words[i];
                if (PairFilter(wp))
                {
                    for (var j = i + 1; j < i + Span; j++)
                    {
                        if (j >= words.Count)
                        {
                            break;
                        }
                        if (!PairFilter(words[j]))
                        {
                            continue;
                        }

                        // TODO: better separator.
                        var key = wp.Word + "$" + words[j].Word;
                        if (!cm.ContainsKey(key))
                        {
                            cm[key] = 0;
                        }
                        cm[key] += 1;
                    }
                }
            }

            foreach (var p in cm)
            {
                var terms = p.Key.Split('$');
                g.AddEdge(terms[0], terms[1], p.Value);
            }

            return g.Rank();
        }
Esempio n. 17
0
        /// <summary>
        /// 删除文件资源。
        /// </summary>
        /// <param name="filePaths">文件路径</param>
        public static void Remove(IEnumerable<string> filePaths)
        {
            if (filePaths.IsEmpty())
            {
                return;
            }

            foreach (var file in filePaths)
            {
                var fileInfo = new FileInfo(HttpContext.Current.Server.MapPath(file));

                if (fileInfo.Exists)
                {
                    fileInfo.Delete();
                    RemoveCompressionImage(fileInfo.FullName);
                }
            }
        }
        private static void InsertMethods(HtmlElement parent, string name, IEnumerable<MethodInfo> methods)
        {
            // Setup initial conditions.
            if (methods.IsEmpty()) return;

            // Create the method container.
            var methodContainer = CreateElement(name);
            parent.AppendChild(methodContainer);

            // Insert each method.
            foreach (var methodInfo in methods)
            {
                var htmMethod = CreateElement("method");
                htmMethod.SetAttribute("name", methodInfo.Name);
                htmMethod.SetAttribute("class", methodInfo.DeclaringType.FullName);
                methodContainer.AppendChild(htmMethod);
            }
        }
Esempio n. 19
0
        /// <summary>
        /// Adds refresh files to the specified project for all assemblies references belonging to the packages specified by packageNames.
        /// </summary>
        /// <param name="project">The project.</param>
        /// <param name="packagesFileSystem">The file system pointing to 'packages' folder under the solution.</param>
        /// <param name="packageNames">The package names.</param>
        public void AddRefreshFilesForReferences(Project project, IFileSystem packagesFileSystem, IEnumerable<PackageName> packageNames)
        {
            if (project == null)
            {
                throw new ArgumentNullException("project");
            }

            if (packagesFileSystem == null)
            {
                throw new ArgumentNullException("packagesFileSystem");
            }

            if (packageNames.IsEmpty())
            {
                return;
            }

            FrameworkName projectTargetFramework = GetTargetFramework(project);

            var projectSystem = _projectSystemFactory != null ? _projectSystemFactory.CreateProjectSystem(project, _fileSystemProvider)
                                                              :  VsProjectSystemFactory.CreateProjectSystem(project, _fileSystemProvider);

            foreach (PackageName packageName in packageNames)
            {
                string packageDirectory;
                IEnumerable<IPackageAssemblyReference> assemblyReferences = GetAssemblyReferences(
                    packagesFileSystem, packageName.Id, packageName.Version, out packageDirectory);
                
                // get compatible assembly references for the current project's target framework
                IEnumerable<IPackageAssemblyReference> compatibleAssemblyReferences;
                if (VersionUtility.TryGetCompatibleItems(projectTargetFramework, assemblyReferences, out compatibleAssemblyReferences))
                {
                    foreach (var assemblyReference in compatibleAssemblyReferences)
                    {
                        // Get the absolute path to the assembly being added. 
                        string assemblyPath = Path.Combine(packageDirectory, assemblyReference.Path); ;

                        // create one refresh file for each assembly reference, as per required by Website projects
                        projectSystem.CreateRefreshFile(assemblyPath);
                    }
                }
            }
        }
Esempio n. 20
0
        /// <summary>
        /// Concatenates the <see cref="ColumnSchema"/>s into a comma-delimited string.
        /// </summary>
        /// <param name="columns">The <see cref="ColumnSchema"/>s.</param>
        /// <returns>The <see cref="ColumnSchema"/>s concatenated a comma-delimited string.</returns>
        static string Concat(IEnumerable<ColumnSchema> columns)
        {
            if (columns.IsEmpty())
                return string.Empty;

            if (columns.Count() == 1)
                return columns.First().Name;

            columns = columns.OrderBy(x => x.Name);

            var sb = new StringBuilder();
            foreach (var c in columns)
            {
                sb.Append(c.Name);
                sb.Append(", ");
            }
            sb.Length -= 2;

            return sb.ToString();
        }
Esempio n. 21
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TextureAtlas"/> class.
        /// </summary>
        /// <param name="atlasItems">The collection of items to place into the atlas.</param>
        /// <exception cref="ArgumentException"><paramref name="atlasItems"/> is null or empty.</exception>
        public TextureAtlas(IEnumerable<ITextureAtlasable> atlasItems)
        {
            if (atlasItems == null || atlasItems.IsEmpty())
            {
                const string errmsg = "atlasItems is null or empty.";
                if (log.IsFatalEnabled)
                    log.Fatal(errmsg);
                throw new ArgumentException(errmsg, "atlasItems");
            }

            UpdateMaxTextureSize();

            // Build the layout for all the items that will be in the atlas
            _atlasTextureInfos = Combine(atlasItems);

            // Build and apply each atlas texture
            foreach (var atlasTextureInfo in _atlasTextureInfos)
            {
                atlasTextureInfo.BuildTexture(Padding);
            }
        }
 /// <summary>
 /// 檢查目前<see cref="IEnumerable{T}"/>實例元素數量是否不為0
 /// </summary>
 /// <param name="obj">目前<see cref="IEnumerable{T}"/>實例</param>
 /// <returns>檢查元素數量是否不為0</returns>
 public static bool IsNotEmpty <TSource>(this IEnumerable <TSource> obj)
 {
     return(!obj.IsEmpty());
 }
Esempio n. 23
0
 public bool IsSupersetOf(IEnumerable <T> other)
 {
     return(other.IsEmpty());
 }
Esempio n. 24
0
 public bool IsProperSubsetOf(IEnumerable <T> other)
 {
     return(!other.IsEmpty());
 }
 public static bool IsNonempty <T>(this IEnumerable <T> enumerable)
 => !enumerable.IsEmpty();
Esempio n. 26
0
        public static void Throws_ArgumentNullException_when_sequence_is_null()
        {
            IEnumerable <object> nullSequence = null;

            Assert.Throws <ArgumentNullException>(() => nullSequence.IsEmpty());
        }
Esempio n. 27
0
 public static bool IsNullOrEmpty <T>(this IEnumerable <T> collection)
 {
     return(collection == null || collection.IsEmpty());
 }
Esempio n. 28
0
 public static bool IsNotEmpty <T>(this IEnumerable <T> list)
 {
     return(!list.IsEmpty());
 }
Esempio n. 29
0
 internal IsolatedFileInfo(IsolatedStorageFile isf, IEnumerable<string> path)
     : base(isf, path)
 {
     Contract.Requires(!path.IsEmpty());
 }
        protected override void OnSave(BitArrayWriter writer, IEnumerable <ExecutionMessage> messages, OrderLogMetaInfo metaInfo)
        {
            if (metaInfo.IsEmpty() && !messages.IsEmpty())
            {
                var item = messages.First();

                metaInfo.FirstOrderId       = metaInfo.LastOrderId = item.SafeGetOrderId();
                metaInfo.FirstTransactionId = metaInfo.LastTransactionId = item.TransactionId;
                metaInfo.ServerOffset       = item.ServerTime.Offset;
            }

            writer.WriteInt(messages.Count());

            var allowNonOrdered  = metaInfo.Version >= MarketDataVersions.Version47;
            var isUtc            = metaInfo.Version >= MarketDataVersions.Version48;
            var allowDiffOffsets = metaInfo.Version >= MarketDataVersions.Version52;

            foreach (var message in messages)
            {
                var hasTrade = message.TradeId != null || message.TradePrice != null;

                var orderId = message.SafeGetOrderId();
                if (orderId < 0)
                {
                    throw new ArgumentOutOfRangeException(nameof(messages), orderId, LocalizedStrings.Str925);
                }

                if (message.ExecutionType != ExecutionTypes.OrderLog)
                {
                    throw new ArgumentOutOfRangeException(nameof(messages), message.ExecutionType, LocalizedStrings.Str1695Params.Put(orderId));
                }

                // sell market orders has zero price (if security do not have min allowed price)
                // execution ticks (like option execution) may be a zero cost
                // ticks for spreads may be a zero cost or less than zero
                //if (item.Price < 0)
                //	throw new ArgumentOutOfRangeException("items", item.Price, LocalizedStrings.Str926Params.Put(item.OrderId));

                var volume = message.SafeGetVolume();
                if (volume <= 0)
                {
                    throw new ArgumentOutOfRangeException(nameof(messages), volume, LocalizedStrings.Str927Params.Put(message.OrderId));
                }

                long?tradeId = null;

                if (hasTrade)
                {
                    tradeId = message.GetTradeId();

                    if (tradeId <= 0)
                    {
                        throw new ArgumentOutOfRangeException(nameof(messages), tradeId, LocalizedStrings.Str1012Params.Put(message.OrderId));
                    }

                    // execution ticks (like option execution) may be a zero cost
                    // ticks for spreads may be a zero cost or less than zero
                    //if (item.TradePrice <= 0)
                    //	throw new ArgumentOutOfRangeException("items", item.TradePrice, LocalizedStrings.Str929Params.Put(item.TradeId, item.OrderId));
                }

                metaInfo.LastOrderId = writer.SerializeId(orderId, metaInfo.LastOrderId);

                var orderPrice = message.OrderPrice;

                if (metaInfo.Version < MarketDataVersions.Version45)
                {
                    writer.WritePriceEx(orderPrice, metaInfo, SecurityId);
                }
                else
                {
                    var isAligned = (orderPrice % metaInfo.PriceStep) == 0;
                    writer.Write(isAligned);

                    if (isAligned)
                    {
                        if (metaInfo.FirstOrderPrice == 0)
                        {
                            metaInfo.FirstOrderPrice = metaInfo.LastOrderPrice = orderPrice;
                        }

                        writer.WritePrice(orderPrice, metaInfo.LastOrderPrice, metaInfo, SecurityId, true);
                        metaInfo.LastOrderPrice = orderPrice;
                    }
                    else
                    {
                        if (metaInfo.FirstNonSystemPrice == 0)
                        {
                            metaInfo.FirstNonSystemPrice = metaInfo.LastNonSystemPrice = orderPrice;
                        }

                        metaInfo.LastNonSystemPrice = writer.WriteDecimal(orderPrice, metaInfo.LastNonSystemPrice);
                    }
                }

                writer.WriteVolume(volume, metaInfo, SecurityId);

                writer.Write(message.Side == Sides.Buy);

                var lastOffset = metaInfo.LastServerOffset;
                metaInfo.LastTime         = writer.WriteTime(message.ServerTime, metaInfo.LastTime, LocalizedStrings.Str1013, allowNonOrdered, isUtc, metaInfo.ServerOffset, allowDiffOffsets, ref lastOffset);
                metaInfo.LastServerOffset = lastOffset;

                if (hasTrade)
                {
                    writer.Write(true);

                    if (metaInfo.FirstTradeId == 0)
                    {
                        metaInfo.FirstTradeId = metaInfo.LastTradeId = tradeId.Value;
                    }

                    metaInfo.LastTradeId = writer.SerializeId(tradeId.Value, metaInfo.LastTradeId);

                    writer.WritePriceEx(message.GetTradePrice(), metaInfo, SecurityId);
                }
                else
                {
                    writer.Write(false);
                    writer.Write(message.OrderState == OrderStates.Active);
                }

                if (metaInfo.Version < MarketDataVersions.Version31)
                {
                    continue;
                }

                writer.WriteNullableInt(message.OrderStatus);

                if (metaInfo.Version < MarketDataVersions.Version33)
                {
                    continue;
                }

                if (metaInfo.Version < MarketDataVersions.Version50)
                {
                    writer.WriteInt((int)(message.TimeInForce ?? TimeInForce.PutInQueue));
                }
                else
                {
                    writer.Write(message.TimeInForce != null);

                    if (message.TimeInForce != null)
                    {
                        writer.WriteInt((int)message.TimeInForce.Value);
                    }
                }

                if (metaInfo.Version >= MarketDataVersions.Version49)
                {
                    writer.Write(message.IsSystem != null);

                    if (message.IsSystem != null)
                    {
                        writer.Write(message.IsSystem.Value);
                    }
                }
                else
                {
                    writer.Write(message.IsSystem ?? true);
                }

                if (metaInfo.Version < MarketDataVersions.Version34)
                {
                    continue;
                }

                metaInfo.LastTransactionId = writer.SerializeId(message.TransactionId, metaInfo.LastTransactionId);

                if (metaInfo.Version < MarketDataVersions.Version40)
                {
                    continue;
                }

                if (metaInfo.Version < MarketDataVersions.Version46)
                {
                    writer.WriteLong(0 /*item.Latency.Ticks*/);
                }

                var portfolio = message.PortfolioName;
                var isEmptyPf = portfolio == null || portfolio == Portfolio.AnonymousPortfolio.Name;

                writer.Write(!isEmptyPf);

                if (!isEmptyPf)
                {
                    metaInfo.Portfolios.TryAdd(message.PortfolioName);
                    writer.WriteInt(metaInfo.Portfolios.IndexOf(message.PortfolioName));
                }

                if (metaInfo.Version < MarketDataVersions.Version51)
                {
                    continue;
                }

                writer.Write(message.Currency != null);

                if (message.Currency != null)
                {
                    writer.WriteInt((int)message.Currency.Value);
                }
            }
        }
Esempio n. 31
0
        private static void AddImplicitConflicts(
            ISymbol renamedSymbol,
            ISymbol originalSymbol,
            IEnumerable<ReferenceLocation> implicitReferenceLocations,
            SemanticModel semanticModel,
            Location originalDeclarationLocation,
            int newDeclarationLocationStartingPosition,
            ConflictResolution conflictResolution,
            CancellationToken cancellationToken)
        {
            {
                var renameRewriterService = conflictResolution.NewSolution.Workspace.Services.GetLanguageServices(renamedSymbol.Language).GetService<IRenameRewriterLanguageService>();
                var implicitUsageConflicts = renameRewriterService.ComputePossibleImplicitUsageConflicts(renamedSymbol, semanticModel, originalDeclarationLocation, newDeclarationLocationStartingPosition, cancellationToken);
                foreach (var implicitUsageConflict in implicitUsageConflicts)
                {
                    conflictResolution.AddOrReplaceRelatedLocation(new RelatedLocation(implicitUsageConflict.SourceSpan, conflictResolution.OldSolution.GetDocument(implicitUsageConflict.SourceTree).Id, RelatedLocationType.UnresolvableConflict));
                }
            }

            if (implicitReferenceLocations.IsEmpty())
            {
                return;
            }

            foreach (var implicitReferenceLocationsPerLanguage in implicitReferenceLocations.GroupBy(loc => loc.Document.Project.Language))
            {
                // the location of the implicit reference defines the language rules to check.
                // E.g. foreach in C# using a MoveNext in VB that is renamed to MOVENEXT (within VB)
                var renameRewriterService = implicitReferenceLocationsPerLanguage.First().Document.Project.LanguageServices.GetService<IRenameRewriterLanguageService>();
                var implicitConflicts = renameRewriterService.ComputeImplicitReferenceConflicts(
                    originalSymbol,
                    renamedSymbol,
                    implicitReferenceLocationsPerLanguage,
                    cancellationToken);

                foreach (var implicitConflict in implicitConflicts)
                {
                    conflictResolution.AddRelatedLocation(new RelatedLocation(implicitConflict.SourceSpan, conflictResolution.OldSolution.GetDocument(implicitConflict.SourceTree).Id, RelatedLocationType.UnresolvableConflict));
                }
            }
        }
        private bool Tag(IContent content, Guid? entityId, IEnumerable<Guid> tagIds)
        {
            if (entityId == Guid.Empty || tagIds.IsEmpty())
            {
                throw new ArgumentException("Please supply both an entity id and one or more tag ids");
            }

            PlatformEntity entity;

            if (content == null)
            {
                entity = this._dataSource.Query<PlatformEntity>().Include(e => e.Tags).FirstOrDefault(e => e.Id == entityId);
            }
            else
            {
                entity = content.Entity;

                if (entity.Tags == null)
                {
                    entity.Tags = new List<Term>();
                }
            }

            var tags = this._dataSource.Query<Term>().Where(t => tagIds.Contains(t.Id)).ToList();

            foreach (var id in tagIds)
            {
                if (!entity.Tags.Any(t => t.Id == id))
                {
                    var tag = tags.First(t => t.Id == id);
                    entity.Tags.Add(tag);
                    tag.TagCount++;
                }
            }

            return true;
        }
        /// <summary>
        /// Creates a new compilation with additional syntax trees.
        /// </summary>
        public new CSharpCompilation AddSyntaxTrees(IEnumerable<SyntaxTree> trees)
        {
            using (Logger.LogBlock(FunctionId.CSharp_Compilation_AddSyntaxTrees, message: this.AssemblyName))
            {
                if (trees == null)
                {
                    throw new ArgumentNullException("trees");
                }

                if (trees.IsEmpty())
                {
                    return this;
                }

                // We're using a try-finally for this builder because there's a test that 
                // specifically checks for one or more of the argument exceptions below
                // and we don't want to see console spew (even though we don't generally
                // care about pool "leaks" in exceptional cases).  Alternatively, we
                // could create a new ArrayBuilder.
                var builder = ArrayBuilder<SyntaxTree>.GetInstance();
                try
                {
                    builder.AddRange(this.SyntaxTrees);

                    bool referenceDirectivesChanged = false;
                    var oldTreeCount = this.SyntaxTrees.Length;
                    var ordinalMap = this.syntaxTreeOrdinalMap;
                    var declMap = rootNamespaces;
                    var declTable = declarationTable;
                    int i = 0;
                    foreach (var tree in trees.Cast<CSharpSyntaxTree>())
                    {
                        if (tree == null)
                        {
                            throw new ArgumentNullException("trees[" + i + "]");
                        }

                        if (!tree.HasCompilationUnitRoot)
                        {
                            throw new ArgumentException(String.Format(CSharpResources.TreeMustHaveARootNodeWith, i));
                        }

                        if (declMap.ContainsKey(tree))
                        {
                            throw new ArgumentException(CSharpResources.SyntaxTreeAlreadyPresent, String.Format(CSharpResources.Trees0, i));
                        }

                        if (IsSubmission && tree.Options.Kind == SourceCodeKind.Regular)
                        {
                            throw new ArgumentException(CSharpResources.SubmissionCanOnlyInclude, String.Format(CSharpResources.Trees0, i));
                        }

                        AddSyntaxTreeToDeclarationMapAndTable(tree, options, IsSubmission, ref declMap, ref declTable, ref referenceDirectivesChanged);
                        builder.Add(tree);
                        ordinalMap = ordinalMap.Add(tree, oldTreeCount + i);

                        i++;
                    }

                    if (IsSubmission && declMap.Count > 1)
                    {
                        throw new ArgumentException(CSharpResources.SubmissionCanHaveAtMostOne, "trees");
                    }

                    return UpdateSyntaxTrees(builder.ToImmutable(), ordinalMap, declMap, declTable, referenceDirectivesChanged);
                }
                finally
                {
                    builder.Free();
                }
            }
        }
Esempio n. 34
0
 public static bool IsNullOrEmpty <T>(IEnumerable <T> enumerable)
 {
     //true or null (null is true)
     return(enumerable?.IsEmpty() != false);
 }
        protected override void OnSave(BitArrayWriter writer, IEnumerable <ExecutionMessage> messages, OrderLogMetaInfo metaInfo)
        {
            if (metaInfo.IsEmpty() && !messages.IsEmpty())
            {
                var item = messages.First();

                metaInfo.FirstOrderId       = metaInfo.LastOrderId = item.OrderId ?? default;
                metaInfo.FirstTransactionId = metaInfo.LastTransactionId = item.TransactionId;
                metaInfo.ServerOffset       = item.ServerTime.Offset;
                metaInfo.FirstSeqNum        = metaInfo.PrevSeqNum = item.SeqNum;
            }

            writer.WriteInt(messages.Count());

            var allowNonOrdered  = metaInfo.Version >= MarketDataVersions.Version47;
            var isUtc            = metaInfo.Version >= MarketDataVersions.Version48;
            var allowDiffOffsets = metaInfo.Version >= MarketDataVersions.Version52;
            var isTickPrecision  = metaInfo.Version >= MarketDataVersions.Version53;
            var useBalance       = metaInfo.Version >= MarketDataVersions.Version54;
            var buildFrom        = metaInfo.Version >= MarketDataVersions.Version55;
            var seqNum           = metaInfo.Version >= MarketDataVersions.Version56;
            var useLong          = metaInfo.Version >= MarketDataVersions.Version57;
            var largeDecimal     = metaInfo.Version >= MarketDataVersions.Version57;
            var stringId         = metaInfo.Version >= MarketDataVersions.Version58;

            foreach (var message in messages)
            {
                var hasTrade = message.TradeId != null || message.TradePrice != null || !message.TradeStringId.IsEmpty();
                var orderId  = message.OrderId;

                if (orderId is null)
                {
                    if (!stringId)
                    {
                        throw new ArgumentOutOfRangeException(nameof(messages), message.TransactionId, LocalizedStrings.Str925);
                    }
                }

                if (message.DataType != DataType.OrderLog)
                {
                    throw new ArgumentOutOfRangeException(nameof(messages), message.DataType, LocalizedStrings.Str1695Params.Put(message));
                }

                // sell market orders has zero price (if security do not have min allowed price)
                // execution ticks (like option execution) may be a zero cost
                // ticks for spreads may be a zero cost or less than zero
                //if (item.Price < 0)
                //	throw new ArgumentOutOfRangeException(nameof(messages), item.Price, LocalizedStrings.Str926Params.Put(item.OrderId));

                var volume = message.SafeGetVolume();
                if (volume <= 0 && message.OrderState != OrderStates.Done)
                {
                    throw new ArgumentOutOfRangeException(nameof(messages), volume, LocalizedStrings.Str927Params.Put(message.TransactionId));
                }

                long?tradeId = null;

                if (hasTrade)
                {
                    tradeId = message.TradeId;

                    if (tradeId is null or <= 0)
                    {
                        if (!stringId)
                        {
                            throw new ArgumentOutOfRangeException(nameof(messages), tradeId, LocalizedStrings.Str1012Params.Put(message.TransactionId));
                        }
                    }

                    // execution ticks (like option execution) may be a zero cost
                    // ticks for spreads may be a zero cost or less than zero
                    //if (item.TradePrice <= 0)
                    //	throw new ArgumentOutOfRangeException(nameof(messages), item.TradePrice, LocalizedStrings.Str929Params.Put(item.TradeId, item.OrderId));
                }

                metaInfo.LastOrderId = writer.SerializeId(orderId ?? 0, metaInfo.LastOrderId);

                var orderPrice = message.OrderPrice;

                if (metaInfo.Version < MarketDataVersions.Version45)
                {
                    writer.WritePriceEx(orderPrice, metaInfo, SecurityId, false, false);
                }
                else
                {
                    var isAligned = (orderPrice % metaInfo.LastPriceStep) == 0;
                    writer.Write(isAligned);

                    if (isAligned)
                    {
                        if (metaInfo.FirstOrderPrice == 0)
                        {
                            metaInfo.FirstOrderPrice = metaInfo.LastOrderPrice = orderPrice;
                        }

                        var prevPrice = metaInfo.LastOrderPrice;
                        writer.WritePrice(orderPrice, ref prevPrice, metaInfo, SecurityId, true);
                        metaInfo.LastOrderPrice = prevPrice;
                    }
                    else
                    {
                        if (metaInfo.FirstFractionalPrice == 0)
                        {
                            metaInfo.FirstFractionalPrice = metaInfo.LastFractionalPrice = orderPrice;
                        }

                        metaInfo.LastFractionalPrice = writer.WriteDecimal(orderPrice, metaInfo.LastFractionalPrice);
                    }
                }

                writer.WriteVolume(volume, metaInfo, largeDecimal);

                writer.Write(message.Side == Sides.Buy);

                var lastOffset = metaInfo.LastServerOffset;
                metaInfo.LastTime         = writer.WriteTime(message.ServerTime, metaInfo.LastTime, LocalizedStrings.Str1013, allowNonOrdered, isUtc, metaInfo.ServerOffset, allowDiffOffsets, isTickPrecision, ref lastOffset);
                metaInfo.LastServerOffset = lastOffset;

                if (hasTrade)
                {
                    writer.Write(true);

                    if (metaInfo.FirstTradeId == 0)
                    {
                        metaInfo.FirstTradeId = metaInfo.LastTradeId = tradeId ?? default;
                    }

                    metaInfo.LastTradeId = writer.SerializeId(tradeId ?? default, metaInfo.LastTradeId);

                    writer.WritePriceEx(message.GetTradePrice(), metaInfo, SecurityId, useLong, largeDecimal);

                    if (metaInfo.Version >= MarketDataVersions.Version54)
                    {
                        writer.WriteInt((int)message.OrderState);
                    }
                }
                else
                {
                    writer.Write(false);

                    if (metaInfo.Version >= MarketDataVersions.Version54)
                    {
                        writer.WriteInt((int)message.OrderState);
                    }
                    else
                    {
                        writer.Write(message.OrderState == OrderStates.Active);
                    }
                }

                if (metaInfo.Version < MarketDataVersions.Version31)
                {
                    continue;
                }

                writer.WriteNullableInt((int?)message.OrderStatus);

                if (metaInfo.Version < MarketDataVersions.Version33)
                {
                    continue;
                }

                if (metaInfo.Version < MarketDataVersions.Version50)
                {
                    writer.WriteInt((int)(message.TimeInForce ?? TimeInForce.PutInQueue));
                }
                else
                {
                    writer.Write(message.TimeInForce != null);

                    if (message.TimeInForce != null)
                    {
                        writer.WriteInt((int)message.TimeInForce.Value);
                    }
                }

                if (metaInfo.Version >= MarketDataVersions.Version49)
                {
                    writer.Write(message.IsSystem != null);

                    if (message.IsSystem != null)
                    {
                        writer.Write(message.IsSystem.Value);
                    }
                }
                else
                {
                    writer.Write(message.IsSystem ?? true);
                }

                if (metaInfo.Version < MarketDataVersions.Version34)
                {
                    continue;
                }

                metaInfo.LastTransactionId = writer.SerializeId(message.TransactionId, metaInfo.LastTransactionId);

                if (metaInfo.Version < MarketDataVersions.Version40)
                {
                    continue;
                }

                if (metaInfo.Version < MarketDataVersions.Version46)
                {
                    writer.WriteLong(0 /*item.Latency.Ticks*/);
                }

                var portfolio   = message.PortfolioName;
                var isEmptyPf   = portfolio == null;
                var isAnonymous = !isEmptyPf && portfolio == Portfolio.AnonymousPortfolio.Name;

                if (isEmptyPf)
                {
                    writer.Write(false);
                }
                else
                {
                    if (isAnonymous)
                    {
                        if (metaInfo.Version < MarketDataVersions.Version54)
                        {
                            writer.Write(false);
                        }
                        else
                        {
                            writer.Write(true);
                            writer.Write(true);                             // is anonymous
                        }
                    }
                    else
                    {
                        writer.Write(true);

                        if (metaInfo.Version > MarketDataVersions.Version54)
                        {
                            writer.Write(false);                             // not anonymous
                        }
                        metaInfo.Portfolios.TryAdd(message.PortfolioName);
                        writer.WriteInt(metaInfo.Portfolios.IndexOf(message.PortfolioName));
                    }
                }

                if (metaInfo.Version < MarketDataVersions.Version51)
                {
                    continue;
                }

                writer.WriteNullableInt((int?)message.Currency);

                if (!useBalance)
                {
                    continue;
                }

                if (message.Balance == null)
                {
                    writer.Write(false);
                }
                else
                {
                    writer.Write(true);

                    if (message.Balance.Value == 0)
                    {
                        writer.Write(false);
                    }
                    else
                    {
                        writer.Write(true);
                        writer.WriteDecimal(message.Balance.Value, 0);
                    }
                }

                if (!buildFrom)
                {
                    continue;
                }

                writer.WriteBuildFrom(message.BuildFrom);

                if (!seqNum)
                {
                    continue;
                }

                writer.WriteSeqNum(message, metaInfo);

                if (!stringId)
                {
                    continue;
                }

                writer.Write(orderId is null);
                writer.WriteStringEx(message.OrderStringId);

                writer.Write(tradeId is null);
                writer.WriteStringEx(message.TradeStringId);

                if (message.OrderBuyId != null)
                {
                    writer.Write(true);
                    metaInfo.LastOrderId = writer.SerializeId(message.OrderBuyId.Value, metaInfo.LastOrderId);
                }
                else
                {
                    writer.Write(false);
                }

                if (message.OrderSellId != null)
                {
                    writer.Write(true);
                    metaInfo.LastOrderId = writer.SerializeId(message.OrderSellId.Value, metaInfo.LastOrderId);
                }
                else
                {
                    writer.Write(false);
                }

                writer.WriteNullableBool(message.IsUpTick);
                writer.WriteNullableDecimal(message.Yield);
                writer.WriteNullableInt(message.TradeStatus);
                writer.WriteNullableDecimal(message.OpenInterest);
                writer.WriteNullableInt((int?)message.OriginSide);
            }
        }
Esempio n. 36
0
 public bool TestIsEmpty(IEnumerable enumeration)
 {
     return(enumeration.IsEmpty());
 }
Esempio n. 37
0
        internal static void DrawTrace(SpriteBatch sb, IEnumerable<TraceLine> lines)
        {
            //TODO: clean this up, in some way or another
            if (lines.IsEmpty())
                return;

            sb.Begin(SpriteSortMode.Deferred, BlendState.NonPremultiplied, SamplerState.LinearClamp, null, null);

            OuterWindow = new Rectangle(PrismDebug.PADDING_X, Main.screenHeight * 2 / 3 + PrismDebug.PADDING_Y, Main.screenWidth - PrismDebug.PADDING_X * 2, Main.screenHeight / 3 - 2 * PrismDebug.PADDING_Y);

            sb.Draw(TMain.WhitePixel, OuterWindow, TraceWindowBg);

            sb.DrawString(Main.fontMouseText, "Prism Debug Tracer", OuterWindow.TopLeft() + new Vector2(2, 16), TraceText, 0f, new Vector2(0, Main.fontItemStack.LineSpacing / 2f), Vector2.One, SpriteEffects.None, 0f);

            sb.End();

            Viewport screen = sb.GraphicsDevice.Viewport;

            try
            {
                sb.GraphicsDevice.Viewport = new Viewport(InnerWindow);
            }
            catch
            {
                sb.GraphicsDevice.Viewport = screen;
            }

            sb.Begin();

            float curY = 0;
            bool altBg = false;

            var lineAmt = lines.Count();
            var drawText   = new List<string>(lineAmt);
            var fadeAlphas = new List<float >(lineAmt);

            var curLine = new StringBuilder();

            foreach (var l in lines.Take(lineAmt))
            {
                float curW = 0f;
                string[] words = l.Text.Split(SpaceArray);

                for (int i = 0; i < words.Length; i++)
                {
                    string append = (i > 0 ? Space : String.Empty) + words[i];
                    curW += Main.fontItemStack.MeasureString(append).X;

                    if (curW >= InnerWindow.Width)
                    {
                        curLine.AppendLine();
                        append = append.TrimStart();
                        curW = Main.fontItemStack.MeasureString(append).X;
                    }
                    curLine.Append(append);
                }

                fadeAlphas.Add(MathHelper.Clamp(l.Timeleft / 30f, 0f, 1f));
                drawText.Add(curLine.ToString());
                curY += Main.fontItemStack.MeasureString(curLine).Y + TraceMsgPadding;

                curLine.Clear();
            }

            TraceScroll = MathHelper.Clamp(curY - InnerWindow.Height, 0, Single.PositiveInfinity);
            curY = 0f;

            for (int i = 0; i < drawText.Count; i++)
            {
                var size = Main.fontItemStack.MeasureString(drawText[i]);

                sb.Draw(TMain.WhitePixel, new Vector2(0, curY - TraceScroll), null, (altBg ? TraceBgColour : TraceBgColourAlt) * fadeAlphas[i], 0f, Vector2.Zero, new Vector2(InnerWindow.Width, size.Y + TraceMsgPadding), SpriteEffects.None, 0f);
                altBg = !altBg;

                sb.DrawString(Main.fontItemStack, drawText[i], new Vector2(0, curY - TraceScroll), TraceText * fadeAlphas[i], 0f, Vector2.Zero, Vector2.One, SpriteEffects.None, 0f);

                curY += size.Y + TraceMsgPadding;
            }

            sb.End();

            sb.GraphicsDevice.Viewport = screen;
        }
Esempio n. 38
0
        private bool ApplySuppressionFix(IEnumerable <DiagnosticData> diagnosticsToFix, Func <Project, bool> shouldFixInProject, bool filterStaleDiagnostics, bool isAddSuppression, bool isSuppressionInSource, bool onlyCompilerDiagnostics, bool showPreviewChangesDialog)
        {
            if (diagnosticsToFix == null)
            {
                return(false);
            }

            diagnosticsToFix = FilterDiagnostics(diagnosticsToFix, isAddSuppression, isSuppressionInSource, onlyCompilerDiagnostics);
            if (diagnosticsToFix.IsEmpty())
            {
                // Nothing to fix.
                return(true);
            }

            ImmutableDictionary <Document, ImmutableArray <Diagnostic> > documentDiagnosticsToFixMap = null;
            ImmutableDictionary <Project, ImmutableArray <Diagnostic> >  projectDiagnosticsToFixMap  = null;

            var title                  = GetFixTitle(isAddSuppression);
            var waitDialogMessage      = GetWaitDialogMessage(isAddSuppression);
            var noDiagnosticsToFix     = false;
            var cancelled              = false;
            var newSolution            = _workspace.CurrentSolution;
            HashSet <string> languages = null;

            void computeDiagnosticsAndFix(IUIThreadOperationContext context)
            {
                var cancellationToken = context.UserCancellationToken;

                cancellationToken.ThrowIfCancellationRequested();
                documentDiagnosticsToFixMap = GetDocumentDiagnosticsToFixAsync(diagnosticsToFix, shouldFixInProject, filterStaleDiagnostics: filterStaleDiagnostics, cancellationToken: cancellationToken)
                                              .WaitAndGetResult(cancellationToken);

                cancellationToken.ThrowIfCancellationRequested();
                projectDiagnosticsToFixMap = isSuppressionInSource ?
                                             ImmutableDictionary <Project, ImmutableArray <Diagnostic> > .Empty :
                                             GetProjectDiagnosticsToFixAsync(diagnosticsToFix, shouldFixInProject, filterStaleDiagnostics: filterStaleDiagnostics, cancellationToken: cancellationToken)
                                             .WaitAndGetResult(cancellationToken);

                if (documentDiagnosticsToFixMap == null ||
                    projectDiagnosticsToFixMap == null ||
                    (documentDiagnosticsToFixMap.IsEmpty && projectDiagnosticsToFixMap.IsEmpty))
                {
                    // Nothing to fix.
                    noDiagnosticsToFix = true;
                    return;
                }

                cancellationToken.ThrowIfCancellationRequested();

                // Equivalence key determines what fix will be applied.
                // Make sure we don't include any specific diagnostic ID, as we want all of the given diagnostics (which can have varied ID) to be fixed.
                var equivalenceKey = isAddSuppression ?
                                     (isSuppressionInSource ? FeaturesResources.in_Source : FeaturesResources.in_Suppression_File) :
                                     FeaturesResources.Remove_Suppression;

                // We have different suppression fixers for every language.
                // So we need to group diagnostics by the containing project language and apply fixes separately.
                languages = new HashSet <string>(projectDiagnosticsToFixMap.Select(p => p.Key.Language).Concat(documentDiagnosticsToFixMap.Select(kvp => kvp.Key.Project.Language)));

                foreach (var language in languages)
                {
                    // Use the Fix multiple occurrences service to compute a bulk suppression fix for the specified document and project diagnostics,
                    // show a preview changes dialog and then apply the fix to the workspace.

                    cancellationToken.ThrowIfCancellationRequested();

                    var documentDiagnosticsPerLanguage = GetDocumentDiagnosticsMappedToNewSolution(documentDiagnosticsToFixMap, newSolution, language);
                    if (!documentDiagnosticsPerLanguage.IsEmpty)
                    {
                        var suppressionFixer = GetSuppressionFixer(documentDiagnosticsPerLanguage.SelectMany(kvp => kvp.Value), language, _codeFixService);
                        if (suppressionFixer != null)
                        {
                            var suppressionFixAllProvider = suppressionFixer.GetFixAllProvider();
                            newSolution = _fixMultipleOccurencesService.GetFix(
                                documentDiagnosticsPerLanguage,
                                _workspace,
                                suppressionFixer,
                                suppressionFixAllProvider,
                                equivalenceKey,
                                title,
                                waitDialogMessage,
                                cancellationToken);
                            if (newSolution == null)
                            {
                                // User cancelled or fixer threw an exception, so we just bail out.
                                cancelled = true;
                                return;
                            }
                        }
                    }

                    var projectDiagnosticsPerLanguage = GetProjectDiagnosticsMappedToNewSolution(projectDiagnosticsToFixMap, newSolution, language);
                    if (!projectDiagnosticsPerLanguage.IsEmpty)
                    {
                        var suppressionFixer = GetSuppressionFixer(projectDiagnosticsPerLanguage.SelectMany(kvp => kvp.Value), language, _codeFixService);
                        if (suppressionFixer != null)
                        {
                            var suppressionFixAllProvider = suppressionFixer.GetFixAllProvider();
                            newSolution = _fixMultipleOccurencesService.GetFix(
                                projectDiagnosticsPerLanguage,
                                _workspace,
                                suppressionFixer,
                                suppressionFixAllProvider,
                                equivalenceKey,
                                title,
                                waitDialogMessage,
                                cancellationToken);
                            if (newSolution == null)
                            {
                                // User cancelled or fixer threw an exception, so we just bail out.
                                cancelled = true;
                                return;
                            }
                        }
                    }
                }
            }

            var result = InvokeWithWaitDialog(computeDiagnosticsAndFix, title, waitDialogMessage);

            // Bail out if the user cancelled.
            if (cancelled || result == UIThreadOperationStatus.Canceled)
            {
                return(false);
            }
            else if (noDiagnosticsToFix || newSolution == _workspace.CurrentSolution)
            {
                // No changes.
                return(true);
            }

            if (showPreviewChangesDialog)
            {
                newSolution = FixAllGetFixesService.PreviewChanges(
                    _workspace.CurrentSolution,
                    newSolution,
                    fixAllPreviewChangesTitle: title,
                    fixAllTopLevelHeader: title,
                    languageOpt: languages?.Count == 1 ? languages.Single() : null,
                    workspace: _workspace);
                if (newSolution == null)
                {
                    return(false);
                }
            }

            waitDialogMessage = isAddSuppression ? ServicesVSResources.Applying_suppressions_fix : ServicesVSResources.Applying_remove_suppressions_fix;
            void applyFix(IUIThreadOperationContext context)
            {
                var operations        = ImmutableArray.Create <CodeActionOperation>(new ApplyChangesOperation(newSolution));
                var cancellationToken = context.UserCancellationToken;
                var scope             = context.AddScope(allowCancellation: true, description: "");

                _editHandlerService.Apply(
                    _workspace,
                    fromDocument: null,
                    operations: operations,
                    title: title,
                    progressTracker: new UIThreadOperationContextProgressTracker(scope),
                    cancellationToken: cancellationToken);
            }

            result = InvokeWithWaitDialog(applyFix, title, waitDialogMessage);
            if (result == UIThreadOperationStatus.Canceled)
            {
                return(false);
            }

            // Kick off diagnostic re-analysis for affected projects so that diagnostics gets refreshed.
            Task.Run(() =>
            {
                var reanalyzeDocuments = diagnosticsToFix.Where(d => d.DocumentId != null).Select(d => d.DocumentId).Distinct();
                _diagnosticService.Reanalyze(_workspace, documentIds: reanalyzeDocuments, highPriority: true);
            });

            return(true);
        }
Esempio n. 39
0
        protected override TimeSpan OnProcess()
        {
            var source = new TrueFXSource();

            if (_settings.UseTemporaryFiles != TempFiles.NotUse)
            {
                source.DumpFolder = GetTempPath();
            }

            var allSecurity = this.GetAllSecurity();

            // если фильтр по инструментам выключен (выбран инструмент все инструменты)
            IEnumerable <HydraTaskSecurity> selectedSecurities = (allSecurity != null
                                ? this.ToHydraSecurities(EntityRegistry.Securities.Filter(ExchangeBoard.TrueFX))
                                : Settings.Securities
                                                                  ).ToArray();

            if (selectedSecurities.IsEmpty())
            {
                this.AddWarningLog(LocalizedStrings.Str2289);

                source.Refresh(EntityRegistry.Securities, new Security(), SaveSecurity, () => !CanProcess(false));

                selectedSecurities = this.ToHydraSecurities(EntityRegistry.Securities.Filter(ExchangeBoard.TrueFX));
            }

            if (selectedSecurities.IsEmpty())
            {
                this.AddWarningLog(LocalizedStrings.Str2292);
                return(TimeSpan.MaxValue);
            }

            var startDate = _settings.StartFrom;
            var endDate   = DateTime.Today - TimeSpan.FromDays(_settings.DayOffset);

            var allDates = startDate.Range(endDate, TimeSpan.FromDays(1)).ToArray();

            foreach (var security in selectedSecurities)
            {
                if (!CanProcess())
                {
                    break;
                }

                if ((allSecurity ?? security).MarketDataTypesSet.Contains(typeof(Level1ChangeMessage)))
                {
                    var storage    = StorageRegistry.GetLevel1MessageStorage(security.Security, _settings.Drive, _settings.StorageFormat);
                    var emptyDates = allDates.Except(storage.Dates).ToArray();

                    if (emptyDates.IsEmpty())
                    {
                        this.AddInfoLog(LocalizedStrings.Str2293Params, security.Security.Id);
                    }
                    else
                    {
                        var secId = security.Security.ToSecurityId();

                        foreach (var emptyDate in emptyDates)
                        {
                            if (!CanProcess())
                            {
                                break;
                            }

                            try
                            {
                                this.AddInfoLog(LocalizedStrings.Str2294Params, emptyDate, security.Security.Id);
                                var ticks = source.LoadTickMessages(secId, emptyDate);

                                if (ticks.Any())
                                {
                                    SaveLevel1Changes(security, ticks);
                                }
                                else
                                {
                                    this.AddDebugLog(LocalizedStrings.NoData);
                                }

                                if (_settings.UseTemporaryFiles == TempFiles.UseAndDelete)
                                {
                                    File.Delete(source.GetDumpFile(security.Security, emptyDate, emptyDate, typeof(Level1ChangeMessage), null));
                                }
                            }
                            catch (Exception ex)
                            {
                                HandleError(new InvalidOperationException(LocalizedStrings.Str2295Params
                                                                          .Put(emptyDate, security.Security.Id), ex));
                            }
                        }
                    }
                }
                else
                {
                    this.AddDebugLog(LocalizedStrings.MarketDataNotEnabled, security.Security.Id, typeof(Level1ChangeMessage).Name);
                }

                if (!CanProcess())
                {
                    break;
                }
            }

            if (CanProcess())
            {
                this.AddInfoLog(LocalizedStrings.Str2300);
            }

            return(base.OnProcess());
        }
        private async Task<IEnumerable<CodeFix>> GetSuppressionsAsync(Document documentOpt, Project project, IEnumerable<Diagnostic> diagnostics, SuppressionTargetInfo suppressionTargetInfo, bool skipSuppressMessage, bool skipUnsuppress, CancellationToken cancellationToken)
        {
            // We only care about diagnostics that can be suppressed/unsuppressed.
            diagnostics = diagnostics.Where(CanBeSuppressedOrUnsuppressed);
            if (diagnostics.IsEmpty())
            {
                return SpecializedCollections.EmptyEnumerable<CodeFix>();
            }

            if (!skipSuppressMessage)
            {
                var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
                var suppressMessageAttribute = compilation.SuppressMessageAttributeType();
                skipSuppressMessage = suppressMessageAttribute == null || !suppressMessageAttribute.IsAttribute();
            }

            var result = new List<CodeFix>();
            foreach (var diagnostic in diagnostics)
            {
                if (!diagnostic.IsSuppressed)
                {
                    var nestedActions = new List<NestedSuppressionCodeAction>();

                    if (diagnostic.Location.IsInSource && documentOpt != null)
                    {
                        // pragma warning disable.
                        nestedActions.Add(PragmaWarningCodeAction.Create(suppressionTargetInfo, documentOpt, diagnostic, this));
                    }

                    // SuppressMessageAttribute suppression is not supported for compiler diagnostics.
                    if (!skipSuppressMessage && !SuppressionHelpers.IsCompilerDiagnostic(diagnostic))
                    {
                        // global assembly-level suppress message attribute.
                        nestedActions.Add(new GlobalSuppressMessageCodeAction(suppressionTargetInfo.TargetSymbol, project, diagnostic, this));
                    }

                    result.Add(new CodeFix(new SuppressionCodeAction(diagnostic, nestedActions), diagnostic));
                }
                else if (!skipUnsuppress)
                {
                    var codeAction = await RemoveSuppressionCodeAction.CreateAsync(suppressionTargetInfo, documentOpt, project, diagnostic, this, cancellationToken).ConfigureAwait(false);
                    if (codeAction != null)
                    {
                        result.Add(new CodeFix(codeAction, diagnostic));
                    }
                }
            }

            return result;
        }
Esempio n. 41
0
 /// <summary>
 /// Determines whether the specified enumerable collection is empty.
 /// Note: This method has the side effect of moving the position of
 /// the enumerator back to the starting position.
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="items">Enumerable to test</param>
 /// <returns>
 ///     <c>true</c> if the specified collection is empty; otherwise, <c>false</c>.
 /// </returns>
 public static Boolean IsNullOrEmpty <T>(this IEnumerable <T> items)
 {
     return(items == null || items.IsEmpty());
 }
Esempio n. 42
0
 /// <summary>
 /// collection is not null or empty
 /// </summary>
 /// <param name="source"></param>
 /// <returns></returns>
 public static bool NotEmpty <T>(this IEnumerable <T> source)
 {
     return(!source.IsEmpty());
 }
Esempio n. 43
0
 /// <summary>
 /// Determines whether the enumerable is null or empty.
 /// </summary>
 /// <typeparam name="T">The source type.</typeparam>
 /// <param name="source">The source enumerable.</param>
 /// <returns>True if the collection is null or empty; else false.</returns>
 public static bool IsNullEmpty <T>(this IEnumerable <T> source)
 {
     return(source?.IsEmpty() ?? true);
 }
Esempio n. 44
0
 /// <summary>
 /// 是否不为 NULL 或空集合。
 /// </summary>
 /// <remarks>
 /// 详情参考  <see cref="Enumerable.Any{TSource}(IEnumerable{TSource})"/>。
 /// </remarks>
 /// <typeparam name="TSource">指定的源类型。</typeparam>
 /// <param name="sources">给定的 <see cref="IEnumerable{TSource}"/>。</param>
 /// <returns>返回布尔值。</returns>
 public static bool IsNotEmpty <TSource>(this IEnumerable <TSource> sources)
 => !sources.IsEmpty();
Esempio n. 45
0
        List <FriendCircleEntity> GeneralPraise(IEnumerable <dm_friend_circleEntity> dm_Friend_CircleEntities, string cacheKey, bool IsGovernment = false)
        {
            //获取用户信息
            dm_userEntity dm_UserEntity = CacheHelper.ReadUserInfo(base.Request.Headers);

            #region 构造点赞信息
            List <int> friend_ids = dm_Friend_CircleEntities.Select(t => t.id).ToList();

            DataTable dataTable = null;
            IEnumerable <dm_friend_thumb_recordEntity> dm_friend_thumb_recordList = null;
            IEnumerable <dm_userEntity> dm_UserList = null;
            if (friend_ids.Count > 0)
            {
                #region 获取哆米圈文章的点赞记录
                dataTable = dm_Friend_Thumb_RecordIBLL.GetPraiseRecord(friend_ids);
                #endregion

                #region 获取我的点赞情况
                dm_friend_thumb_recordList = dm_Friend_Thumb_RecordIBLL.GetPraiseRecord(friend_ids, (int)dm_UserEntity.id);
                #endregion

                if (!IsGovernment)
                {
                    List <string> user_ids = dm_Friend_CircleEntities.Select(t => t.createcode).Distinct().ToList();//获取任务创建人
                    dm_UserList = dM_UserIBLL.GetUserListByIDS(user_ids);
                }
            }

            List <FriendCircleEntity> dyList = new List <FriendCircleEntity>();
            foreach (var item in dm_Friend_CircleEntities)
            {
                List <string> headPicList = new List <string>();
                int           MyPariseStatus = 0;
                string        NickName = "", HeadPic = "";
                if (IsGovernment)
                {
                    NickName = "哆来米";
                    HeadPic  = "http://dlaimi.cn/Content/Images/default.png";
                }
                else
                {
                    if (!dm_UserList.IsEmpty())
                    {
                        dm_userEntity Pub_UserEntity = dm_UserList.Where(t => item.createcode == t.id.ToString()).FirstOrDefault();
                        if (!Pub_UserEntity.IsEmpty())
                        {
                            NickName = Pub_UserEntity.nickname;
                            HeadPic  = Pub_UserEntity.headpic;
                        }
                    }
                }


                if (!dataTable.IsEmpty())
                {
                    DataRow[] dataRows = dataTable.Select(" friend_id=" + item.id);
                    foreach (DataRow itemRow in dataRows)
                    {
                        headPicList.Add(itemRow["headpic"].IsEmpty() ? "" : itemRow["headpic"].ToString());
                    }
                }

                if (!dm_friend_thumb_recordList.IsEmpty())
                {
                    dm_friend_thumb_recordEntity dm_Friend_Thumb_RecordEntity = dm_friend_thumb_recordList.Where(t => t.user_id == dm_UserEntity.id && t.friend_id == item.id).FirstOrDefault();
                    MyPariseStatus = dm_Friend_Thumb_RecordEntity.IsEmpty() ? 0 : (int)dm_Friend_Thumb_RecordEntity.status;
                }
                dyList.Add(new FriendCircleEntity
                {
                    TemplateDetail = item,
                    PraiseRecord   = headPicList,
                    MyPariseStatus = MyPariseStatus,
                    Pub_UserInfo   = new PubUserInfo {
                        NickName = NickName, HeadPic = HeadPic, PubTime = TimeConvert(item.createtime)
                    },
                    CacheKey = cacheKey
                });
            }
            #endregion

            return(dyList);
        }
Esempio n. 46
0
        private static ImmutableArray<AnalyzerReference> CreateAnalyzerReferencesFromPackages(
            IEnumerable<HostDiagnosticAnalyzerPackage> analyzerPackages,
            HostAnalyzerReferenceDiagnosticReporter reporter)
        {
            if (analyzerPackages == null || analyzerPackages.IsEmpty())
            {
                return ImmutableArray<AnalyzerReference>.Empty;
            }

            var analyzerAssemblies = analyzerPackages.SelectMany(p => p.Assemblies);

            var builder = ImmutableArray.CreateBuilder<AnalyzerReference>();
            foreach (var analyzerAssembly in analyzerAssemblies.Distinct(StringComparer.OrdinalIgnoreCase))
            {
                var reference = new AnalyzerFileReference(analyzerAssembly, s_assemblyLoader);
                reference.AnalyzerLoadFailed += reporter.OnAnalyzerLoadFailed;

                builder.Add(reference);
            }

            return builder.ToImmutable();
        }
Esempio n. 47
0
 public bool SetEquals(IEnumerable <T> other)
 {
     return(other.IsEmpty());
 }
Esempio n. 48
0
        // Adds the span surrounding the syntax list as a region.  The
        // snippet shown is the text from the first line of the first 
        // node in the list.
        public static OutliningSpan CreateRegion(IEnumerable<SyntaxNode> syntaxList, bool autoCollapse)
        {
            if (syntaxList.IsEmpty())
            {
                return null;
            }

            var end = GetCollapsibleEnd(syntaxList.Last().GetLastToken());

            var spanStart = syntaxList.First().GetFirstToken().FullSpan.End;
            var spanEnd = end >= spanStart
                ? end
                : spanStart;

            var hintSpanStart = syntaxList.First().SpanStart;
            var hintSpanEnd = end >= hintSpanStart
                ? end
                : hintSpanStart;

            return CreateRegion(
                textSpan: TextSpan.FromBounds(spanStart, spanEnd),
                hintSpan: TextSpan.FromBounds(hintSpanStart, hintSpanEnd),
                bannerText: Ellipsis,
                autoCollapse: autoCollapse);
        }
Esempio n. 49
0
 public static bool IsNullOrEmpty <T>(this IEnumerable <T> enumerable)
 {
     return(enumerable?.IsEmpty() ?? true);
 }
Esempio n. 50
0
 /// <summary>対象の列挙可能型がNullまたは空かどうかを判定する</summary>
 /// <typeparam name="T">型</typeparam>
 /// <param name="target">対象</param>
 /// <returns>空の場合に真</returns>
 public static bool IsNullOrEmpty <T>(this IEnumerable <T> target)
 {
     return(target?.IsEmpty() ?? true);
 }
Esempio n. 51
0
        public ServiceTermResponse CalculateTerms(Dictionary <string, object> arguments, DateTime startDate)
        {
            var response          = new ServiceTermResponse();
            var userConnectionArg = new ConstructorArgument("userConnection", UserConnection);
            var argumentsArg      = new ConstructorArgument("arguments", arguments);
            var selector          = ClassFactory.Get <CaseTermIntervalSelector>(userConnectionArg);
            //var termInterval = selector.Get(arguments) as CaseTermInterval;
            var termInterval = new CaseTermInterval();

            var d = "";

            termInterval.ResolveTerm            = new TimeTerm();
            termInterval.ResolveTerm.CalendarId = new Guid("F0FF1F0E-F46B-1410-1787-0026185BFCD3");
            termInterval.ResolveTerm.Type       = TimeUnit.WorkingHour;
            termInterval.ResolveTerm.Value      = 1;
            var mask = termInterval.GetMask();
            var intervalResolveTerm = 0;
            var procent             = 0;
            var userTimeZone        = UserConnection.CurrentUser.TimeZone;

            if (mask != CaseTermStates.None)
            {
                var intervalReader = ClassFactory.Get <CaseActiveIntervalReader>(userConnectionArg, argumentsArg);

                IEnumerable <DateTimeInterval> intervals = intervalReader.GetActiveIntervals();
                if (intervals.IsEmpty())
                {
                    //termInterval.ResolveTerm.Value = 10;
                    response = ExecuteCalculateTerms(startDate, termInterval, userTimeZone, mask);
                }
                else
                {
                    var dateTime = ConvertFromUtc(DateTime.UtcNow, userTimeZone);
                    response = ExecuteRecalculateTerms(dateTime, termInterval, intervals, userTimeZone, mask);
                }
            }
            //поиск порядка уведомлений ICLTimeToNotifyDic
            var caseId    = Guid.Parse(arguments["CaseId"].ToString());
            var accountId = Guid.Parse(arguments["AccountId"].ToString());
            var del       = new Delete(UserConnection).From("ICLCaseReminder")
                            .Where("ICLCaseId").IsEqual(new QueryParameter(caseId)) as Delete;

            del.Execute();
            if (termInterval.ResolveTerm.Type == TimeUnit.WorkingHour || termInterval.ResolveTerm.Type == TimeUnit.Hour)
            {
                intervalResolveTerm = termInterval.ResolveTerm.Value * 60;//минуты
            }
            if (termInterval.ResolveTerm.Type == TimeUnit.WorkingDay || termInterval.ResolveTerm.Type == TimeUnit.Day)
            {
                intervalResolveTerm = termInterval.ResolveTerm.Value * 60 * 24;//минуты
            }
            if (termInterval.ResolveTerm.Type == TimeUnit.WorkingMinute || termInterval.ResolveTerm.Type == TimeUnit.Minute)
            {
                intervalResolveTerm = termInterval.ResolveTerm.Value;//минуты
            }
            termInterval.ResolveTerm.Type = TimeUnit.WorkingMinute;

            var collnotify = FindCollectionTimeNotify(accountId);

            foreach (ICLTimeToNotifyDic notify in collnotify)
            {
                //проценты
                if (notify.ICLUnitId.Equals(new Guid("7a5e5d2d-7400-4469-9674-3a74d6b32de4")))
                {
                    termInterval.ResolveTerm.Value = intervalResolveTerm * notify.ICLValue / 100;
                }
                else
                {
                    termInterval.ResolveTerm.Value = notify.ICLValue;
                }
                var notifyTime = ExecuteCalculateTerms(startDate, termInterval, userTimeZone, mask);

                ICLCaseReminder iclCaseReminder = new ICLCaseReminder(UserConnection);
                iclCaseReminder.SetDefColumnValues();
                iclCaseReminder.ICLCaseId     = caseId;
                iclCaseReminder.ICLTimeSend   = notifyTime.SolutionTime.GetValueOrDefault();
                iclCaseReminder.ICLTimeRuleId = notify.Id;
                if (iclCaseReminder.ICLTimeSend < ConvertFromUtc(DateTime.UtcNow, userTimeZone))
                {
                    iclCaseReminder.ICLStatusId = new Guid("095CB711-8480-4EA5-9D25-E567648A3255"); //просрочена
                }
                else
                {
                    iclCaseReminder.ICLStatusId = new Guid("be9c92ca-b092-4950-8548-bb2160a61f8b");//не начата
                }
                iclCaseReminder.ICLOverTimeSolution = intervalResolveTerm - termInterval.ResolveTerm.Value;
                iclCaseReminder.Save();
            }
            return(response);
        }
        /// <summary>
        /// Creates a new compilation without the specified syntax trees. Preserves metadata info for use with trees
        /// added later. 
        /// </summary>
        public new CSharpCompilation RemoveSyntaxTrees(IEnumerable<SyntaxTree> trees)
        {
            using (Logger.LogBlock(FunctionId.CSharp_Compilation_RemoveSyntaxTrees, message: this.AssemblyName))
            {
                if (trees == null)
                {
                    throw new ArgumentNullException("trees");
                }

                if (trees.IsEmpty())
                {
                    return this;
                }

                bool referenceDirectivesChanged = false;
                var removeSet = new HashSet<SyntaxTree>();
                var declMap = rootNamespaces;
                var declTable = declarationTable;
                foreach (var tree in trees.Cast<CSharpSyntaxTree>())
                {
                    RemoveSyntaxTreeFromDeclarationMapAndTable(tree, ref declMap, ref declTable, ref referenceDirectivesChanged);
                    removeSet.Add(tree);
                }

                Debug.Assert(!removeSet.IsEmpty());

                // We're going to have to revise the ordinals of all
                // trees after the first one removed, so just build
                // a new map.
                var ordinalMap = ImmutableDictionary.Create<SyntaxTree, int>();
                var builder = ArrayBuilder<SyntaxTree>.GetInstance();
                int i = 0;
                foreach (var tree in this.SyntaxTrees)
                {
                    if (!removeSet.Contains(tree))
                    {
                        builder.Add(tree);
                        ordinalMap = ordinalMap.Add(tree, i++);
                    }
                }

                return UpdateSyntaxTrees(builder.ToImmutableAndFree(), ordinalMap, declMap, declTable, referenceDirectivesChanged);
            }
        }
Esempio n. 53
0
        internal Threat GetTarget()
        {
            IEnumerable <Threat> allThreats = this.GetAllThreats();

            foreach (Threat threat in allThreats)
            {
                threat.ThreatValue *= (float)(0.899999976158142 + (double)MBRandom.RandomFloat * 0.200000002980232);
            }
            if (this.currentThreat != null)
            {
                this.currentThreat = allThreats.SingleOrDefault <Threat>((Func <Threat, bool>)(t => t.Equals((object)this.currentThreat)));
                if (this.currentThreat != null)
                {
                    this.currentThreat.ThreatValue *= 2f;
                }
            }
            IEnumerable <Threat> source = allThreats.Where <Threat>((Func <Threat, bool>)(t =>
            {
                if ((t.WeaponEntity != null || t.Agent != null) && this.Weapon.CanShootAtBox(t.BoundingBoxMin, t.BoundingBoxMax))
                {
                    return(true);
                }
                return(t.Formation != null && t.Formation.GetCountOfUnitsWithCondition((Func <Agent, bool>)(agent =>
                {
                    RangedSiegeWeapon weapon = this.Weapon;
                    CapsuleData collisionCapsule = agent.CollisionCapsule;
                    Vec3 boxMin = collisionCapsule.GetBoxMin();
                    collisionCapsule = agent.CollisionCapsule;
                    Vec3 boxMax = collisionCapsule.GetBoxMax();
                    return weapon.CanShootAtBox(boxMin, boxMax);
                })) > 0);
            }));

            if (source.IsEmpty <Threat>())
            {
                return((Threat)null);
            }
            this.currentThreat = source.MaxBy <Threat, float>((Func <Threat, float>)(t => t.ThreatValue));
            if (this.currentThreat.WeaponEntity == null)
            {
                if (this.targetAgent != null && this.targetAgent.IsActive() && this.currentThreat.Formation.HasUnitsWithCondition((Func <Agent, bool>)(agent => agent == this.targetAgent)))
                {
                    RangedSiegeWeapon weapon           = this.Weapon;
                    CapsuleData       collisionCapsule = this.targetAgent.CollisionCapsule;
                    Vec3 boxMin = collisionCapsule.GetBoxMin();
                    collisionCapsule = this.targetAgent.CollisionCapsule;
                    Vec3 boxMax = collisionCapsule.GetBoxMax();
                    if (weapon.CanShootAtBox(boxMin, boxMax))
                    {
                        goto label_15;
                    }
                }
                float selectedAgentScore = float.MaxValue;
                Agent selectedAgent      = this.targetAgent;
                this.currentThreat.Formation.ApplyActionOnEachUnit((Action <Agent>)(agent =>
                {
                    float num = agent.Position.DistanceSquared(this.Weapon.GameEntity.GlobalPosition) * (float)((double)MBRandom.RandomFloat * 0.200000002980232 + 0.800000011920929);
                    if (agent == this.targetAgent)
                    {
                        num *= 0.5f;
                    }
                    if ((double)selectedAgentScore <= (double)num || !this.Weapon.CanShootAtBox(agent.CollisionCapsule.GetBoxMin(), agent.CollisionCapsule.GetBoxMax()))
                    {
                        return;
                    }
                    selectedAgent      = agent;
                    selectedAgentScore = num;
                }));
                this.targetAgent         = selectedAgent ?? this.currentThreat.Formation.GetUnitWithIndex(MBRandom.RandomInt(this.currentThreat.Formation.CountOfUnits));
                this.currentThreat.Agent = this.targetAgent;
            }
label_15:
            this.targetAgent = (Agent)null;
            return(this.currentThreat.WeaponEntity == null && this.currentThreat.Agent == null ? (Threat)null : this.currentThreat);
        }