示例#1
1
 public string GenerateTestFixture(IEnumerable<Test> tests, string fileName)
 {
     var generator = new CodeGenerator(TemplateEnum.MbUnitTestFixture, TestText, MethodText, PropertyText, TypeText,
                                       AssertText);
     var code = generator.GenerateTestFixture(tests.ToList(), fileName);
     return code;
 }
 public static bool RequiresRenumbering(IEnumerable<int> numbers)
 {
     List<int> SortedList = Renumber(numbers.ToList());
     if (AreEqual(numbers.ToList(), SortedList))
         return false;
     return true;
 }
示例#3
0
        public ActionResult Manage(IEnumerable<RoleRights> changes)
        {
            MasterService srv = new MasterService(_Session.MasterTbl);
            bool CanCommit = true; string err = "";
            //Make sure If there's any DELETE - it is NOT being referred
            CanCommit = !MasterController.isDeletedBeingReferred(changes, true, ref err);//.Cast<Master>().ToList()
            //Check duplicates among New records only
            if (CanCommit && changes != null && changes.ToList<Master>().Exists(r => r.IsAdded))
                CanCommit = !MasterController.hasDuplicateInNewEntries(changes, ref err);

            #region All OK so go ahead
            if (CanCommit)//Commit
            {
                new SecurityService().BulkAddEditDel(changes.ToList<RoleRights>());//Performs Add, Edit & Delete by chacking each item
                base.operationSuccess = true; // Set operation sucess
                //Log Activity
                new ActivityLogService(ActivityLogService.Activity.RoleManage).Add(new CPM.DAL.ActivityHistory());
            }
            else // worst case or hack
                return Json(err, JsonRequestBehavior.AllowGet);

            #endregion

            return Json(string.Empty, JsonRequestBehavior.AllowGet);
        }
        // Calcul des soldes opérations pour une série d'opérations et une série de comte banque
        public void EnrichirAvecSoldeArchivable(IEnumerable<Budget> budgets)
        {
            // Reset solde opérations
            budgets.ToList().ForEach(c => c.SoldeOperationArchivables = 0.0M);
            budgets.ToList().ForEach(c => c.SoldeFinancementArchivables = 0.0M);
            budgets.ToList().ForEach(c => c.SoldeProvisionArchivables = 0.0M);
            budgets.ToList().ForEach(c => c.SoldeArchivable = 0.0M);

            // Contrats
            var s1 = new BudgetContratEnrichisseur(uow, groupeId);
            s1.EnrichirAvecNbContrats(budgets);

            // Inputs: opérations
            FacadeRepo facade = new FacadeRepo(uow, groupeId);
            InputSoldeBudgets inputs = facade.InputSoldeArchivableBudgets(dateLimiteArchivage);

            // Enrichissement solde des opérations
            var enrichisseur = new BudgetSoldeOperationArchivableEnrichisseur();
            enrichisseur.Executer(inputs, budgets);

            // Enrichissement solde archive
            foreach (var budget in budgets)
            {
                budget.EnrichirAvecSoldeArchivable();
            }
        }
示例#5
0
 public string[] GetFormattedTicket(Ticket ticket, IEnumerable<Order> lines, PrinterTemplate printerTemplate)
 {
     var orders = printerTemplate.MergeLines ? MergeLines(lines.ToList()) : lines.ToList();
     ticket.Orders.Clear();
     orders.ToList().ForEach(ticket.Orders.Add);
     var content = _ticketValueChanger.GetValue(printerTemplate, ticket);
     content = UpdateExpressions(content);
     return content.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries).ToArray();
 }
        private static IList<SignatureHelpItem> Filter(IEnumerable<SignatureHelpItem> items, IEnumerable<string> parameterNames)
        {
            if (parameterNames == null)
            {
                return items.ToList();
            }

            var filteredList = items.Where(i => Include(i, parameterNames)).ToList();
            return filteredList.Count == 0 ? items.ToList() : filteredList;
        }
示例#7
0
        public MagicCard(Bitmap cameraBitmap, IEnumerable<IntPoint> corners)
        {
            this.CameraBitmap = cameraBitmap;

            QuadrilateralTransformation transformFilter = new QuadrilateralTransformation(corners.ToList(), 211, 298);
            this.CardBitmap = transformFilter.Apply(cameraBitmap);

            QuadrilateralTransformation cardArtFilter = new QuadrilateralTransformation(artCorners.ToList(), 183, 133);
            this.CardArtBitmap = cardArtFilter.Apply(this.CardBitmap);

            this.Corners = corners.ToList();
        }
