public static Expression CreateNewExpression(Expression currentContext, IEnumerable<DataApiNode> fieldExpressions, ISchemaProvider schemaProvider, out Type dynamicType) { var fieldExpressionsByName = fieldExpressions.ToDictionary(f => f.Name, f => f.Expression); dynamicType = LinqRuntimeTypeBuilder.GetDynamicType(fieldExpressions.ToDictionary(f => f.Name, f => f.Expression.Type)); var bindings = dynamicType.GetFields().Select(p => Expression.Bind(p, fieldExpressionsByName[p.Name])).OfType<MemberBinding>(); var newExp = Expression.New(dynamicType.GetConstructor(Type.EmptyTypes)); var mi = Expression.MemberInit(newExp, bindings); return mi; }
public EpicsOverviewViewModel(IEnumerable<JiraIssue> issues, IEnumerable<RawAgileEpic> epics, IMessenger messenger) { _issues = issues; _messenger = messenger; _epicKeyToIgnoreStatus = epics.ToDictionary(e => e.Key, e => e.Done); _epicKeyToIgnoreStatus[""] = false; _epicKeyToName = epics.ToDictionary(e => e.Key, e => e.Name); _epicKeyToName[""] = "(No epic)"; EpicsStatistics = new ObservableCollection<EpicShare>(); GenerateData(); }
public OracularConfig(IEnumerable<OracularTable> tables, IEnumerable<OracularSpec> specs) { try { this.tables = tables.ToDictionary (t => t.Table); } catch (ArgumentException ex) { throw new OracularException ("duplicate table " + ex.ParamName); } try { this.specs = specs.ToDictionary (s => s.Name); } catch (ArgumentException ex) { throw new OracularException ("duplicate spec " + ex.ParamName); } foreach (var spec in this.specs.Values) { spec.config = this; } }
private ExpansionContext(Stack<MethodBase> stack, Scope scope, NameGenerator names, IEnumerable<KeyValuePair<Sym, Expression>> env) { Stack = stack; Scope = scope; Names = names; Env = env.ToDictionary(); }
public static void ResolveDependencies(IEnumerable<ClassNode> allClasses) { var allClassesBySymbol = allClasses.ToDictionary(x => x.Symbol, x => x); foreach (var dependor in allClassesBySymbol.Values) { foreach (var dependency in dependor.SymbolDependencies) { if (allClassesBySymbol.ContainsKey(dependency)) { CreateDependency(allClassesBySymbol[dependency], dependor); } else { var matchingSymbols = allClassesBySymbol.Keys.Where(x => SymbolsMatch(x, dependency)).ToList(); if (matchingSymbols.Count == 1) { CreateDependency(allClassesBySymbol[matchingSymbols.First()], dependor); } if (matchingSymbols.Count > 1) throw new NotImplementedException(); } } } }
public CommandLineArgsHandler( IEnumerable<Action<string>> parameters, IEnumerable<KeyValuePair<string, Action<string>>> flags) { this.flags = flags.ToDictionary(x => x.Key, x => x.Value); this.parameters = parameters.ToArray(); }
/// <summary> /// Initializes a new instance of the class <see cref="CryptographyManagerImpl"/> given a collection of <see cref="IHashProvider"/> and a /// collection of <see cref="ISymmetricCryptoProvider"/>. /// </summary> /// <param name="hashProviderNames">Sequence of names of the hash providers as defined in configuration.</param> /// <param name="hashProviders">The hash providers corresponding to the names in <paramref name="hashProviderNames"/> at the same index.</param> /// <param name="cryptoProviderNames">Sequence of names of the cryptography providers as defined in configuration.</param> /// <param name="symmetricCryptoProviders">The symmetric cryptography providers corresponding to the names give in <paramref name="cryptoProviderNames"/> /// <param name="instrumentationProvider">The instrumentation provider used to report errors.</param> /// at the same index.</param> public CryptographyManagerImpl(IEnumerable<string> hashProviderNames, IEnumerable<IHashProvider> hashProviders, IEnumerable<string> cryptoProviderNames, IEnumerable<ISymmetricCryptoProvider> symmetricCryptoProviders, IDefaultCryptographyInstrumentationProvider instrumentationProvider) : this(hashProviderNames.ToDictionary(hashProviders), cryptoProviderNames.ToDictionary(symmetricCryptoProviders), instrumentationProvider) { }
internal static void EnableProvider( TraceEventSession session, Guid providerId, EventLevel level, EventKeywords matchAnyKeyword, IEnumerable<KeyValuePair<string, string>> arguments, IEnumerable<string> processNamesToFilter, bool sendManifest = true) { // Make explicit the invocation for requesting the manifest from the EventSource (Provider). var argumentsDictionary = arguments.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); if (sendManifest) { argumentsDictionary["Command"] = "SendManifest"; } var options = new TraceEventProviderOptions { Arguments = argumentsDictionary, ProcessNameFilter = processNamesToFilter.ToArray() }; session.EnableProvider(providerId, (TraceEventLevel)level, (ulong)matchAnyKeyword, options); }
public TaskList(IEnumerable<TaskTable> tasks, IEnumerable<CategoryTable> categories, int currentPosition = 0) { _tasks = tasks.ToList(); _taskDictionary = _tasks.ToDictionary(task => task.Id); _category = categories.ToDictionary(cat => cat.Id); _enumerator = new TaskEnumerator(this) { CurrentPosition = currentPosition }; }
/// <summary> /// Erzeugt eine neue Verwaltung. /// </summary> /// <param name="definition">Die Definition der Aufzeichnung.</param> /// <param name="exceptions">Alle Ausnahmen zur Aufzeichnung.</param> /// <exception cref="ArgumentNullException">Es wurde keine Aufzeichnung angegeben.</exception> public _Schedule( IScheduleDefinition definition, IEnumerable<PlanException> exceptions = null ) { // Validate if (definition == null) throw new ArgumentNullException( "plan" ); // Remember Definition = definition; // Default if (exceptions == null) exceptions = Enumerable.Empty<PlanException>(); // Validate exceptions foreach (var exception in exceptions) if (exception.ExceptionDate.TimeOfDay != TimeSpan.Zero) throw new ArgumentException( string.Format( Properties.SchedulerResources.Exception_NotAPureDate, exception.ExceptionDate ), "exceptions" ); // Cross validate foreach (var exception in exceptions.GroupBy( e => e.ExceptionDate )) if (exception.Count() > 1) throw new ArgumentException( string.Format( Properties.SchedulerResources.Exception_DuplicateDate, exception.Key ), "exceptions" ); // Order plan m_Exceptions = exceptions.ToDictionary( e => e.ExceptionDate ); }
private static void ReadExistingRatings(string filename, IEnumerable<RatedCard> ratedCards) { var ratedCardsDictionary = ratedCards.ToDictionary(x => x.Name); using (var reader = new StreamReader(filename)) { var line = reader.ReadLine(); while (line != null) { var ratingAndName = line.Split(new[] {";"}, 2, StringSplitOptions.RemoveEmptyEntries); if (ratingAndName.Length == 2) { if (ratedCardsDictionary.ContainsKey(ratingAndName[1])) { ratedCardsDictionary[ratingAndName[1]].Rating = Decimal.Parse(ratingAndName[0], CultureInfo.InvariantCulture); } } line = reader.ReadLine(); } } }
public void Init(IEnumerable<IPlayer> players) { Players = players.ToDictionary(p => p.Name, StringComparer.OrdinalIgnoreCase); States = Players.Values.ToDictionary(p => p, p => new PlayerState()); Table = new Table(); }
/// <summary> /// This is the default constructor for the Microservice Id object. /// </summary> /// <param name="name">The Microservice short name.</param> /// <param name="serviceId">The service unique GUID</param> /// <param name="description">An optional description for the Microservice.</param> /// <param name="externalServiceId">The external service id. </param> /// <param name="serviceVersionId">The service version id. If not set, this will be pulled from the calling assembly Dll settings.</param> /// <param name="serviceEngineVersionId">The engine version id. If not set, this will be pulled from the executing assembly Dll settings.</param> /// <param name="properties">Any custom additional properties.</param> public MicroserviceId(string name , string serviceId = null , string description = null , string externalServiceId = null , string serviceVersionId = null , string serviceEngineVersionId = null , IEnumerable <Tuple <string, string> > properties = null) { ServiceId = string.IsNullOrEmpty(serviceId) ? Guid.NewGuid().ToString("N").ToUpperInvariant() : serviceId; Name = string.IsNullOrEmpty(name) ? $"Service{ServiceId}" : name; if (!ValidServiceIdentifier(ServiceId)) { throw new MicroserviceIdNotValidException(nameof(ServiceId), ServiceId); } if (!ValidServiceIdentifier(Name)) { throw new MicroserviceIdNotValidException(nameof(Name), Name); } Description = description; StartTime = DateTime.UtcNow; MachineName = Environment.MachineName; ServiceVersionId = serviceVersionId ?? Assembly.GetCallingAssembly().GetName().Version.ToString(); ServiceEngineVersionId = serviceEngineVersionId ?? Assembly.GetExecutingAssembly().GetName().Version.ToString(); ExternalServiceId = externalServiceId ?? string.Format("{0}_{1}_{2:yyyyMMddHHmm}_{3}", Name, MachineName, StartTime, ServiceId); Properties = properties?.ToDictionary((i) => i.Item1, (i) => i.Item2) ?? new Dictionary <string, string>(); }
public CompilationResult32( uint textSegmentSize, uint dataSegmentSize, uint bssSegmentSize, UInt32 entryPoint, UInt32 textSegmentBase, UInt32?dataSegmentBase, byte[] textSegment, IEnumerable <KeyValuePair <string, UInt32> > textLabelsOffsets, IEnumerable <BytecodeTextSymbol32> textSymbolReferenceOffsets, ImmutableArray <byte> dataSegment, IEnumerable <KeyValuePair <string, BytecodeDataSymbol32> > dataSymbolOffsets, IEnumerable <BytecodeBssSymbol> bssSymbols, IEnumerable <CompilationError> errors) : base(textSegmentSize, dataSegmentSize, bssSegmentSize, textSegment, dataSegment, bssSymbols, errors) { this.EntryPoint = entryPoint; this.TextSegmentBase = textSegmentBase; this.DataSegmentBase = dataSegmentBase; this.TextLabelsOffsets = textLabelsOffsets?.ToDictionary(k => k.Key, v => v.Value); this.TextSymbolReferenceOffsets = textSymbolReferenceOffsets.ToImmutableList(); this.DataSymbolOffsets = dataSymbolOffsets?.ToDictionary(k => k.Key, v => v.Value); }
/// <summary> /// Gets the <see cref="Type" /> matching the provided members. /// </summary> /// <param name="sourceType">The <see cref="Type" /> to generate the runtime type from.</param> /// <param name="properties">The <see cref="MemberInfo" /> to use to generate properties.</param> /// <returns>A <see cref="Type" /> mathing the provided properties.</returns> public Type Get(Type sourceType, IEnumerable<MemberInfo> properties) { properties = properties.ToArray(); if (!properties.Any()) { throw new ArgumentOutOfRangeException("properties", "properties must have at least 1 property definition"); } var dictionary = properties.ToDictionary(f => _nameResolver.ResolveName(f), memberInfo => memberInfo); var className = GetTypeKey(sourceType, dictionary); return BuiltTypes.GetOrAdd( className, s => { var typeBuilder = ModuleBuilder.DefineType( className, TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.Serializable); Contract.Assume(typeBuilder != null); SetAttributes(typeBuilder, sourceType); foreach (var field in dictionary) { CreateProperty(typeBuilder, field); } return typeBuilder.CreateType(); }); }
public Dictionary <string, string> FetchExifFrom(string path, IEnumerable <string> tagsToKeep = null, bool keepKeysWithEmptyValues = true) { var res = new Dictionary <string, string>(); if (!File.Exists(path)) { return(res); } var tagsTable = tagsToKeep?.ToDictionary(x => x, x => 1); bool filter = tagsTable != null && tagsTable.Count > 0; var cmdRes = this.SendCommand(path); if (!cmdRes) { return(res); } foreach (string s in cmdRes.Result.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)) { string[] kv = s.Split('\t'); Debug.Assert(kv.Length == 2, $"Can not parse line :'{s}'"); if (kv.Length != 2 || (!keepKeysWithEmptyValues && string.IsNullOrEmpty(kv[1]))) { continue; } if (filter && !tagsTable.ContainsKey(kv[0])) { continue; } res[kv[0]] = kv[1]; } return(res); }
public SyndicationService(string title, IEnumerable<IResourceCollection> collections) { Title = title; this.collections = collections.ToDictionary( x => x.Info.Title.Text, StringComparer.OrdinalIgnoreCase); }
public MappedConstructor MapToConstructor(IEnumerable<Column> columns) { var error = new ErrorBuilder(); var columnsByName = columns.ToDictionary(x => x.Name.ToUpper()); foreach (TypeConstructor ctor in _constructors) { var selectedColumns = new List<Column>(); foreach (var attribute in ctor.Attributes) { var key = attribute.Name.ToUpper(); if (!columnsByName.ContainsKey(key)) { error.UnmappedAttribute(attribute); } else { selectedColumns.Add(columnsByName[key]); } } if (!error.HasErrors) { return new MappedConstructor(ctor, selectedColumns); } } throw error.Create(); }
private BoardState(IPathsValidator <TEntity> pathsValidator, IEnumerable <LocatedItem <TEntity> > clonedItems) { _items = clonedItems?.ToDictionary(k => k.Location, k => k) ?? new Dictionary <BoardLocation, LocatedItem <TEntity> >(); _pathsValidator = pathsValidator; }
public CacheableKeyCreator(IEnumerable <ICacheableKeyFragmentFactory> keyFragmentFactories, IContentCacheKeyCreator contentCacheKeyCreator) { var factories = keyFragmentFactories?.ToDictionary(x => x.SupportedVaryBy, StringComparer.OrdinalIgnoreCase) ?? throw new ArgumentNullException(nameof(keyFragmentFactories)); _keyFragmentFactories = new ReadOnlyDictionary <string, ICacheableKeyFragmentFactory>(factories); ContentCacheKeyCreator = contentCacheKeyCreator; }
public void Create(string userId, IEnumerable <CartItemSummaryServiceModel> items) { if (String.IsNullOrEmpty(userId) || items.Count() == 0) { return; // Exception ? } var keyValuePairs = items? .ToDictionary(i => i.Id, i => i.Quantity); var orderItems = this.db .Shoes .Where(s => keyValuePairs.ContainsKey(s.Id)) .Select(s => new OrderItem { ShoeId = s.Id, ShoePrice = s.Price, Quantity = keyValuePairs[s.Id] }) .ToList(); var order = new Order { UserId = userId, Items = orderItems }; this.db .Orders .Add(order); this.db .SaveChanges(); }
internal EntityType(string schema, string name, IEnumerable<EntityField> fields) { _schema = schema; _name = name; _tableName = String.Format("{0}_{1}", _schema, _name); _fields = fields.ToDictionary(val => val.Name); }
public ServerConfig(IEnumerable<Tuple<WikiConfig, IPageCache>> config) { configMap = new ConcurrentDictionary<string, Tuple<WikiConfig, MasterRepository, IPageCache>>( config.ToDictionary( c => CreateSafeName(c.Item1.SiteName), c => new Tuple<WikiConfig, MasterRepository, IPageCache>(c.Item1, new MasterRepository(c.Item1.Convertor.FileExtension), c.Item2))); }
public AuditEvent(string messageType, object messageBody, IEnumerable<KeyValuePair<string, object>> properties, DateTimeOffset timestamp) { MessageBody = messageBody; Properties = properties.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); Timestamp = timestamp; MessageType = messageType; }
/// <summary> /// Creates a new instance of the <see cref="ModelRepository"/> type. /// </summary> /// <param name="modelFactories"> /// A collection that contains all registered <see cref="IModelFactory"/> implementations. /// </param> /// <param name="modelReader"> /// A <see cref="IModelReader"/> implementation for loading persisted <see cref="IModel"/>s from disk. /// </param> public ModelRepository( IEnumerable <IModelFactory> modelFactories, IModelReader modelReader) { ModelFactories = modelFactories?.ToDictionary(f => f.Id) ?? new Dictionary <Guid, IModelFactory>(); ModelReader = modelReader; }
public StepDirectory(string path, ScriptEngine pythonEngine) { _path = path; _pythonEngine = pythonEngine; _logger = LogManager.GetLogger("steps"); var stepTypes = this.GetType().Assembly.GetTypes() .Where(t => !t.IsAbstract) .Where(t => t.IsSubclassOf(typeof (Step))) .Select(t => new { Type = t, Extensions = t.GetCustomAttributes(typeof (HandlesAttribute), true) .Cast<HandlesAttribute>() .SelectMany(h => h.Extensions) }); _extensions = stepTypes.SelectMany(t => t.Extensions); _typesByExtension = _extensions.ToDictionary(ext => ext.ToLowerInvariant(), ext => stepTypes.Single(s => s.Extensions.Contains(ext)).Type); LoadStepsAndMetadata(); InitializeFileWatcher(); }
public XmlTestResultParser(IEnumerable<TestCase> testCasesRun, string xmlResultFile, TestEnvironment testEnvironment, string baseDir) { _testEnvironment = testEnvironment; _baseDir = baseDir; _xmlResultFile = xmlResultFile; _testCasesMap = testCasesRun.ToDictionary(tc => tc.FullyQualifiedName, tc => tc); }
/// <inheritdoc/> public IPropertyBag CreateModified( IPropertyBag input, IEnumerable <KeyValuePair <string, object> >?propertiesToSetOrAdd, IEnumerable <string>?propertiesToRemove) { IReadOnlyDictionary <string, object> existingProperties = input.AsDictionary(); Dictionary <string, object> newProperties = propertiesToSetOrAdd?.ToDictionary(kv => kv.Key, kv => kv.Value) ?? new Dictionary <string, object>(); HashSet <string>?remove = propertiesToRemove == null ? null : new HashSet <string>(propertiesToRemove); foreach (KeyValuePair <string, object> existingKv in existingProperties) { string key = existingKv.Key; bool newPropertyWithThisNameExists = newProperties.ContainsKey(key); bool existingPropertyIsToBeRemoved = remove?.Contains(key) == true; if (newPropertyWithThisNameExists && existingPropertyIsToBeRemoved) { throw new ArgumentException($"Property {key} appears in both {nameof(propertiesToSetOrAdd)} and {nameof(propertiesToRemove)}"); } if (!newPropertyWithThisNameExists && !existingPropertyIsToBeRemoved) { newProperties.Add(key, existingKv.Value); } } return(new JsonNetPropertyBag(newProperties, this.serializerSettings)); }
public Dictionary<Webpage, List<MobileFriendlyNavigationChildNode>> GetNodes(IEnumerable<Webpage> parents) { Webpage webpageAlias = null; MobileFriendlyNavigationChildNode nodeAlias = null; var countSubNodes = QueryOver.Of<Webpage>() .Where(x => x.Parent.Id == webpageAlias.Id && x.RevealInNavigation && x.PublishOn != null) .ToRowCountQuery(); var parentIds = parents.Select(webpage => webpage.Id).ToList(); var nodes = _session.QueryOver(() => webpageAlias) .Where(node => node.RevealInNavigation && node.Published) .Where(node => node.Parent.Id.IsIn(parentIds)) .OrderBy(x => x.DisplayOrder).Asc .SelectList(x => x.Select(y => y.Id).WithAlias(() => nodeAlias.Id) .Select(y => y.Parent.Id).WithAlias(() => nodeAlias.ParentId) .Select(y => y.Name).WithAlias(() => nodeAlias.Name) .Select(y => y.UrlSegment).WithAlias(() => nodeAlias.UrlSegment) .Select(y => y.PublishOn).WithAlias(() => nodeAlias.PublishOn) .Select(y => y.DocumentType).WithAlias(() => nodeAlias.DocumentType) .Select(y => y.DisplayOrder).WithAlias(() => nodeAlias.DisplayOrder) .SelectSubQuery(countSubNodes).WithAlias(() => nodeAlias.ChildCount)) .TransformUsing(Transformers.AliasToBean<MobileFriendlyNavigationChildNode>()) .List<MobileFriendlyNavigationChildNode>().ToList() .GroupBy(node => node.ParentId) .ToDictionary(grouping => grouping.Key, g => g.ToList()); return parents.ToDictionary(webpage => webpage, webpage => nodes.ContainsKey(webpage.Id) ? nodes[webpage.Id] : new List<MobileFriendlyNavigationChildNode>()); }
public IEnumerable<Language> GetDowloadedSubtitleLanguages(string filePath, IEnumerable<Language> languages) { var filesToCheck = languages.ToDictionary( language => language, language => CreateSubtitleFileName(filePath, $".{language.TwoLetterIsoName}.srt")); return filesToCheck.Where(item => _fileSystem.File.Exists(item.Value)).Select(item => item.Key); }
public void AddSerializers(IEnumerable<Type> list) { var dictionary = list.ToDictionary(type => type.BaseType.GenericTypeArguments[0], type => (ISerializer)Activator.CreateInstance(type)); foreach (var serializer in dictionary) serializers.Add(serializer.Key, serializer.Value); }
public static string Generate <T>(T value, IEnumerable <ICustomConverter> customConverters = null) { var converters = customConverters?.ToDictionary(x => x.Type) ?? new Dictionary <Type, ICustomConverter>(); if (!converters.ContainsKey(typeof(string))) { converters.Add(typeof(string), new StringConverter()); } if (!converters.ContainsKey(typeof(Guid))) { converters.Add(typeof(Guid), new GuidConverter()); } if (!converters.ContainsKey(typeof(char))) { converters.Add(typeof(char), new CharConverter()); } if (!converters.ContainsKey(typeof(DateTime))) { converters.Add(typeof(DateTime), new DateTimeConverter()); } if (!converters.ContainsKey(typeof(bool))) { converters.Add(typeof(bool), new BoolConverter()); } if (!converters.ContainsKey(typeof(bool?))) { converters.Add(typeof(bool?), new NullableBoolConverter()); } return(Generate(value, converters, new Dictionary <Type, Type>())); }
private string PrepareInsertCommand(string sql, IDbCommand command, IEnumerable<Column> columns) { var parameterFactory = _adapter.ProviderHelper.GetCustomProvider<IDbParameterFactory>(_schemaProvider) ?? new GenericDbParameterFactory(command); var columnLookup = columns.ToDictionary(c => c.QuotedName, c => c); if (columnLookup.Count == 0) return PrepareCommand(sql, command); int openParenIndex = sql.IndexOf('('); int closeParenLength = sql.IndexOf(')') - openParenIndex; var columnNameList = sql.Substring(openParenIndex, closeParenLength).Trim('(', ')').Split(','); int index = 0; var sqlBuilder = new StringBuilder(); foreach (var c in sql) { if (c == '?') { var column = columnLookup[columnNameList[index]]; var parameter = parameterFactory.CreateParameter(_schemaProvider.NameParameter("p" + index), column); command.Parameters.Add(parameter); sqlBuilder.Append(parameter.ParameterName); index++; } else { sqlBuilder.Append(c); } } return sqlBuilder.ToString(); }
public void WaitForDeploymentsToFinish(IEnumerable<string> linksToDeploymentTasks, TimeSpan timeout, TimeSpan deploymentStatusCheckSleepCycle) { IDictionary<string, Task> tasks; var stopwatch = Stopwatch.StartNew(); do { tasks = linksToDeploymentTasks.ToDictionary(link => link, link => session.Get<Task>(link)); var allTasksFinished = tasks.Values.All(task => task.IsFinished); if (allTasksFinished) break; EnsureDeploymentIsNotTakingLongerThanExpected(stopwatch.Elapsed, timeout); log.Debug(String.Format("Deployment not yet finished. It's taken {0} so far.", stopwatch.Elapsed)); Thread.Sleep(deploymentStatusCheckSleepCycle); } while (true); var failedTasks = tasks.Values.Where(task => !task.FinishedSuccessfully); if (failedTasks.Any()) { var message = "{0} of the deployment tasks has failed. Please check Octopus web site for more details. Failed tasks: {1}"; var taskIds = failedTasks.Aggregate("", (accumulator, task) => accumulator + task.Id + ", "); throw new CommandException(String.Format(message, failedTasks.Count(), taskIds)); } log.Debug("Deployment has finished succeessfully"); }
public static void RedirectFromLogin(string login, IEnumerable<RestResponseCookie> cookies) { if (cookies == null) throw new ArgumentNullException("cookies"); cookies = cookies.ToArray(); var data = JsonConvert.SerializeObject(cookies.ToDictionary(c => c.Name, c => c.Value)); var cookie = FormsAuthentication.GetAuthCookie(login, false); var sourceTicket = FormsAuthentication.Decrypt(cookie.Value); if (sourceTicket == null) throw new ApplicationException("Unable to decrypt authentication"); var expiration = cookies.Select(c => c.Expires) .Where(exp => exp > DateTime.Today.AddYears(-1) && exp < DateTime.Today.AddYears(1)) .Concat(new[] {sourceTicket.Expiration}) .Min(); var ticket = new FormsAuthenticationTicket( sourceTicket.Version, sourceTicket.Name, sourceTicket.IssueDate, expiration, false, data); cookie.Value = FormsAuthentication.Encrypt(ticket); Response.SetCookie(cookie); var redirectUrl = FormsAuthentication.GetRedirectUrl(login, sourceTicket.IsPersistent); Response.Redirect(redirectUrl); }
/// <summary> /// Executes synchronous orders to bring the account within margin requirements. /// </summary> /// <param name="generatedMarginCallOrders">These are the margin call orders that were generated /// by individual security margin models.</param> /// <returns>The list of orders that were actually executed</returns> public virtual List<Order> ExecuteMarginCall(IEnumerable<Order> generatedMarginCallOrders) { // if our margin used is back under the portfolio value then we can stop liquidating if (Portfolio.MarginRemaining >= 0) { return new List<Order>(); } // order by losers first var executedOrders = new List<Order>(); var ordersWithSecurities = generatedMarginCallOrders.ToDictionary(x => x, x => Portfolio[x.Symbol]); var orderedByLosers = ordersWithSecurities.OrderBy(x => x.Value.UnrealizedProfit).Select(x => x.Key); foreach (var order in orderedByLosers) { Portfolio.Transactions.AddOrder(order); Portfolio.Transactions.WaitForOrder(order.Id); executedOrders.Add(order); // if our margin used is back under the portfolio value then we can stop liquidating if (Portfolio.MarginRemaining >= 0) { break; } } return executedOrders; }
internal AudioScan(DirectoryInfo directory, SearchOption searchoption, bool parseAdd, bool parseUpdate, bool removeDeadFiles, string[] extensions, IEnumerable<RawTrack> existingFiles, IEnumerable<string> ignoredFiles, ScanFileEventHandler parsed, ScanCompletedEventHandler done) { var thread = new Thread(Run); _directory = directory; _searchoption = searchoption; _parseAdd = parseAdd; _parseUpdate = parseUpdate; _removeDeadFiles = removeDeadFiles; _parser = new MediaParser(); _extensions = extensions; _existingFiles = existingFiles.ToDictionary(rt => rt.File); _ignoredFiles = (from s in ignoredFiles select new FileInfo(s)).ToArray(); Parsed = parsed; Done = done; _state = ScannerState.NotRunning; _added = _updated = _skipped = _error = _removed = _total = 0; thread.Start(); }
public void Add(string typeName, string assemblyName, IEnumerable <KeyValuePair <string, object> > properties) { Assembly assembly = null; try { var assemblyRef = new AssemblyName(assemblyName); assembly = Assembly.Load(assemblyRef); } catch (Exception exc) { throw new TypeLoadException($"Cannot load TelemetryConsumer class {typeName} from assembly {assembly?.FullName ?? assemblyName} - Error={exc}"); } var pluginType = assembly.GetType(typeName); if (pluginType == null) { throw new TypeLoadException($"Cannot locate plugin class {typeName} in assembly {assembly.FullName}"); } if (!typeof(ITelemetryConsumer).IsAssignableFrom(pluginType)) { throw new InvalidOperationException($"Telemetry consumer class {typeName} must implement one of {nameof(ITelemetryConsumer)} based interfaces"); } var extendedProperties = properties?.ToDictionary(x => x.Key, x => x.Value); Consumers.Add(new ConsumerConfiguration { ConsumerType = pluginType, Properties = extendedProperties }); }
public static IEnumerable<FrameworkName> SelectFrameworks(Runtime.Project project, IEnumerable<string> userSelection, FrameworkName fallbackFramework, out string errorMessage) { var specifiedFrameworks = userSelection.ToDictionary(f => f, FrameworkNameHelper.ParseFrameworkName); var projectFrameworks = new HashSet<FrameworkName>( project.GetTargetFrameworks() .Select(c => c.FrameworkName)); IEnumerable<FrameworkName> frameworks = null; if (projectFrameworks.Count > 0) { // Specified target frameworks have to be a subset of the project frameworks if (!ValidateFrameworks(projectFrameworks, specifiedFrameworks, out errorMessage)) { return null; } frameworks = specifiedFrameworks.Count > 0 ? specifiedFrameworks.Values : (IEnumerable<FrameworkName>)projectFrameworks; } else { frameworks = new[] { fallbackFramework }; } errorMessage = string.Empty; return frameworks; }
public TestNuCacheContentService( IEnumerable <ContentNodeKit> contentKits, IEnumerable <ContentNodeKit> mediaKits = null) { ContentKits = contentKits?.ToDictionary(x => x.Node.Id, x => x) ?? new Dictionary <int, ContentNodeKit>(); MediaKits = mediaKits?.ToDictionary(x => x.Node.Id, x => x) ?? new Dictionary <int, ContentNodeKit>(); }
/* *Build a tree from given inputs and return the root node. */ public TreeNode BuildTree(IEnumerable<Input> inputs, TreeNode parentNode = null) { TreeNode rootNode = null; var inputDictionary = inputs.ToDictionary( // Building a dictionary to store each input and its corresponding node. This way we can create a Node and add it as a child of the given parent node. input => input.Id, input => new { Input = input, newNode = new TreeNode(input.Id) }); foreach (var value in inputDictionary.Values) // Iterating through the nodes so that we can add proper children for parents. { var input = value.Input; if (input.ParentId != null) //If the ParentId is null, add it as root. If not, add it as a child. { inputDictionary[(int)input.ParentId].newNode.AddChild(value.newNode); //Get the parentID for the input. Then get the node for the parentID and the add the child node to that parentNode. } else { rootNode = value.newNode; //If it does not have parent, its a root node. } } return rootNode; //throw new NotImplementedException(); }
public XmlElementNodeSerializer(IEnumerable <Element> underlyingElementsForRead) { // VixenSystem.Elements has not yet been populated because the file is in the // middle of being read/written. This serializer has a dependency on the // newly read element collection. //_underlyingElements = underlyingElementsForRead; _underlyingElementMap = underlyingElementsForRead?.ToDictionary(x => x.Id); }
protected OperationInternalBase(ClientDiagnostics clientDiagnostics, string operationTypeName, IEnumerable <KeyValuePair <string, string> >?scopeAttributes = null, DelayStrategy?fallbackStrategy = null) { _diagnostics = clientDiagnostics; _updateStatusScopeName = $"{operationTypeName}.UpdateStatus"; _scopeAttributes = scopeAttributes?.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); _fallbackStrategy = fallbackStrategy; _responseLock = new AsyncLockWithValue <Response>(); }
protected OperationInternalBase(ClientDiagnostics clientDiagnostics, Response rawResponse, string operationTypeName, IEnumerable <KeyValuePair <string, string> >?scopeAttributes = null) { _diagnostics = clientDiagnostics; _updateStatusScopeName = $"{operationTypeName}.UpdateStatus"; _scopeAttributes = scopeAttributes?.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); RawResponse = rawResponse; DefaultPollingInterval = TimeSpan.FromSeconds(1); }
public Core(LoginIqOptionDTO mainAccount, IEnumerable <LoginIqOptionDTO> followersAccount = null) { _trader = new IqOptionClient(mainAccount.Email, mainAccount.Password); _trader.OnBuy += FollowerBuyAsync; Followers = followersAccount ?.ToDictionary(x => x.Email, x => new IqOptionClient(x.Email, x.Password)); }
/// <inheritdoc/> public virtual Task SendMessageToQueueAsync(string deadLetterQueueUrl, string message, IEnumerable <KeyValuePair <string, string> > messageAttributes) => SqsClient.SendMessageAsync(new SendMessageRequest { QueueUrl = deadLetterQueueUrl, MessageBody = message, MessageAttributes = messageAttributes?.ToDictionary(kv => kv.Key, kv => new MessageAttributeValue { StringValue = kv.Value }) ?? new Dictionary <string, MessageAttributeValue>() });
public DirectoryStructure(PathSet pathSet, IEnumerable <FileStructure> files, IEnumerable <DirectoryStructure> directories, PropertiesSet properties) { this.Name = pathSet.Name; this.FullPath = pathSet.FullPath; this.RelativePath = pathSet.RelativePath; this.Files = files?.ToDictionary(o => o.Name); this.Directories = directories?.ToDictionary(o => o.Name); this.Properties = properties; }
/// <summary> /// Send a message to the specified SQS queue. The Lambda function requires <c>sqs:SendMessage</c> permission /// on the specified SQS queue. /// </summary> /// <param name="deadLetterQueueUrl">The SQS queue URL.</param> /// <param name="message">The message to send.</param> /// <param name="messageAttributes">Optional attributes for the message.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>The task object representing the asynchronous operation.</returns> public virtual Task SendMessageToQueueAsync(string deadLetterQueueUrl, string message, IEnumerable <KeyValuePair <string, string> >?messageAttributes, CancellationToken cancellationToken) => SqsClient.SendMessageAsync(new SendMessageRequest { QueueUrl = deadLetterQueueUrl, MessageBody = message, MessageAttributes = messageAttributes?.ToDictionary(kv => kv.Key, kv => new MessageAttributeValue { DataType = "String", StringValue = kv.Value }) ?? new Dictionary <string, MessageAttributeValue>() }, cancellationToken);
public PipelineBuilder Effect( Func <IGraphicsEffectSource, Task <IGraphicsEffectSource> > factory, IEnumerable <string> animations = null, IEnumerable <BrushProvider> initializers = null) { async ValueTask <IGraphicsEffectSource> Factory() => await factory(await this.sourceProducer()); return(new PipelineBuilder(this, Factory, animations?.ToArray(), initializers?.ToDictionary(item => item.Name, item => item.Initializer))); }
public OverridePropertyManager(IEnumerable <DavProperty <TEntry> > properties, IPropertyManager basePropertyManager, Func <TEntry, IStoreItem> converter = null) { // Convert the properties to a dictionary for fast retrieval _properties = properties?.ToDictionary(p => p.Name) ?? throw new ArgumentNullException(nameof(properties)); _basePropertyManager = basePropertyManager ?? throw new ArgumentNullException(nameof(basePropertyManager)); _converter = converter ?? (si => si); // Create the property information immediately Properties = GetPropertyInfo(); }
public static void GenerateCSharpFile(string outputPath, IEnumerable <FunctionDoc> functionDocs) { _functionDocs = functionDocs?.ToDictionary(functionDoc => functionDoc.Function, funcDoc => funcDoc); var apiMetadata = GetAPIMetadata(); var csharpClass = GenerateCSharpClass(apiMetadata); File.WriteAllText(outputPath, csharpClass); }
/// <inheritdoc /> public async Task UpdateAsync(ImmutableArray <Position> positions, ImmutableArray <Order> orders, ImmutableArray <MarginTradingAccount> accounts, IEnumerable <BestPriceContract> fxRates, IEnumerable <BestPriceContract> cfdQuotes) { if (!_tradingDay.HasValue) { throw new InvalidOperationException("Unable to update snapshot: the draft snapshot provider has not been initialized yet"); } if (positions == null || !positions.Any()) { throw new ArgumentNullException(nameof(positions), @"Unable to update snapshot: positions list is empty"); } if (orders == null || !orders.Any()) { throw new ArgumentNullException(nameof(orders), @"Unable to update snapshot: orders list is empty"); } if (accounts == null || !accounts.Any()) { throw new ArgumentNullException(nameof(accounts), @"Unable to update snapshot: accounts list is empty"); } await EnsureSnapshotLoadedOrThrowAsync(); var fxPrices = fxRates?.ToDictionary(r => r.Id, r => r); var tradingPrices = cfdQuotes?.ToDictionary(q => q.Id, q => q); _snapshot = new TradingEngineSnapshot(_snapshot.TradingDay, _snapshot.CorrelationId, _snapshot.Timestamp, orders.ToJson(), positions.ToJson(), accounts.ToJson(), _snapshot .GetBestFxPrices() .Merge(fxPrices) .ToJson(), _snapshot .GetBestTradingPrices() .Merge(tradingPrices) .ToJson(), _snapshot.Status); // to force keeper deserialize updated values from json next time data is accessed _positions = null; _orders = null; _accounts = null; _fxPrices = null; _cfdQuotes = null; }
public DiscLibrary(IEnumerable <FolderModel> folders, IEnumerable <DiscModel> discs, IEnumerable <SongModel> songs, IEnumerable <ArtistModel> artists, IEnumerable <GenreModel> genres, IEnumerable <AdviseGroupModel> adviseGroups, IEnumerable <AdviseSetModel> adviseSets) { this.folders = folders?.ToDictionary(x => x.Id, x => x) ?? throw new ArgumentNullException(nameof(folders)); this.discs = discs?.ToDictionary(x => x.Id, x => x) ?? throw new ArgumentNullException(nameof(discs)); this.songs = songs?.ToDictionary(x => x.Id, x => x) ?? throw new ArgumentNullException(nameof(songs)); this.artists = artists?.ToDictionary(x => x.Id, x => x) ?? throw new ArgumentNullException(nameof(artists)); this.genres = genres?.ToDictionary(x => x.Id, x => x) ?? throw new ArgumentNullException(nameof(genres)); this.adviseGroups = adviseGroups?.ToDictionary(x => x.Id, x => x) ?? throw new ArgumentNullException(nameof(adviseGroups)); this.adviseSets = adviseSets?.ToDictionary(x => x.Id, x => x) ?? throw new ArgumentNullException(nameof(adviseSets)); }
/// <summary> /// Initializes a new instance of the <see cref="OperationInternal{T}"/> class. /// </summary> /// <param name="clientDiagnostics">Used for diagnostic scope and exception creation. This is expected to be the instance created during the construction of your main client.</param> /// <param name="operation">The long-running operation making use of this class. Passing "<c>this</c>" is expected.</param> /// <param name="rawResponse"> /// The initial value of <see cref="RawResponse"/>. Usually, long-running operation objects can be instantiated in two ways: /// <list type="bullet"> /// <item> /// When calling a client's "<c>Start<OperationName></c>" method, a service call is made to start the operation, and an <see cref="Operation{T}"/> instance is returned. /// In this case, the response received from this service call can be passed here. /// </item> /// <item> /// When a user instantiates an <see cref="Operation{T}"/> directly using a public constructor, there's no previous service call. In this case, passing <c>null</c> is expected. /// </item> /// </list> /// </param> /// <param name="operationTypeName"> /// The type name of the long-running operation making use of this class. Used when creating diagnostic scopes. If left <c>null</c>, the type name will be inferred based on the /// parameter <paramref name="operation"/>. /// </param> /// <param name="scopeAttributes">The attributes to use during diagnostic scope creation.</param> public OperationInternal(ClientDiagnostics clientDiagnostics, IOperation <T> operation, Response rawResponse, string operationTypeName = null, IEnumerable <KeyValuePair <string, string> > scopeAttributes = null) { operationTypeName ??= operation.GetType().Name; _operation = operation; _diagnostics = clientDiagnostics; _updateStatusScopeName = $"{operationTypeName}.UpdateStatus"; _scopeAttributes = scopeAttributes?.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); RawResponse = rawResponse; DefaultPollingInterval = TimeSpan.FromSeconds(1); }
public CompositeSearchProvider(IEnumerable <ISongSearchProvider> providers) { if (providers == null) { throw new ArgumentNullException(nameof(providers)); } this.Providers = providers ?.ToDictionary(x => x.Id, x => x) ?? throw new ArgumentNullException(nameof(providers)); }
/// <summary> /// Create router /// </summary> /// <param name="logger"></param> /// <param name="invokers"></param> public MethodRouter(ILogger logger, IEnumerable <IMethodInvoker> invokers = null) { _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _calltable = invokers?.ToDictionary(i => i.MethodName, i => i) ?? new Dictionary <string, IMethodInvoker>(); // Create chunk server var server = new ChunkMethodServer(this, logger); _calltable.Add(MethodNames.Call, new ChunkMethodServerInvoker(server));; }
public Field(string name, IArrowType dataType, bool nullable, IEnumerable <KeyValuePair <string, string> > metadata = default) { if (string.IsNullOrWhiteSpace(name)) { throw new ArgumentNullException(nameof(name)); } Name = name; DataType = dataType ?? NullType.Default; IsNullable = nullable; Metadata = metadata?.ToDictionary(kv => kv.Key, kv => kv.Value); }
/// <summary> /// Initializes a new instance of the <see cref="GeneratorBaseClass{TMappedClass}"/> class. /// </summary> /// <param name="mappingInformation">The mapping information.</param> /// <param name="queryGenerators">The query generators.</param> /// <exception cref="ArgumentNullException"> /// linqQueryGenerator or mappingInformation or queryGenerators /// </exception> /// <exception cref="ArgumentException">Mapping not found for type: AssociatedType</exception> protected GeneratorBaseClass(IMappingSource mappingInformation, IEnumerable <IQueryGenerator <TMappedClass> > queryGenerators) { MappingInformation = mappingInformation ?? throw new ArgumentNullException(nameof(mappingInformation)); if (!MappingInformation.GetChildMappings(AssociatedType).Any()) { throw new ArgumentException("Mapping not found for type: " + AssociatedType); } QueryGenerators = queryGenerators?.ToDictionary(x => x.QueryType) ?? throw new ArgumentNullException(nameof(queryGenerators)); LinqQueryGenerator = (ILinqQueryGenerator <TMappedClass>)queryGenerators.FirstOrDefault(x => x.QueryType == QueryType.LinqQuery); DataQueryGenerator = (IDataQueryGenerator <TMappedClass>)queryGenerators.FirstOrDefault(x => x.QueryType == QueryType.LoadData); }
public static Task <HttpResponseMessage> GetAsync(this HttpClient client, Uri requestUri, HttpCompletionOption completionOption = HttpCompletionOption.ResponseContentRead, IEnumerable <KeyValuePair <string, IEnumerable <string> > > additionalHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { IDictionary <string, string[]> headers = additionalHeaders?.ToDictionary(x => x.Key, x => x.Value.ToArray()); if (headers?.Count > 0) { HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUri); MergeHeaders(request, headers); return(client.SendAsync(request, completionOption, cancellationToken)); } return(client.GetAsync(requestUri, completionOption, cancellationToken)); }
/// <summary> /// Creates an instance of <see cref="DefaultClusterConfig"/> /// </summary> /// <param name="hostname">The hostname</param> /// <param name="port">The port number</param> /// <param name="minNodes">Minimum nodes required in the cluster</param> /// <param name="seedNodes">Full URIs of seed nodes</param> /// <param name="roles">Roles and the minimum number of those roles required in the cluster</param> /// <returns></returns> public DefaultClusterConfig( string hostname, int port, int minNodes = 1, IEnumerable <string> seedNodes = null, IEnumerable <KeyValuePair <string, int> > roles = null, bool enablePubSub = true ) : this(hostname, port) { MinNodeNumberForUp = minNodes; SeedNodePaths = seedNodes?.ToArray() ?? new string[] { }; Roles = roles?.ToDictionary(x => x.Key, x => x.Value) ?? new Dictionary <string, int>(); WithPubSub = enablePubSub; }