示例#8
0
        public void AddEntities(string variable, IEnumerable<IPersistIfcEntity> entities)
        {
            FixVariableName(ref variable);
            if (IsDefined(variable))
            {
                _data[variable] = _data[variable].Union(entities.ToList());
            }
            else
                _data.Add(variable, entities.ToList());

            _lastVariable = variable;
        }
 public JeapieResponse SendToConcreteSubscribers(IEnumerable<string> emails, string message, string title ="",
                                                 JeapieMessagePriority priority = DefaultPriority)
 {
     var  validationCollection = ParameterValidator.ValidateArguments(message, emails.ToList());
     var  result = HttpClient.Request(providerKey,
                                         message,
                                         title,
                                         emails.ToList(),
                                         JeapieRequestType.SendToConcreteSubscribers,
                                         priority);
     result.ValidationResults.AddRange(validationCollection);
     return result;
 }
        public EjectStorageDomainSpectraS3Request(IEnumerable<Ds3Object> objects, string storageDomainId)
        {
            this.StorageDomainId = storageDomainId;
            this.Objects = objects.ToList();
            this.QueryParams.Add("operation", "eject");

            this.QueryParams.Add("storage_domain_id", storageDomainId);

            if (!objects.ToList().TrueForAll(obj => obj.Size.HasValue))
            {
                throw new Ds3RequestException(Resources.ObjectsMissingSizeException);
            }
        }
示例#11
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ValidationResult"/> class.
 /// </summary>
 /// <param name="elementResults">The element results.</param>
 /// <param name="fieldResults">The field results.</param>
 /// <param name="childResults">The child results.</param>
 public ValidationResult(IEnumerable<ValidationElementResult> elementResults, IEnumerable<IValidationFieldResult> fieldResults, IEnumerable<ValidationResult> childResults)
 {
     ElementDirectResults = elementResults.ToList();
     ElementDirectFailures = elementResults.Where(result => result.Result.CountsAsFailure).ToList();
     ElementResults = childResults.SelectMany(res => res.ElementResults).Union(elementResults.ToList()).ToList();
     ElementFailures = ElementResults.Where(result => result.Result.CountsAsFailure);
     Results = childResults.SelectMany(res => res.Failures).Union(fieldResults.ToList()).ToList();
     Failures = Results.Where(result => result.CountsAsFailure);
     ElementResultsCount = ElementResults.AsBindable().Count();
     ElementFailureCount = ElementFailures.AsBindable().Count();
     ResultsCount = Results.AsBindable().Count();
     FailureCount = Failures.AsBindable().Count();
     IsSuccessful = FailureCount.Project(count => count == 0);
 }
示例#12
0
        public Action PrepareToExecute(IEnumerable<CacheElement> toInsert)
        {
            var insertList = toInsert.ToList();

            return () => 
            {
                foreach (var v in insertList) 
                {
                    try 
                    {
                        this.Checked(raw.sqlite3_bind_text(insertOp, 1, v.Key));

                        if (String.IsNullOrWhiteSpace(v.TypeName)) 
                        {
                            this.Checked(raw.sqlite3_bind_null(insertOp, 2));
                        } 
                        else 
                        {
                            this.Checked(raw.sqlite3_bind_text(insertOp, 2, v.TypeName));
                        }

                        this.Checked(raw.sqlite3_bind_blob(insertOp, 3, v.Value));
                        this.Checked(raw.sqlite3_bind_int64(insertOp, 4, v.Expiration.Ticks));
                        this.Checked(raw.sqlite3_bind_int64(insertOp, 5, v.CreatedAt.Ticks));

                        this.Checked(raw.sqlite3_step(insertOp));
                    } 
                    finally 
                    {
                        this.Checked(raw.sqlite3_reset(insertOp));
                    }
                }
            };
        }
示例#13
0
        public static List<Obj_AI_Base> GetDashObjects(IEnumerable<Obj_AI_Base> predefinedObjectList = null)
        {
            var objects = predefinedObjectList != null ? predefinedObjectList.ToList() : ObjectManager.Get<Obj_AI_Base>().Where(o => o.LSIsValidTarget(ObjectManager.Player.AttackRange)).ToList();
            var apexPoint = ObjectManager.Player.ServerPosition.ToVector2() + (ObjectManager.Player.ServerPosition.ToVector2() - Game.CursorPos.ToVector2()).LSNormalized() * ObjectManager.Player.AttackRange;

            return objects.Where(o => IsLyingInCone(o.ServerPosition.ToVector2(), apexPoint, ObjectManager.Player.ServerPosition.ToVector2(), Math.PI)).OrderBy(o => o.LSDistanceSquared(apexPoint)).ToList();
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ShardedMongoServerProxy"/> class.
        /// </summary>
        /// <param name="server">The server.</param>
        /// <param name="instances">The instances.</param>
        /// <param name="connectionQueue">The state change queue.</param>
        /// <param name="connectionAttempt">The connection attempt.</param>
        /// <remarks>This constructor is used when the instances have already been instructed to connect.</remarks>
        protected MultipleInstanceMongoServerProxy(MongoServer server, IEnumerable<MongoServerInstance> instances, BlockingQueue<MongoServerInstance> connectionQueue, int connectionAttempt)
        {
            _state = MongoServerState.Connecting;
            _server = server;
            _connectedInstances = new ConnectedInstanceCollection();
            _connectionAttempt = connectionAttempt;

            _outstandingInstanceConnections = connectionQueue.Count;
            ThreadPool.QueueUserWorkItem(_ =>
            {
                while (connectionQueue.Count > 0)
                {
                    var instance = connectionQueue.Dequeue();
                    Interlocked.Decrement(ref _outstandingInstanceConnections);
                }
            });

            // It's important to have our own copy of this list because it might get modified during iteration. 
            _instances = instances.ToList();
            foreach (var instance in instances)
            {
                instance.StateChanged += InstanceStateChanged;
                ProcessInstanceStateChange(instance);
            }
        }
        public ComposeEmailViewModel(IEnumerable<Video> videos)
        {

            Videos = videos.ToList();
            Message = new Message();

        }
 public int UpdateMany(string tableName, IEnumerable<IDictionary<string, object>> data,
                       IAdapterTransaction transaction, IList<string> keyFields)
 {
     IBulkUpdater bulkUpdater = ProviderHelper.GetCustomProvider<IBulkUpdater>(ConnectionProvider) ??
                                new BulkUpdater();
     return bulkUpdater.Update(this, tableName, data.ToList(), ((AdoAdapterTransaction)transaction).DbTransaction);
 }
        public HasPassengers(string title, IEnumerable<ProtoCrewMember> passengers)
            : base(title)
        {
            this.passengers = passengers.ToList();

            CreateDelegates();
        }
示例#18
0
 public ContentTypeDefinition(string name, string displayName, IEnumerable<ContentTypePartDefinition> parts, JObject settings)
 {
     Name = name;
     DisplayName = displayName;
     Parts = parts.ToList();
     Settings = settings;
 }
示例#19
0
        public void Write(IEnumerable<CommandRegistry> commands)
        {
            var list = commands.ToList();

            Writer.WriteLine("Commands found: {0}", list.Count);

            foreach (var cmd in list)
            {
                Blank();

                Writer.Write("Command: ");
                WriteCommandName(cmd.Command, cmd.Parser);

                var options = cmd.Parser.Options.ToList();

                if (options.Count > 0)
                {
                    Writer.WriteLine("Available options:");
                    foreach (var option in cmd.Parser.Options)
                        Writer.WriteLine("> {0} [{1}]", option.Name, option.Member.Type.GetRealClassName());
                }
                else
                {
                    Writer.WriteLine("No available options.");
                }
            }
        }
示例#20
0
        public AirNet( IEnumerable< CompAir > newNodes, NetLayer layer, CompAir root )
        {
            Layer = layer;
            var compAirs = newNodes.ToList();

            foreach ( var current in compAirs )
            {
                RegisterNode( current );
                current.connectedNet = this;
            }

            checked
            {
                debugId = debugIdNext++;
            }
            this.root = root;

            var intake =
                compAirs.Where( s => s.GetType() == typeof ( CompAirTrader ) )
                        .Cast< CompAirTrader >()
                        .ToList()
                        .Find(
                            s =>
                                s.parent.def.defName == "RedistHeat_DuctIntake" ||
                                s.parent.def.defName == "RedistHeat_DuctCooler" );

            if ( intake == null || intake.netTemp == 999 )
            {
                NetTemperature = GenTemperature.OutdoorTemp;
            }
            else
            {
                NetTemperature = intake.netTemp;
            }
        }
示例#21
0
        public static ExecutionRequestParameters Create(Guid processId, IEnumerable<ParameterDefinitionWithValue> parameters, ActivityDefinition activityToExecute, ConditionDefinition condition, bool isPreExecution)
        {
            List<ActionDefinitionForActivity> implementation = isPreExecution
                                                                   ? activityToExecute.PreExecutionImplemementation
                                                                   : activityToExecute.Implemementation;

            if (parameters == null) throw new ArgumentNullException("parameters");
            var parametersList = parameters.ToList();

            var methods = new List<MethodToExecuteInfo>(implementation.Count);
            var executionParameters = new ExecutionRequestParameters
                                          {
                                              ProcessId = processId,
                                              ConditionType = condition.Type,
                                              ConditionResultOnPreExecution = condition.ResultOnPreExecution,
                                              ConditionMethod = condition.Type == ConditionType.Action ? GetMethodToExecuteInfo(parametersList, ActionDefinition.Create(condition.Action, 0)) : null,
                                          };

            methods.AddRange(implementation.Select(method => GetMethodToExecuteInfo(parametersList, method)));

            var parameters1 = new List<ParameterContainerInfo>();

            parameters1.AddRange(parameters.Where(p => p.Name != DefaultDefinitions.ParameterExecutedActivityState.Name).Select(p => new ParameterContainerInfo() { Name = p.Name, Type = p.Type, Value = p.Value }));
            parameters1.Add(new ParameterContainerInfo{Name = DefaultDefinitions.ParameterExecutedActivityState.Name,Type = DefaultDefinitions.ParameterExecutedActivityState.Type,Value = activityToExecute.State});
            executionParameters.ParameterContainer = parameters1.ToArray();
            executionParameters.Methods = methods.ToArray();

            executionParameters.ActivityName = activityToExecute.Name;

            return executionParameters;
        }
        public virtual void AddLocals(IEnumerable<ParameterDeclaration> declarations, AstNode statement)
        {
            declarations.ToList().ForEach(item =>
            {
                var name = this.Emitter.GetEntityName(item);
                var vName = this.AddLocal(item.Name, item.Type);

                if (item.ParameterModifier == ParameterModifier.Out || item.ParameterModifier == ParameterModifier.Ref)
                {
                    this.Emitter.LocalsMap[item.Name] = name + ".v";
                }
                else
                {
                    this.Emitter.LocalsMap[item.Name] = name;
                }
            });

            var visitor = new ReferenceArgumentVisitor();
            statement.AcceptVisitor(visitor);

            foreach (var expr in visitor.DirectionExpression)
            {
                var rr = this.Emitter.Resolver.ResolveNode(expr, this.Emitter);

                if (rr is LocalResolveResult && expr is IdentifierExpression)
                {
                    var ie = (IdentifierExpression)expr;
                    this.Emitter.LocalsMap[ie.Identifier] = ie.Identifier + ".v";
                }
                else
                {
                    throw new EmitterException(expr, "Only local variables can be passed by reference");
                }
            }
        }
        /// <summary>
        /// Asynchronously sends a batch of event data to the same partition.
        /// All the event data in the batch need to have the same value in the Partitionkey property.
        /// If the batch size is greater than the maximum batch size, 
        /// the method partitions the original batch into multiple batches, 
        /// each smaller in size than the maximum batch size.
        /// </summary>
        /// <param name="eventHubClient">The current EventHubClient object.</param>
        /// <param name="eventDataEnumerable">An IEnumerable object containing event data instances.</param>
        /// <param name="trace">true to cause a message to be written; otherwise, false.</param>
        public static void SendPartitionedBatch(this EventHubClient eventHubClient, IEnumerable<EventData> eventDataEnumerable, bool trace = false)
        {
            var eventDataList = eventDataEnumerable as IList<EventData> ?? eventDataEnumerable.ToList();
            if (eventDataEnumerable == null || !eventDataList.Any())
            {
                throw new ArgumentNullException(EventDataListCannotBeNullOrEmpty);
            }

            var batchList = new List<EventData>();
            long batchSize = 0;

            foreach (var eventData in eventDataList)
            {
                if ((batchSize + eventData.SerializedSizeInBytes) > 262144)
                {
                    // Send current batch
                    eventHubClient.SendBatch(batchList);
                    Trace.WriteLineIf(trace, string.Format(SendPartitionedBatchFormat, batchSize, batchList.Count));

                    // Initialize a new batch
                    batchList = new List<EventData> { eventData };
                    batchSize = eventData.SerializedSizeInBytes;
                }
                else
                {
                    // Add the EventData to the current batch
                    batchList.Add(eventData);
                    batchSize += eventData.SerializedSizeInBytes;
                }
            }
            // The final batch is sent outside of the loop
            eventHubClient.SendBatch(batchList);
            Trace.WriteLineIf(trace, string.Format(SendPartitionedBatchFormat, batchSize, batchList.Count));
        }
示例#24
0
        public static Solid CreateFromIntersectingPlanes(IEnumerable<Plane> planes, IDGenerator generator)
        {
            var solid = new Solid(generator.GetNextObjectID());
            var list = planes.ToList();
            for (var i = 0; i < list.Count; i++)
            {
                // Split the polygon by all the other planes
                var poly = new Polygon(list[i]);
                for (var j = 0; j < list.Count; j++)
                {
                    if (i != j) poly.Split(list[j]);
                }

                // The final polygon is the face
                var face = new Face(generator.GetNextFaceID()) { Plane = poly.Plane , Parent = solid };
                face.Vertices.AddRange(poly.Vertices.Select(x => new Vertex(x, face)));
                face.UpdateBoundingBox();
                face.AlignTextureToWorld();
                solid.Faces.Add(face);
            }

            // Ensure all the faces point outwards
            var origin = solid.GetOrigin();
            foreach (var face in solid.Faces)
            {
                if (face.Plane.OnPlane(origin) >= 0) face.Flip();
            }

            solid.UpdateBoundingBox();
            return solid;
        }
示例#25
0
        public void UpdateConsumerSubscriptionTopics(string consumerId, IEnumerable<string> subscriptionTopics)
        {
            var subscriptionTopicChanged = false;
            IEnumerable<string> oldSubscriptionTopics = new List<string>();
            IEnumerable<string> newSubscriptionTopics = new List<string>();

            _consumerSubscriptionTopicDict.AddOrUpdate(consumerId,
            key =>
            {
                subscriptionTopicChanged = true;
                newSubscriptionTopics = subscriptionTopics;
                return subscriptionTopics;
            },
            (key, old) =>
            {
                if (IsStringCollectionChanged(old.ToList(), subscriptionTopics.ToList()))
                {
                    subscriptionTopicChanged = true;
                    oldSubscriptionTopics = old;
                    newSubscriptionTopics = subscriptionTopics;
                }
                return subscriptionTopics;
            });

            if (subscriptionTopicChanged)
            {
                _logger.InfoFormat("Consumer subscription topics changed. groupName:{0}, consumerId:{1}, old:{2}, new:{3}", _groupName, consumerId, string.Join("|", oldSubscriptionTopics), string.Join("|", newSubscriptionTopics));
            }
        }
 /// <summary>
 /// Constructs a new playlist object
 /// </summary>
 /// <param name="medium">The medium the playlist belongs to</param>
 /// <param name="persistentID">The persistent ID of the playlist</param>
 /// <param name="name">The name of the playlist</param>
 /// <param name="trackIDs">List of IDs of tracks which are part of the playlist</param>
 public Playlist(Medium medium, string persistentID, string name, IEnumerable<string> trackIDs)
     : this(medium)
 {
     this.PersistentID = persistentID;
     this.Name = name;
     this.SetTracks(trackIDs.ToList());
 }
 public RedisSentinelResolver(RedisSentinel sentinel, IEnumerable<RedisEndpoint> masters, IEnumerable<RedisEndpoint> slaves)
 {
     this.sentinel = sentinel;
     ResetMasters(masters.ToList());
     ResetSlaves(slaves.ToList());
     ClientFactory = RedisConfig.ClientFactory;
 }
 public void Store(string messageId, IEnumerable<TransportOperation> transportOperations)
 {
     if (!storage.TryAdd(messageId, new StoredMessage(messageId, transportOperations.ToList())))
     {
         throw new Exception(string.Format("Outbox message with id '{0}' is already present in storage.", messageId));
     }
 }
示例#29
0
        public void UpdateConsumerConsumingQueues(string consumerId, IEnumerable<string> consumingQueues)
        {
            var consumingQueueChanged = false;
            IEnumerable<string> oldConsumingQueues = new List<string>();
            IEnumerable<string> newConsumingQueues = new List<string>();

            _consumerConsumingQueueDict.AddOrUpdate(consumerId,
            key =>
            {
                newConsumingQueues = consumingQueues;
                if (consumingQueues.Count() > 0)
                {
                    consumingQueueChanged = true;
                }
                return consumingQueues;
            },
            (key, old) =>
            {
                if (IsStringCollectionChanged(old.ToList(), consumingQueues.ToList()))
                {
                    consumingQueueChanged = true;
                    oldConsumingQueues = old;
                    newConsumingQueues = consumingQueues;
                }
                return consumingQueues;
            });

            if (consumingQueueChanged)
            {
                _logger.InfoFormat("Consumer consuming queues changed. groupName:{0}, consumerId:{1}, old:{2}, new:{3}", _groupName, consumerId, string.Join("|", oldConsumingQueues), string.Join("|", newConsumingQueues));
            }
        }
示例#30
0
 public override void LoadTextures(IEnumerable<TextureItem> items)
 {
     var list = items.ToList();
     var packages = list.Select(x => x.Package).Distinct();
     try
     {
         HLLib.Initialize();
         foreach (var package in packages)
         {
             var p = package;
             using (var pack = new HLLib.Package(p.PackageFile))
             {
                 var folder = pack.GetRootFolder();
                 foreach (var ti in list.Where(x => x.Package == p))
                 {
                     var item = folder.GetItemByName(ti.Name + ".bmp", HLLib.FindType.Files);
                     if (!item.Exists) continue;
                     using (var stream = pack.CreateStream(item))
                     {
                         var bmp = new Bitmap(new MemoryStream(stream.ReadAll()));
                         bool hasTransparency;
                         bmp = PostProcessBitmap(ti.Name, bmp, out hasTransparency);
                         TextureHelper.Create(ti.Name.ToLowerInvariant(), bmp, hasTransparency);
                         bmp.Dispose();
                     }
                 }
             }
         }
     }
     finally
     {
         HLLib.Shutdown();
     }
 }
示例#31
0
 public static IReadOnlyList <T> ToReadOnlyListFast <T>(this IEnumerable <T> enumerable)
 => enumerable as IReadOnlyList <T> ?? enumerable?.ToList() ?? (IReadOnlyList <T>)Array.Empty <T>();
 public BulkDownloadFileResponse(IEnumerable <DownloadFileResponse> files)
 {
     Files = files?.ToList() ?? new List <DownloadFileResponse>();
 }
示例#33
0
 /// <summary>
 /// Creates a new <see cref="TransformBuilder"/>
 /// </summary>
 public TransformBuilder(IServiceProvider services, IEnumerable <ITransformFactory> factories, IEnumerable <ITransformProvider> providers)
 {
     _services  = services ?? throw new ArgumentNullException(nameof(services));
     _factories = factories?.ToList() ?? throw new ArgumentNullException(nameof(factories));
     _providers = providers?.ToList() ?? throw new ArgumentNullException(nameof(providers));
 }
示例#34
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="results"></param>
 public VulcanSearchHitList(IEnumerable <VulcanSearchHit> results)
 {
     _took    = -1;
     _results = results?.ToList();
 }
示例#35
0
 public AQRDataStream(IQRDataStreamEncodingFormat format, IEnumerable <IQRDataStreamData> payload = null)
 {
     this.format  = format;
     this.payload = payload?.ToList() ?? new List <IQRDataStreamData>();
 }
示例#36
0
 /// <summary>
 /// Parses a list even if value = null
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="value"></param>
 /// <returns></returns>
 public static List <T> ParseList <T>(this IEnumerable <T> value)
 {
     return(value?.ToList() ?? new List <T>());
 }
示例#37
0
 protected Controller(IEnumerable <IProvider <TMsg> > providers)
 {
     Providers = providers?.ToList() ?? new List <IProvider <TMsg> >(0);
 }
示例#38
0
 public Task <bool> BlockIPAddresses(string ruleNamePrefix, IEnumerable <IPAddressRange> ranges, IEnumerable <PortRange> allowedPorts = null, CancellationToken cancelToken = default)
 {
     // for performance, ranges is assumed to be sorted
     lock (this)
     {
         ruleNamePrefix = ScrubRuleNamePrefix(ruleNamePrefix);
         List <IPAddressRange> rangesList = new List <IPAddressRange>(ranges);
         blockRulesRanges[ruleNamePrefix] = new MemoryFirewallRuleRanges(rangesList, allowedPorts?.ToList(), true);
     }
     return(Task.FromResult <bool>(true));
 }
示例#39
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ChatUpdate"/> class.
 /// </summary>
 /// <param name="channels">The <see cref="IEnumerable{T}"/> that forms the value of <see cref="Channels"/>.</param>
 public ChatUpdate(IEnumerable <ChannelRepresentation> channels)
 {
     Channels = channels?.ToList() ?? throw new ArgumentNullException(nameof(channels));
 }
示例#40
0
 public CacheInvalidationBehavior(IEnumerable <ICacheInvalidator <TRequest> > cacheInvalidators)
 {
     _cacheInvalidators = cacheInvalidators?.ToList();
 }
 public SpecificationValidationResult(bool isValid, IEnumerable <ValidationFailure> errors)
 {
     IsValid = isValid;
     Errors  = errors?.ToList().AsReadOnly() ?? new List <ValidationFailure>().AsReadOnly();
 }
示例#42
0
 public async Task <List <TElement> > Convert <TMessage>(InitializeContext <TMessage> context, IEnumerable <TElement> input)
     where TMessage : class
 {
     return(input?.ToList());
 }
示例#43
0
        public ActionContext(
            string contextGroupName                = "default",
            [CallerMemberName] string name         = null,
            ActionContextSettings settings         = null,
            IEnumerable <ISanitizer> logSanitizers = null)
        {
            _logSanitizers = logSanitizers?.ToList();

            _stopwatch = new Stopwatch();
            _stopwatch.Start();

            _asyncLocalStacks.Value ??= new ConcurrentDictionary <string, ActionContextStack>();
            _namedStacks = _asyncLocalStacks.Value;
            _stack       = _namedStacks.GetOrAdd(contextGroupName, new ActionContextStack());

            _parent = _stack.Peek();
            _stack.Push(this);

            var id            = Guid.NewGuid();
            var causationId   = _parent?.Info.Id ?? id;
            var correlationId = _stack.CorrelationId;

            if (_parent == null)
            {
                Settings = settings ?? new ActionContextSettings();

                Info = new ContextInfo(
                    true,
                    0,
                    name,
                    contextGroupName,
                    _stack.CorrelationId);

                State  = new ContextState(_logSanitizers);
                Logger = new ContextLogger(this);
            }
            else
            {
                Settings = _parent.Settings;

                Info = new ContextInfo(
                    false,
                    _parent.Info.Depth + 1,
                    name,
                    contextGroupName,
                    _stack.CorrelationId,
                    _parent?.Info?.Id);

                State  = _parent.State;
                Logger = _parent.Logger;

                Logger.TrySetContext(this);
            }

            var entryType = Info.IsRoot ? ContextLogEntryType.ContextStart : ContextLogEntryType.ChildContextStart;

            Logger.LogAsType(Settings.ContextStartMessageLevel,
                             $"Context {Info.ContextName} has started.", entryType);

            Loaded?.Invoke(this);
        }
示例#44
0
 public ColumnParameter(string name, ISqlParameterType type, IEnumerable <IColumnConstraint> constraints)
 {
     Name        = name;
     Type        = type;
     Constraints = constraints?.ToList();
 }
示例#45
0
 /// <summary>
 /// Constructs <see cref="FilterChain64"/> from collection of <paramref name="filters"/>.
 /// </summary>
 /// <param name="filters">Collection of online filters</param>
 public FilterChain64(IEnumerable<IOnlineFilter64> filters = null)
 {
     _filters = filters?.ToList() ?? new List<IOnlineFilter64>();
 }
 public CompositeTypeInspector(IEnumerable <ITypeInspector> typeInspectors)
 {
     this.typeInspectors = typeInspectors?.ToList() ?? throw new ArgumentNullException(nameof(typeInspectors));
 }
示例#47
0
 public InlineLayout(IEnumerable <ILayout> elements, double top, double bottom)
 {
     Elements = elements?.ToList() ?? new List <ILayout>(0);
     Top      = top;
     Bottom   = bottom;
 }
示例#48
0
 /// <summary>
 /// Initializes the query with the specified parameters.
 /// </summary>
 /// <param name="pageIds">PageIds of the pages to get.</param>
 /// <param name="workFlowStatus">Used to determine which version of the page to include data for.</param>
 public GetPageRenderDetailsByIdRangeQuery(IEnumerable <int> pageIds, PublishStatusQuery?workFlowStatus = null)
     : this(pageIds?.ToList())
 {
 }
 internal PolicyWrapper(IEnumerable <PolicyBase> policySettings, Func <ServiceStatus> getStatus) : base(getStatus)
 {
     mPolicySettings = policySettings?.ToList() ?? new List <PolicyBase>();
 }
示例#50
0
 public GridLayout(IEnumerable <GridColumnLayout> columns, double top, double bottom)
 {
     Columns = columns?.ToList() ?? new List <GridColumnLayout>(0);
     Top     = top;
     Bottom  = bottom;
 }
示例#51
0
 public ChatroomChangedNotification(int chatroomId, string chatroomName, IEnumerable <int> participants)
 {
     ChatroomId   = chatroomId;
     ChatroomName = chatroomName;
     Participants = participants?.ToList() ?? throw new ArgumentNullException(nameof(participants));
 }
示例#52
0
 internal static List <T> AsInstanceOrToListOrDefault <T>(this IEnumerable <T> list) => list as List <T> ?? list?.ToList <T>() ?? new List <T>();
示例#53
0
 public GetImageAssetEntityMicroSummariesByIdRangeQuery(
     IEnumerable <int> ids
     )
     : this(ids?.ToList())
 {
 }
示例#54
0
 internal static List <T> AsInstanceOrToListOrNull <T>(this IEnumerable <T> list) => list as List <T> ?? list?.ToList <T>();
示例#55
0
 public QuizServiceClientFake(IEnumerable <Quiz> expectedQuizzes)
 {
     _quizzes = expectedQuizzes?.ToList();
 }
示例#56
0
 public ActivityResponse(string text, IEnumerable <AttachmentResponse> attachments = null)
 {
     this.Text        = text;
     this.Attachments = attachments?.ToList() ?? new List <AttachmentResponse>();
 }
 public new static void Choice <T>(IDialogContext context, ResumeAfter <T> resume, IEnumerable <T> options, string prompt, string retry = null, int attempts = 3, PromptStyle promptStyle = PromptStyle.Auto, IEnumerable <string> descriptions = null)
 {
     if (!(context is TranslatingDialogContext))
     {
         context = new TranslatingDialogContext(context);
     }
     Choice(context, resume, new PromptOptions <T>(prompt, retry, attempts: attempts, options: options.ToList(), promptStyler: new PromptStyler(promptStyle), descriptions: descriptions?.ToList()));
 }
示例#58
0
        /// <summary>
        /// Use the parameter path to extensions
        /// </summary>
        public void UpdateExtensions(IEnumerable <string> additionalExtensionsPath, bool shouldLoadOnlyWellKnownExtensions)
        {
            lock (this.lockForExtensionsUpdate)
            {
                EqtTrace.Verbose(
                    "TestPluginCache: Updating loadOnlyWellKnownExtensions from {0} to {1}.",
                    this.loadOnlyWellKnownExtensions,
                    shouldLoadOnlyWellKnownExtensions);

                this.loadOnlyWellKnownExtensions = shouldLoadOnlyWellKnownExtensions;

                List <string> extensions = additionalExtensionsPath?.ToList();
                if (extensions == null || extensions.Count == 0)
                {
                    return;
                }

                string extensionString;
                if (this.pathToExtensions != null &&
                    extensions.Count == this.pathToExtensions.Count() &&
                    extensions.All(e => this.pathToExtensions.Contains(e)))
                {
                    extensionString = this.pathToExtensions != null
                                          ? string.Join(",", this.pathToExtensions.ToArray())
                                          : null;

                    EqtTrace.Verbose(
                        "TestPluginCache: Ignoring the new extensions update as there is no change. Current extensions are '{0}'.",
                        extensionString);

                    return;
                }

                // Don't do a strict check for existence of the extension path. The extension paths may or may
                // not exist on the disk. In case of .net core, the paths are relative to the nuget packages
                // directory. The path to nuget directory is automatically setup for CLR to resolve.
                // Test platform tries to load every extension by assembly name. If it is not resolved, we don't
                // an error.
                if (this.pathToExtensions != null)
                {
                    extensions.AddRange(this.pathToExtensions);
                }

                extensions = extensions.Select(Path.GetFullPath).Distinct(StringComparer.OrdinalIgnoreCase).ToList();

                // Use the new paths and set the extensions discovered to false so that the next time
                // any one tries to get the additional extensions, we rediscover.
                this.pathToExtensions = extensions;

                this.TestExtensions?.InvalidateCache();

                if (EqtTrace.IsVerboseEnabled)
                {
                    var directories =
                        this.pathToExtensions.Select(e => Path.GetDirectoryName(Path.GetFullPath(e))).Distinct();

                    var directoryString = directories != null?string.Join(",", directories.ToArray()) : null;

                    EqtTrace.Verbose(
                        "TestPluginCache: Using directories for assembly resolution '{0}'.",
                        directoryString);

                    extensionString = this.pathToExtensions != null
                                          ? string.Join(",", this.pathToExtensions.ToArray())
                                          : null;

                    EqtTrace.Verbose("TestPluginCache: Updated the available extensions to '{0}'.", extensionString);
                }
            }
        }
示例#59
0
 public Task <bool> AllowIPAddresses(string ruleNamePrefix, IEnumerable <IPAddressRange> ipAddresses, IEnumerable <PortRange> allowedPorts = null, CancellationToken cancelToken = default)
 {
     lock (this)
     {
         allowRuleRanges[ruleNamePrefix] = new MemoryFirewallRuleRanges(ipAddresses.Select(i => IPAddressRange.Parse(i)).ToList(), allowedPorts?.ToList(), false);
     }
     return(Task.FromResult <bool>(true));
 }
 public static List <TSource> SafeToList <TSource>(this IEnumerable <TSource> source, List <TSource> nullResult = null)
 {
     return(source?.ToList() ?? nullResult);
 }