private static TraceLevel GetTraceLevel(IDictionary<string, string> attributes) { string type; attributes.TryGetValue("type", out type); if (type == "error") { return TraceLevel.Error; } string value; if (attributes.TryGetValue("traceLevel", out value)) { var traceLevel = Int32.Parse(value); if (traceLevel <= (int)TraceLevel.Error) { return TraceLevel.Error; } else if (traceLevel <= (int)TraceLevel.Info) { return TraceLevel.Info; } } return TraceLevel.Verbose; }
public static IGraph ReplaceResourceUris(IGraph original, IDictionary<string, Uri> replacements) { IGraph modified = new Graph(); foreach (Triple triple in original.Triples) { Uri subjectUri; if (!replacements.TryGetValue(triple.Subject.ToString(), out subjectUri)) { subjectUri = ((IUriNode)triple.Subject).Uri; } INode subjectNode = modified.CreateUriNode(subjectUri); INode predicateNode = triple.Predicate.CopyNode(modified); INode objectNode; if (triple.Object is IUriNode) { Uri objectUri; if (!replacements.TryGetValue(triple.Object.ToString(), out objectUri)) { objectUri = ((IUriNode)triple.Object).Uri; } objectNode = modified.CreateUriNode(objectUri); } else { objectNode = triple.Object.CopyNode(modified); } modified.Assert(subjectNode, predicateNode, objectNode); } return modified; }
private void RegisterKeyboards(IDictionary<string, uint> keyboards) { if (keyboards.Count <= 0) return; var configRegistry = XklConfigRegistry.Create(XklEngine); var layouts = configRegistry.Layouts; Dictionary<string, XkbKeyboardDescription> curKeyboards = KeyboardController.Instance.Keyboards.OfType<XkbKeyboardDescription>().ToDictionary(kd => kd.Id); foreach (var kvp in layouts) { foreach (var layout in kvp.Value) { uint index; // Custom keyboards may omit defining a country code. Try to survive such cases. string codeToMatch; if (layout.CountryCode == null) codeToMatch = layout.LanguageCode.ToLowerInvariant(); else codeToMatch = layout.CountryCode.ToLowerInvariant(); if ((keyboards.TryGetValue(layout.LayoutId, out index) && (layout.LayoutId == codeToMatch)) || keyboards.TryGetValue(string.Format("{0}+{1}", codeToMatch, layout.LayoutId), out index)) { AddKeyboardForLayout(curKeyboards, layout, index, SwitchingAdaptor); } } } foreach (XkbKeyboardDescription existingKeyboard in curKeyboards.Values) existingKeyboard.SetIsAvailable(false); }
private void AddFeatures(Node parent, IEnumerable<IFsFeatDefn> features, IDictionary<IFsFeatDefn, object> values) { foreach (IFsFeatDefn feature in features) { var complexFeat = feature as IFsComplexFeature; if (complexFeat != null) { var node = new ComplexFeatureNode(complexFeat) {Image = m_complexImage}; object value; if (values == null || !values.TryGetValue(complexFeat, out value)) value = null; AddFeatures(node, complexFeat.TypeRA.FeaturesRS, (IDictionary<IFsFeatDefn, object>) value); parent.Nodes.Add(node); } else { var closedFeat = feature as IFsClosedFeature; if (closedFeat != null) { var node = new ClosedFeatureNode(closedFeat) {Image = m_closedImage}; object value; if (values != null && values.TryGetValue(closedFeat, out value)) { var closedVal = (ClosedFeatureValue) value; node.IsChecked = closedVal.Negate; node.Value = new SymbolicValue(closedVal.Symbol); } parent.Nodes.Add(node); } } } }
/// <inheritdoc/> public IConnectionProvider CreateProvider( IDictionary<string, string> options) { string connection_string; if (options.TryGetValue(kConnectionStringOption, out connection_string)) { return new SqlConnectionProvider(connection_string); } SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(); builder.DataSource = GetOption(kServerOption, options); // We try to get the user name information using the "login" key for // backward compatibility. string user_id; if (!options.TryGetValue(kLoginOption, out user_id)) { user_id = GetOption(kUserNameOption, options); } builder.UserID = user_id; builder.Password = GetOption(kPasswordOption, options); string catalog; if (options.TryGetValue(kInitialCatalogOption, out catalog)) { builder.InitialCatalog = catalog; } return new SqlConnectionProvider(builder.ConnectionString); }
private void RegisterKeyboards(IDictionary<string, uint> keyboards) { if (keyboards.Count <= 0) return; var configRegistry = XklConfigRegistry.Create(_engine); var layouts = configRegistry.Layouts; foreach (var kvp in layouts) { foreach (var layout in kvp.Value) { uint index; // Custom keyboards may omit defining a country code. Try to survive such cases. string codeToMatch; if (layout.CountryCode == null) codeToMatch = layout.LanguageCode.ToLowerInvariant(); else codeToMatch = layout.CountryCode.ToLowerInvariant(); if ((keyboards.TryGetValue(layout.LayoutId, out index) && (layout.LayoutId == codeToMatch)) || keyboards.TryGetValue(string.Format("{0}+{1}", codeToMatch, layout.LayoutId), out index)) { AddKeyboardForLayout(layout, index, _adaptor); } } } }
void ITableEntity.ReadEntity(IDictionary<string, EntityProperty> properties, Microsoft.WindowsAzure.Storage.OperationContext operationContext) { // This can occasionally fail because someone didn't finish creating the entity yet. EntityProperty value; if (properties.TryGetValue("SerializedError", out value)) { Error = ErrorXml.DecodeString(value.StringValue); } else { Error = new Error { ApplicationName = "TableErrorLog", StatusCode = 999, HostName = Environment.MachineName, Time = DateTime.UtcNow, Type = typeof(Exception).FullName, Detail = "Error Log Entry is Corrupted/Missing in Table Store" }; return; } if (properties.TryGetValue("Detail", out value)) { Error.Detail = value.StringValue; } if (properties.TryGetValue("WebHostHtmlMessage", out value)) { Error.WebHostHtmlMessage = value.StringValue; } }
private void Load(IDictionary<string, int> parameters) { var subjectId = 0; var definitionId = 0; parameters.TryGetValue ("SubjectId", out subjectId); parameters.TryGetValue ("DefinitionId", out definitionId); parameters.TryGetValue ("Mode", out _currentMode); MeasurementSubjectId = subjectId; if (definitionId == 0) { var measurement = _instanceRepository.GetAll (predicate: null, orderBy: (o) => o.DateRecorded, descending: true, skip: 0, count: 1).FirstOrDefault (); if (measurement != null) { LoadFromDefinition (measurement.MeasurementDefinitionId, measurement.MeasurementSubjectId); } } else { LoadFromDefinition (definitionId, subjectId); } UnregisterMessages (); }
/// <summary> /// Initializes a new instance of the <see cref="RuntimeModelElementConstructorMetadata"/> class. /// </summary> /// <param name="metadata">The metadata.</param> public RuntimeModelElementConstructorMetadata(IDictionary<string, object> metadata) : base(metadata) { this.ModelType = (Type)metadata.TryGetValue(nameof(this.ModelType)); this.ModelContractType = (Type)metadata.TryGetValue(nameof(this.ModelContractType)); this.RuntimeType = (Type)metadata.TryGetValue(nameof(this.RuntimeType)); }
/// <summary> /// Creates a ScriptRuntimeSetup object which includes the Python script engine with the specified options. /// /// The ScriptRuntimeSetup object can then be additional configured and used to create a ScriptRuntime. /// </summary> /*!*/ public static ScriptRuntimeSetup CreateRuntimeSetup(IDictionary<string, object> options) { ScriptRuntimeSetup setup = new ScriptRuntimeSetup(); setup.LanguageSetups.Add(CreateLanguageSetup(options)); if (options != null) { object value; if (options.TryGetValue("Debug", out value) && value is bool && (bool)value) { setup.DebugMode = true; } if (options.TryGetValue("PrivateBinding", out value) && value is bool && (bool)value) { setup.PrivateBinding = true; } } return setup; }
private IObjectMap FindMap(IDictionary<Object, IObjectMap> dic, Object id, Boolean extend = false) { if (dic == null || dic.Count <= 0) return null; IObjectMap map = null; // 名称不能是null,否则字典里面会报错 if (id == null) id = String.Empty; // 如果找到,直接返回 if (dic.TryGetValue(id, out map) || dic.TryGetValue(id + "", out map)) return map; if (id == null || "" + id == String.Empty) { // 如果名称不为空,则试一试找空的 if (dic.TryGetValue(String.Empty, out map)) return map; } else if (extend) { // 如果名称为空,找第一个 foreach (var item in dic.Values) { return item; } } return null; }
public ChannelMetadata(IDictionary<string, object> metadata) { object raw; if (metadata.TryGetValue("Channel", out raw)) Channel = (int)raw; if (metadata.TryGetValue("Map", out raw)) Map = (string)raw; }
/// <summary> /// Sets up the webserver and starts it /// </summary> /// <param name="options">A set of options</param> public Server(IDictionary<string, string> options) { int port; string portstring; IEnumerable<int> ports = null; options.TryGetValue(OPTION_PORT, out portstring); if (!string.IsNullOrEmpty(portstring)) ports = from n in portstring.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries) where int.TryParse(n, out port) select int.Parse(n); if (ports == null || !ports.Any()) ports = new int[] { DEFAULT_OPTION_PORT }; string interfacestring; System.Net.IPAddress listenInterface; options.TryGetValue(OPTION_INTERFACE, out interfacestring); if (string.IsNullOrWhiteSpace(interfacestring)) interfacestring = Program.DataConnection.ApplicationSettings.ServerListenInterface; if (string.IsNullOrWhiteSpace(interfacestring)) interfacestring = DEFAULT_OPTION_INTERFACE; if (interfacestring.Trim() == "*" || interfacestring.Trim().Equals("any", StringComparison.InvariantCultureIgnoreCase)) listenInterface = System.Net.IPAddress.Any; else if (interfacestring.Trim() == "loopback") listenInterface = System.Net.IPAddress.Loopback; else listenInterface = System.Net.IPAddress.Parse(interfacestring); // If we are in hosted mode with no specified port, // then try different ports foreach(var p in ports) try { // Due to the way the server is initialized, // we cannot try to start it again on another port, // so we create a new server for each attempt var server = CreateServer(options); server.Start(listenInterface, p); m_server = server; m_server.ServerName = "Duplicati v" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString(); this.Port = p; if (interfacestring != Program.DataConnection.ApplicationSettings.ServerListenInterface) Program.DataConnection.ApplicationSettings.ServerListenInterface = interfacestring; return; } catch (System.Net.Sockets.SocketException) { } throw new Exception("Unable to open a socket for listening, tried ports: " + string.Join(",", from n in ports select n.ToString())); }
public override void Initialize(RazorHost razorHost, IDictionary<string, string> directives) { if (ReadSwitchValue(directives, GeneratePrettyNamesTransformer.DirectiveName) == true) { var trimLeadingUnderscores = ReadSwitchValue(directives, TrimLeadingUnderscoresKey) ?? false; _transformers.Add(new GeneratePrettyNamesTransformer(trimLeadingUnderscores)); } string typeVisibility; if (directives.TryGetValue(TypeVisibilityKey, out typeVisibility)) { _transformers.Add(new SetTypeVisibility(typeVisibility)); } string typeNamespace; if (directives.TryGetValue(NamespaceKey, out typeNamespace)) { _transformers.Add(new SetTypeNamespace(typeNamespace)); } if (ReadSwitchValue(directives, DisableLinePragmasKey) == true) { razorHost.EnableLinePragmas = false; } else if (ReadSwitchValue(directives, GenerateAbsolutePathLinePragmas) != true) { // Rewrite line pragamas to generate bin relative paths instead of absolute paths. _transformers.Add(new RewriteLinePragmas()); } if (ReadSwitchValue(directives, ExcludeFromCodeCoverage) == true) { _transformers.Add(new ExcludeFromCodeCoverageTransformer()); } string suffix; if (directives.TryGetValue(SuffixFileName, out suffix)) { _transformers.Add(new SuffixFileNameTransformer(suffix)); } string genericParameters; if (directives.TryGetValue(GenericParametersKey, out genericParameters)) { var parameters = from p in genericParameters.Split(',') select p.Trim(); _transformers.Add(new GenericParametersTransformer(parameters)); } string imports; if (directives.TryGetValue(ImportsKey, out imports)) { var values = from p in imports.Split(',') select p.Trim(); _transformers.Add(new SetImports(values, false)); } base.Initialize(razorHost, directives); }
/// <summary> /// Analyzes an incoming request message payload to discover what kind of /// message is embedded in it and returns the type, or null if no match is found. /// </summary> /// <param name="recipient">The intended or actual recipient of the request message.</param> /// <param name="fields">The name/value pairs that make up the message payload.</param> /// <returns> /// A newly instantiated <see cref="IProtocolMessage"/>-derived object that this message can /// deserialize to. Null if the request isn't recognized as a valid protocol message. /// </returns> public IDirectedProtocolMessage GetNewRequestMessage(MessageReceivingEndpoint recipient, IDictionary<string, string> fields) { ErrorUtilities.VerifyArgumentNotNull(recipient, "recipient"); ErrorUtilities.VerifyArgumentNotNull(fields, "fields"); RequestBase message = null; // Discern the OpenID version of the message. Protocol protocol = Protocol.V11; string ns; if (fields.TryGetValue(Protocol.V20.openid.ns, out ns)) { ErrorUtilities.VerifyProtocol(string.Equals(ns, Protocol.OpenId2Namespace, StringComparison.Ordinal), MessagingStrings.UnexpectedMessagePartValue, Protocol.V20.openid.ns, ns); protocol = Protocol.V20; } string mode; if (fields.TryGetValue(protocol.openid.mode, out mode)) { if (string.Equals(mode, protocol.Args.Mode.associate)) { if (fields.ContainsKey(protocol.openid.dh_consumer_public)) { message = new AssociateDiffieHellmanRequest(protocol.Version, recipient.Location); } else { message = new AssociateUnencryptedRequest(protocol.Version, recipient.Location); } } else if (string.Equals(mode, protocol.Args.Mode.checkid_setup) || string.Equals(mode, protocol.Args.Mode.checkid_immediate)) { AuthenticationRequestMode authMode = string.Equals(mode, protocol.Args.Mode.checkid_immediate) ? AuthenticationRequestMode.Immediate : AuthenticationRequestMode.Setup; if (fields.ContainsKey(protocol.openid.identity)) { message = new CheckIdRequest(protocol.Version, recipient.Location, authMode); } else { ErrorUtilities.VerifyProtocol(!fields.ContainsKey(protocol.openid.claimed_id), OpenIdStrings.IdentityAndClaimedIdentifierMustBeBothPresentOrAbsent); message = new SignedResponseRequest(protocol.Version, recipient.Location, authMode); } } else if (string.Equals(mode, protocol.Args.Mode.cancel) || (string.Equals(mode, protocol.Args.Mode.setup_needed) && (protocol.Version.Major >= 2 || fields.ContainsKey(protocol.openid.user_setup_url)))) { message = new NegativeAssertionResponse(protocol.Version, recipient.Location, mode); } else if (string.Equals(mode, protocol.Args.Mode.id_res)) { if (fields.ContainsKey(protocol.openid.identity)) { message = new PositiveAssertionResponse(protocol.Version, recipient.Location); } else { ErrorUtilities.VerifyProtocol(!fields.ContainsKey(protocol.openid.claimed_id), OpenIdStrings.IdentityAndClaimedIdentifierMustBeBothPresentOrAbsent); message = new IndirectSignedResponse(protocol.Version, recipient.Location); } } else if (string.Equals(mode, protocol.Args.Mode.check_authentication)) { message = new CheckAuthenticationRequest(protocol.Version, recipient.Location); } else if (string.Equals(mode, protocol.Args.Mode.error)) { message = new IndirectErrorResponse(protocol.Version, recipient.Location); } else { ErrorUtilities.ThrowProtocol(MessagingStrings.UnexpectedMessagePartValue, protocol.openid.mode, mode); } } if (message != null) { message.SetAsIncoming(); } return message; }
internal LeaderboardAndRank(IDictionary<string, object> dict) { object value; dict.TryGetValue ("rank", out value); Rank = new Rank ((IDictionary<string,object>)value); dict.TryGetValue ("leaderboard", out value); Leaderboard = new Leaderboard ((IDictionary<string,object>)value); }
public override bool IsApplicable(string name, IDictionary<string, object> properties) { object flat; object glyph; return (base.IsApplicable(name, properties) && properties.TryGetValue("Flat", out flat) && Equals(flat, true) && (!properties.TryGetValue("Glyph.Data", out glyph) || Equals(glyph, null))); }
public static string GetCompilerPath(IDictionary<string, string> provOptions, string compilerExecutable) { // Get the location of the runtime, the usual answer string compPath = Executor.GetRuntimeInstallDirectory(); // if provOptions is provided check to see if it alters what version we should bind to. // provOptions can be null if someone does new VB/CSCodeProvider(), in which case // they get the default behavior. if (provOptions != null) { string directoryPath; bool directoryPathPresent = provOptions.TryGetValue(DirectoryPath, out directoryPath); string versionVal; bool versionValPresent = provOptions.TryGetValue(NameTag, out versionVal); if(directoryPathPresent && versionValPresent) { throw new InvalidOperationException(SR.GetString(SR.Cannot_Specify_Both_Compiler_Path_And_Version, DirectoryPath, NameTag)); } // If they have an explicit path, use it. Otherwise, look it up from the registry. if (directoryPathPresent) { return directoryPath; } // If they have specified a version number in providerOptions, use it. if (versionValPresent) { switch (versionVal) { case RedistVersionInfo.InPlaceVersion: // Use the RuntimeInstallDirectory, already obtained break; case RedistVersionInfo.RedistVersion: // lock to the Orcas version, if it's not available throw (we'll throw at compile time) compPath = GetCompilerPathFromRegistry(versionVal); break; case RedistVersionInfo.RedistVersion20: //look up 2.0 compiler path from registry compPath = GetCompilerPathFromRegistry(versionVal); break; default: compPath = null; break; } } } if (compPath == null) throw new InvalidOperationException(SR.GetString(SR.CompilerNotFound, compilerExecutable)); return compPath; }
protected void RequestSimpleAttribute(QueryAttribute queryAttribute, IDictionary<object, TableQueryData> tableQueries, IList<TableJoin> tableJoins, string miaJoinType, IDictionary<QueryAttribute, RequestedAttribute> requestedAttributes, IDictionary<MediaItemAspectMetadata, TableQueryData> miaTypeTableQueries, RequestedAttribute miaIdAttribute, out RequestedAttribute requestedAttribute) { if (requestedAttributes.TryGetValue(queryAttribute, out requestedAttribute)) // Already requested return; MediaItemAspectMetadata.AttributeSpecification spec = queryAttribute.Attr; MediaItemAspectMetadata miaType = spec.ParentMIAM; TableQueryData tqd; switch (spec.Cardinality) { case Cardinality.Inline: // For Inline queries, we request the Inline attribute's column name at the MIA main table, which gets joined // with the MIA ID if (!tableQueries.TryGetValue(miaType, out tqd)) { tqd = tableQueries[miaType] = TableQueryData.CreateTableQueryOfMIATable(_miaManagement, miaType); if (miaTypeTableQueries != null) miaTypeTableQueries.Add(miaType, tqd); tableJoins.Add(new TableJoin(miaJoinType, tqd, miaIdAttribute, new RequestedAttribute(tqd, MIA_Management.MIA_MEDIA_ITEM_ID_COL_NAME))); } requestedAttribute = new RequestedAttribute(tqd, _miaManagement.GetMIAAttributeColumnName(queryAttribute.Attr)); break; case Cardinality.ManyToOne: // For MTO queries, we request both the MIA main table and the MTO table TableQueryData miaTqd; if (!tableQueries.TryGetValue(miaType, out miaTqd)) { miaTqd = tableQueries[miaType] = TableQueryData.CreateTableQueryOfMIATable(_miaManagement, miaType); if (miaTypeTableQueries != null) miaTypeTableQueries.Add(miaType, miaTqd); // Add MIA main table to list of table joins tableJoins.Add(new TableJoin(miaJoinType, miaTqd, miaIdAttribute, new RequestedAttribute(miaTqd, MIA_Management.MIA_MEDIA_ITEM_ID_COL_NAME))); } if (!tableQueries.TryGetValue(spec, out tqd)) { tqd = tableQueries[spec] = TableQueryData.CreateTableQueryOfMTOTable(_miaManagement, spec); // We must use left outer joins for MTO value tables, because if the value is null, the association FK is null tableJoins.Add(new TableJoin("LEFT OUTER JOIN", tqd, new RequestedAttribute(miaTqd, _miaManagement.GetMIAAttributeColumnName(queryAttribute.Attr)), new RequestedAttribute(tqd, MIA_Management.FOREIGN_COLL_ATTR_ID_COL_NAME))); } requestedAttribute = new RequestedAttribute(tqd, MIA_Management.COLL_ATTR_VALUE_COL_NAME); break; default: throw new IllegalCallException("Attributes of cardinality '{0}' cannot be queried via the {1}", spec.Cardinality, GetType().Name); } requestedAttributes.Add(queryAttribute, requestedAttribute); }
public static EndpointDetails ReceivingEndpoint(IDictionary<string, string> headers) { var endpoint = new EndpointDetails(); string hostIdHeader; if (headers.TryGetValue(Headers.HostId, out hostIdHeader)) { endpoint.HostId = Guid.Parse(hostIdHeader); } string hostDisplayNameHeader; if (headers.TryGetValue(Headers.HostDisplayName, out hostDisplayNameHeader)) { endpoint.Host = hostDisplayNameHeader; } else { DictionaryExtensions.CheckIfKeyExists("NServiceBus.ProcessingMachine", headers, s => endpoint.Host = s); } DictionaryExtensions.CheckIfKeyExists(Headers.ProcessingEndpoint, headers, s => endpoint.Name = s); if (!string.IsNullOrEmpty(endpoint.Name) && !string.IsNullOrEmpty(endpoint.Host)) { return endpoint; } var address = Address.Undefined; //use the failed q to determine the receiving endpoint DictionaryExtensions.CheckIfKeyExists("NServiceBus.FailedQ", headers, s => address = Address.Parse(s)); // If we have a failed queue, then construct an endpoint from the failed queue information if (address != Address.Undefined) { if (string.IsNullOrEmpty(endpoint.Name)) { endpoint.Name = address.Queue; } if (string.IsNullOrEmpty(endpoint.Host)) { endpoint.Host = address.Machine; } // If we've been now able to get the endpoint details, return the new info. if (!string.IsNullOrEmpty(endpoint.Name) && !string.IsNullOrEmpty(endpoint.Host)) { return endpoint; } } return null; }
/// <summary> /// Initializes a new instance of the <see cref="DataConverterMetadata"/> class. /// </summary> /// <param name="metadata">The metadata.</param> public DataConverterMetadata(IDictionary<string, object> metadata) : base(metadata) { if (metadata == null) { return; } this.SourceType = (Type)metadata.TryGetValue(nameof(this.SourceType)); this.TargetType = (Type)metadata.TryGetValue(nameof(this.TargetType)); }
public void Configure(IDictionary<string, string> commandlineOptions) { commandlineOptions.TryGetValue(STARTUP_OPTION, out m_startScript); commandlineOptions.TryGetValue(REQUIRED_OPTION, out m_requiredScript); commandlineOptions.TryGetValue(FINISH_OPTION, out m_finishScript); string t; if (!commandlineOptions.TryGetValue(TIMEOUT_OPTION, out t)) t = DEFAULT_TIMEOUT; m_timeout = (int)Utility.Timeparser.ParseTimeSpan(t).TotalMilliseconds; m_options = commandlineOptions; }
public ICache BuildCache(string regionName, IDictionary<string, string> properties) { if (_dataCache == null) { throw new InvalidOperationException("Can't call this method when provider is in stopped state."); } TimeSpan? expiration = null; string expirationString; if (properties.TryGetValue(NHibernate.Cfg.Environment.CacheDefaultExpiration, out expirationString) || properties.TryGetValue("cache.default_expiration", out expirationString)) { expiration = TimeSpan.FromSeconds(Int32.Parse(expirationString)); } return new AzureCacheClient(_dataCache, regionName, expiration); }
public static void ThrowIfError(IDictionary<string, string> responseValues) { if (responseValues != null) { string error = null; string errorDescription = null; if (responseValues.TryGetValue(Constants.Authentication.ErrorDescriptionKeyName, out errorDescription) || responseValues.TryGetValue(Constants.Authentication.ErrorKeyName, out error)) { OAuthErrorHandler.ParseAuthenticationError(error, errorDescription); } } }
private static MessageRegistration ExtractFrom(IDictionary<string, string> properties) { string type; string versionString; int version = 0; properties.TryGetValue(EventDataPropertyKeys.MessageType, out type); if (properties.TryGetValue(EventDataPropertyKeys.MessageTypeVersion, out versionString)) { version = int.Parse(versionString); } return new MessageRegistration { Type = type, Version = version }; }
/// <summary> /// Initializes a new instance of the <see cref="RuntimeElementInfoFactoryMetadata"/> class. /// </summary> /// <param name="metadata">The metadata.</param> public RuntimeElementInfoFactoryMetadata(IDictionary<string, object> metadata) : base(metadata) { object value; if (metadata.TryGetValue(ElementInfoTypeKey, out value)) { this.ElementInfoType = (Type)value; } if (metadata.TryGetValue(RuntimeInfoTypeKey, out value)) { this.RuntimeInfoType = (Type)value; } }
public void Initialize(IDirectoryProvider directoryProvider, IDictionary<string, string> indexProperties, ISearchFactoryImplementor searchFactoryImplementor) { this.directoryProvider = directoryProvider; string maxString; indexProperties.TryGetValue("optimizer.operation_limit.max", out maxString); if (!string.IsNullOrEmpty(maxString)) int.TryParse(maxString, out operationMax); indexProperties.TryGetValue("optimizer.transaction_limit.max", out maxString); if (!string.IsNullOrEmpty(maxString)) int.TryParse(maxString, out transactionMax); }
public static string GetCompilerPath(IDictionary<string, string> provOptions, string compilerExecutable) { string runtimeInstallDirectory = Executor.GetRuntimeInstallDirectory(); if (provOptions != null) { string str2; string str3; bool flag = provOptions.TryGetValue("CompilerDirectoryPath", out str2); bool flag2 = provOptions.TryGetValue("CompilerVersion", out str3); if (flag && flag2) { throw new InvalidOperationException(SR.GetString("Cannot_Specify_Both_Compiler_Path_And_Version", new object[] { "CompilerDirectoryPath", "CompilerVersion" })); } if (flag) { return str2; } if (flag2) { string str4 = str3; if (str4 == null) { goto Label_00A9; } if (str4 != "v4.0") { if (!(str4 == "v3.5")) { if (str4 == "v2.0") { runtimeInstallDirectory = GetCompilerPathFromRegistry(str3); goto Label_00AB; } goto Label_00A9; } runtimeInstallDirectory = GetCompilerPathFromRegistry(str3); } } } goto Label_00AB; Label_00A9: runtimeInstallDirectory = null; Label_00AB: if (runtimeInstallDirectory == null) { throw new InvalidOperationException(SR.GetString("CompilerNotFound", new object[] { compilerExecutable })); } return runtimeInstallDirectory; }
internal static ServerError Create(IDictionary<string, object> dict, IJsonSerializerStrategy strategy) { object status, error; int statusCode = -1; if (dict.TryGetValue("status", out status)) statusCode = Convert.ToInt32(status); if (!dict.TryGetValue("error", out error)) return null; return new ServerError { Status = statusCode, Error = (Error)strategy.DeserializeObject(error, typeof(Error)) }; }
void IExternalBlobConnectionProvider.Configure(IDictionary<string, string> settings) { string connStr; if (settings.TryGetValue(Environment.ConnectionStringNameProperty, out connStr)) { ConnectionStringSettings connectionStringSettings = ConfigurationManager.ConnectionStrings[connStr]; if (connectionStringSettings == null) throw new HibernateException(string.Format("Could not find named connection string {0}", connStr)); ConnectionString = connectionStringSettings.ConnectionString; } else if (settings.TryGetValue(Environment.ConnectionStringProperty, out connStr)) { ConnectionString = connStr; } }
/// <summary> /// Retrieves a value from the single-instance share. /// </summary> /// <typeparam name="T">The type of the desired data.</typeparam> /// <param name="key">The string key to retrieve. <i>Suggested key format: YourMod. /// Category.KeyName</i></param> /// <returns>The data associated with that key.</returns> public static T GetData <T>(string key) { T value = default; object sval = null; if (string.IsNullOrEmpty(key)) { throw new ArgumentNullException("key"); } InitRegistry(); registry?.TryGetValue(key, out sval); if (sval is T) { value = (T)sval; } return(value); }
public IDbConnection Create(string name) { DbConnectionConfig dbConnectionConfig = null; if (configurationList?.TryGetValue(name, out dbConnectionConfig) ?? false) { switch ((dbConnectionConfig.Provider?.ToLower() ?? "")) { case var prv when prv == DbProviders.Oracle: return(CreateOraConnection(dbConnectionConfig)); default: throw new InvalidOperationException($"Тип провайдера данных {dbConnectionConfig.Provider} не поддерживается"); } } throw new InvalidOperationException($"Конфигурация для соединения {name} не найдена"); }
protected virtual IMessage DoConvert(object payload, IDictionary <string, object> headers, IMessagePostProcessor postProcessor) { IMessageHeaders messageHeaders = null; object conversionHint = null; headers?.TryGetValue(CONVERSION_HINT_HEADER, out conversionHint); var headersToUse = ProcessHeadersToSend(headers); if (headersToUse != null) { if (headersToUse is MessageHeaders) { messageHeaders = (MessageHeaders)headersToUse; } else { messageHeaders = new MessageHeaders(headersToUse, null, null); } } var converter = MessageConverter; var message = converter is ISmartMessageConverter ? ((ISmartMessageConverter)converter).ToMessage(payload, messageHeaders, conversionHint) : converter.ToMessage(payload, messageHeaders); if (message == null) { var payloadType = payload.GetType().Name; object contentType = null; messageHeaders?.TryGetValue(MessageHeaders.CONTENT_TYPE, out contentType); contentType = contentType ?? "unknown"; throw new MessageConversionException("Unable to convert payload with type='" + payloadType + "', contentType='" + contentType + "', converter=[" + MessageConverter + "]"); } if (postProcessor != null) { message = postProcessor.PostProcessMessage(message); } return(message); }
private static string MapInterpreterId(string idStr, string versionStr, IDictionary <Guid, string> msBuildInterpreters) { int splitter = idStr.IndexOfAny(new[] { '/', '\\' }); if (splitter > 0) { versionStr = idStr.Substring(splitter + 1); idStr = idStr.Remove(splitter); } Guid id; Version version; if (string.IsNullOrEmpty(idStr) || !Guid.TryParse(idStr, out id)) { return(null); } string fmt; if (InterpreterIdMap.TryGetValue(id, out fmt)) { if (string.IsNullOrEmpty(versionStr) || !Version.TryParse(versionStr, out version)) { return(null); } // CPython 3.5 32-bit needs a special fix to the version string if (id == new Guid("{2AF0F10D-7135-4994-9156-5D01C9C11B7E}") && version == new Version(3, 5)) { return(fmt.FormatInvariant("3.5-32")); } return(fmt.FormatInvariant(version.ToString())); } string msbuildId = null; if ((msBuildInterpreters?.TryGetValue(id, out msbuildId) ?? false) && !string.IsNullOrEmpty(msbuildId)) { return("MSBuild|{0}|$(MSBuildProjectFullPath)".FormatInvariant(msbuildId)); } return(null); }
public static async Task ApplyRegistration(Registration registration, IDictionary <string, string> classMap = null) { var stylesheet = await Stylesheet.GetInstance(); if (registration.RulesToInsert?.Any() == true) { // rulesToInsert is an ordered array of selector/rule pairs. for (var i = 0; i < registration.RulesToInsert.Count; i += 2) { var rules = registration.RulesToInsert[i + 1]; if (!string.IsNullOrWhiteSpace(rules)) { var selector = registration.RulesToInsert[i]; selector = Regex.Replace(selector, @"(&)|\$([\w-]+)\b", (match) => { var amp = match.Groups[1]; var cn = match.Groups[2]; if (amp.Success) { return("." + registration.ClassName); } else if (cn.Success) { string value = null; var success = classMap?.TryGetValue(cn.Value, out value); return("." + (success == true ? value : cn.Value)); } return(""); }, RegexOptions.Compiled); // Fix selector using map. // Insert. Note if a media query, we must close the query with a final bracket. var processedRule = string.Format("{0}{1}{2}", selector, "{" + rules + "}", selector.IndexOf("@media") == 0 ? "}" : ""); stylesheet.InsertRule(processedRule); } } stylesheet.CacheClassName(registration.ClassName, registration.Key, registration.Args, registration.RulesToInsert.ToArray()); } }
public DriveInfoContract GetDrive(RootName root, string apiKey, IDictionary <string, string> parameters) { if (root == null) { throw new ArgumentNullException(nameof(root)); } if (parameters?.TryGetValue(PARAMETER_ROOT, out rootPath) != true) { throw new ArgumentException($"Required {PARAMETER_ROOT} missing in {nameof(parameters)}".ToString(CultureInfo.CurrentCulture)); } if (string.IsNullOrEmpty(rootPath)) { throw new ArgumentException($"{PARAMETER_ROOT} cannot be empty".ToString(CultureInfo.CurrentCulture)); } var drive = new DriveInfo(Path.GetFullPath(rootPath)); return(new DriveInfoContract(root.Value, drive.AvailableFreeSpace, drive.TotalSize - drive.AvailableFreeSpace)); }
public async Task Run( [BlobTrigger("%BlobPath%/{name}", Connection = "BlobConnection")] Stream myBlob, string name, IDictionary <string, string> metadata, [ServiceBus("%ContactsTopicName%", Connection = "ContactsTopicSendConnection")] MessageSender messagesQueue) { logger.LogInformation($"C# Blob trigger function Processed blob\n Name:{name} \n Size: {myBlob.Length} Bytes"); try { // extract userToken var userToken = string.Empty; metadata?.TryGetValue(UserToken, out userToken); // extract meetings var reader = new StreamReader(myBlob); var jsonContent = await reader.ReadToEndAsync(); JObject jsonObject = JObject.Parse(jsonContent); IList <Meeting> meetings = null; JToken trgArray = jsonObject.Descendants().First(d => d is JArray); if (trgArray != null && trgArray.Type == JTokenType.Array) { meetings = JsonConvert.DeserializeObject <List <Meeting> >(trgArray.ToString()); } if (meetings == null) { throw new Exception("Invalid meeting list format"); } logger.LogInformation("UserToken: {userToken}. Received {meetingsCount} meetings", userToken, meetings.Count); contactTracingService.MessageSender = messagesQueue; await contactTracingService.ProcessContactList(userToken, meetings); } catch (Exception ex) { logger.LogError(ex, $"Unhandled exception: {ex.Message}"); throw; } }
protected void AddPropertyValue(IProperty property, string?culture, string?segment, IDictionary <string, IEnumerable <object?> >?values) { var editor = _propertyEditors[property.PropertyType.PropertyEditorAlias]; if (editor == null) { return; } var indexVals = editor.PropertyIndexValueFactory.GetIndexValues(property, culture, segment, PublishedValuesOnly); foreach (var keyVal in indexVals) { if (keyVal.Key.IsNullOrWhiteSpace()) { continue; } var cultureSuffix = culture == null ? string.Empty : "_" + culture; foreach (var val in keyVal.Value) { switch (val) { //only add the value if its not null or empty (we'll check for string explicitly here too) case null: continue; case string strVal: { if (strVal.IsNullOrWhiteSpace()) { continue; } var key = $"{keyVal.Key}{cultureSuffix}"; if (values?.TryGetValue(key, out var v) ?? false) { values[key] = new List <object?>(v) { val } } .ToArray();
public async Task <RootDirectoryInfoContract> GetRootAsync(RootName root, string apiKey, IDictionary <string, string> parameters) { var baseAddress = default(string); if (parameters?.TryGetValue(PARAMETER_BASEADDRESS, out baseAddress) != true) { throw new ArgumentException($"Required {PARAMETER_BASEADDRESS} missing in {nameof(parameters)}".ToString(CultureInfo.CurrentCulture)); } var context = await RequireContextAsync(root, apiKey, new Uri(baseAddress)); var propfindResponse = await context.Client.Propfind(context.AppendPrefix("/")); CheckSuccess(propfindResponse, nameof(WebDavClient.Propfind), "/"); var item = propfindResponse.Resources.Single(r => context.RemovePrefix(r.Uri) == "/"); return(new RootDirectoryInfoContract(item.Uri, item.CreationDate ?? DateTimeOffset.FromFileTime(0), item.LastModifiedDate ?? DateTimeOffset.FromFileTime(0))); }
public static IDbManager CreateDbManager(string providerName, string connectionString = null) { IDbManager dbManager; Type t = null; Managers?.TryGetValue(providerName, out t); if (t != null) { dbManager = (IDbManager)Activator.CreateInstance(t); dbManager.ConnectionString = connectionString; } else { throw new TypeLoadException($"Provider {providerName} not found."); } return(dbManager); }
private string GetConfigValue(string key) // TODO: not thread safe { string value; if (_config.TryGetValue(key, out value)) { return(value); } string configFileName = ConfigurationManager.AppSettings["ConfigFile"]; XDocument document = XDocument.Load(configFileName); _config = document.Root?.Elements("add").ToDictionary(e => e.Attribute("key")?.Value, e => e.Attribute("value")?.Value); if (_config?.TryGetValue(key, out value) == true) { return(value); } return(null); }
private static void ConfigureArchiveDataLayer(IServiceCollection services, IDictionary <string, DbConnectionConfig> dbConnectionList) { DbConnectionConfig dbConnectionConfig = null; if (dbConnectionList?.TryGetValue(QueriesConstants.ArchiveDbName, out dbConnectionConfig) ?? false) { switch ((dbConnectionConfig.Provider?.ToLower() ?? "")) { case var prv when prv == DbProviders.Oracle: { ConfigureOraArchiveDataLayer(services, dbConnectionConfig); break; } default: throw new InvalidOperationException($"Тип провайдера данных {dbConnectionConfig.Provider} не поддерживается"); } } throw new InvalidOperationException($"Конфигурация для соединения {QueriesConstants.ArchiveDbName} не найдена"); }
/// <summary> /// Compile the specified expression /// </summary> /// <param name="me"></param> /// <param name="fieldOrExpression"></param> /// <returns></returns> public static Lambda CompileExpression(this IRenderContext me, String fieldOrExpression) { IDictionary <String, Lambda> exprs = me.Parent?.Tags["expressions"] as IDictionary <String, Lambda>; Lambda evaluator = null; if (exprs?.TryGetValue(fieldOrExpression, out evaluator) != true) { var interpretor = new Interpreter(InterpreterOptions.Default) .Reference(typeof(Guid)) .Reference(typeof(DateTimeOffset)) .Reference(typeof(TimeSpan)) .SetVariable("BiUtil", m_helpers) .SetFunction("now", (Func <DateTime>)(() => DateTime.Now)); evaluator = interpretor.Parse(fieldOrExpression, (me.ScopedObject as IDictionary <String, Object>).Select(o => new Parameter(o.Key, o.Value?.GetType() ?? typeof(Object))).ToArray()); } return(evaluator); }
public static string GetParameters(IDictionary <string, JToken> actionArguments) { JToken vsoBuildParametersToken = null; actionArguments?.TryGetValue("vsoBuildParameters", out vsoBuildParametersToken); if (vsoBuildParametersToken == null) { return(null); } JObject parameterObject = (JObject)vsoBuildParametersToken; foreach (KeyValuePair <string, JToken> parameter in parameterObject) { string value = GetValueString(parameter.Value); parameterObject[parameter.Key] = value; } return(parameterObject.ToString()); }
private static string MapInterpreterId(string idStr, string versionStr, IDictionary <Guid, string> msBuildInterpreters) { int splitter = idStr.IndexOfAny(new[] { '/', '\\' }); if (splitter > 0) { versionStr = idStr.Substring(splitter + 1); idStr = idStr.Remove(splitter); } Guid id; Version version; if (string.IsNullOrEmpty(idStr) || !Guid.TryParse(idStr, out id)) { return(null); } string fmt; if (InterpreterIdMap.TryGetValue(id, out fmt)) { if (string.IsNullOrEmpty(versionStr) || !Version.TryParse(versionStr, out version)) { return(null); } return(fmt.FormatInvariant(version.ToString())); } string msbuildId = null; if ((msBuildInterpreters?.TryGetValue(id, out msbuildId) ?? false) && !string.IsNullOrEmpty(msbuildId)) { return("MSBuild|{0}|$(MSBuildProjectFullPath)".FormatInvariant(msbuildId)); } return(null); }
public async Task <DriveInfoContract> GetDriveAsync(RootName root, string apiKey, IDictionary <string, string> parameters) { var baseAddress = default(string); if (parameters?.TryGetValue(PARAMETER_BASEADDRESS, out baseAddress) != true) { throw new ArgumentException($"Required {PARAMETER_BASEADDRESS} missing in {nameof(parameters)}".ToString(CultureInfo.CurrentCulture)); } var context = await RequireContextAsync(root, apiKey, new Uri(baseAddress)); var propfindResponse = await context.Client.Propfind(context.AppendPrefix("/")); CheckSuccess(propfindResponse, nameof(WebDavClient.Propfind), "/"); var item = propfindResponse.Resources.Single(r => context.RemovePrefix(r.Uri) == "/"); var availableSpaceValue = item.Properties.SingleOrDefault(p => p.Name == availableSpaceProperty)?.Value; var usedSpaceValue = item.Properties.SingleOrDefault(p => p.Name == usedSpaceProperty)?.Value; return(new DriveInfoContract(root.Value, !string.IsNullOrEmpty(availableSpaceValue) ? long.Parse(availableSpaceValue) : 1 << 30, !string.IsNullOrEmpty(usedSpaceValue) ? long.Parse(usedSpaceValue) : 0)); }
private static HttpResponseMessage CreateResponse(HttpRequestMessage request, HttpStatusCode statusCode, object content, IDictionary <string, object> headers, bool isRawResponse) { if (isRawResponse) { // We only write the response through one of the formatters if // the function hasn't indicated that it wants to write the raw response return(new HttpResponseMessage(statusCode) { Content = CreateResultContent(content) }); } string contentType = null; MediaTypeHeaderValue mediaType = null; if (content != null && (headers?.TryGetValue <string>("content-type", out contentType, ignoreCase: true) ?? false) && MediaTypeHeaderValue.TryParse((string)contentType, out mediaType)) { var writer = request.GetConfiguration().Formatters.FindWriter(content.GetType(), mediaType); if (writer != null) { return(new HttpResponseMessage(statusCode) { Content = new ObjectContent(content.GetType(), content, writer, mediaType) }); } // create a non-negotiated result content HttpContent resultContent = CreateResultContent(content, mediaType.MediaType); return(new HttpResponseMessage(statusCode) { Content = resultContent }); } return(CreateNegotiatedResponse(request, statusCode, content)); }
/// <summary> /// Initializes the <see cref="_graph"/> field which stores the graph that we operate on. /// </summary> private void CopyToWorkingGraph() { // Make a copy of the original graph _graph = new BidirectionalGraph <SugiVertex, SugiEdge>(); // Copy the vertices foreach (TVertex vertex in VisitedGraph.Vertices) { var size = default(Size); _verticesSizes?.TryGetValue(vertex, out size); var vertexWrapper = new SugiVertex(vertex, size); _graph.AddVertex(vertexWrapper); _verticesMap[vertex] = vertexWrapper; } // Copy the edges foreach (TEdge edge in VisitedGraph.Edges) { var edgeWrapper = new SugiEdge(edge, _verticesMap[edge.Source], _verticesMap[edge.Target]); _graph.AddEdge(edgeWrapper); } }
/// <summary> /// Gets a stream containing the image binary in the specified property (or the default Binary field). /// Image dimensions can be determined by providing the width and height values among the parameters. /// The image is also redacted if the user does not have enough permissions to see the full image /// in case of preview images, only restricted ones. /// </summary> /// <param name="propertyName">Name of the binary property to serve, default is Binary.</param> /// <param name="parameters">Optional parameters that may include image width and height.</param> /// <param name="contentType">Out parameter, filled with the binary content type to be served to the client.</param> /// <param name="fileName">Out parameter, filled with the file name to serve to the client.</param> public Stream GetImageStream(string propertyName, IDictionary <string, object> parameters, out string contentType, out BinaryFileName fileName) { Stream imageStream; object widthParam = null; object heightParam = null; object watermarkParam = null; parameters?.TryGetValue("width", out widthParam); parameters?.TryGetValue("height", out heightParam); parameters?.TryGetValue("watermark", out watermarkParam); var binaryData = !string.IsNullOrEmpty(propertyName) ? GetBinary(propertyName) : Binary; contentType = binaryData?.ContentType ?? string.Empty; fileName = string.IsNullOrEmpty(propertyName) || string.CompareOrdinal(propertyName, "Binary") == 0 ? new BinaryFileName(Name) : binaryData?.FileName ?? string.Empty; if (DocumentPreviewProvider.Current != null && DocumentPreviewProvider.Current.IsPreviewOrThumbnailImage(NodeHead.Get(Id))) { var options = new PreviewImageOptions { BinaryFieldName = propertyName }; if (watermarkParam != null && ((int.TryParse((string)watermarkParam, out var wmValue) && wmValue == 1) || (bool.TryParse((string)watermarkParam, out var wmBool) && wmBool))) { options.RestrictionType = RestrictionType.Watermark; } // get preview image with watermark or redaction if necessary imageStream = DocumentPreviewProvider.Current.GetRestrictedImage(this, options); } else { imageStream = binaryData?.GetStream(); } if (imageStream == null) { return(new MemoryStream()); } imageStream.Position = 0; int ConvertImageParameter(object param) { if (param != null) { // we recognize int and string values as well switch (param) { case int i: return(i); case string s when int.TryParse(s, out var pint): return(pint); } } return(200); } // no resize parameters: return the original stream if (widthParam == null || heightParam == null) { return(imageStream); } var width = ConvertImageParameter(widthParam); var height = ConvertImageParameter(heightParam); // compute a new, resized stream on-the-fly var resizedStream = ImageResizer.CreateResizedImageFile(imageStream, width, height, 80, getImageFormat(contentType)); // in case the method created a new stream, we have to close the original to prevent memory leak if (!ReferenceEquals(resizedStream, imageStream)) { imageStream.Dispose(); } return(resizedStream); }
bool Headers.TryGetHeader(string key, out object value) { return(_headers.TryGetValue(key, out value)); }
private static void TryMapType(Type type, IDictionary <Type, List <MemberInfo> > map, ISet <Type> visited) { while (true) { if (type == null) { return; } if (visited.Contains(type)) { return; } visited.Add(type); if (type.IsArray || type.IsByRef) { type = type.GetElementType(); continue; } if (Filtered(type)) { return; } if (!map.TryGetValue(type, out var list)) { map.Add(type, list = new List <MemberInfo>()); } foreach (var member in AccessorMembers.Create(type, scope: AccessorMemberScope.Public)) { switch (member.MemberType) { case AccessorMemberType.Property: { if (!map.ContainsKey(member.Type)) { TryMapType(member.Type, map, visited); } list.Add(member.MemberInfo); break; } case AccessorMemberType.Field: { if (!map.ContainsKey(member.Type)) { TryMapType(member.Type, map, visited); } list.Add(member.MemberInfo); break; } case AccessorMemberType.Method: { list.Add(member.MemberInfo); if (member.MemberInfo is MethodInfo method) { foreach (var parameter in method.GetParameters()) { if (!map.ContainsKey(parameter.ParameterType)) { TryMapType(parameter.ParameterType, map, visited); } } } break; } default: throw new ArgumentOutOfRangeException(); } } break; } }
/// <summary> /// Gets a value from the dictionary with given key. Returns default value if can not find. /// </summary> /// <param name="dictionary">Dictionary to check and get</param> /// <param name="key">Key to find the value</param> /// <typeparam name="TKey">Type of the key</typeparam> /// <typeparam name="TValue">Type of the value</typeparam> /// <returns>Value if found, default if can not found.</returns> public static TValue GetOrDefault <TKey, TValue>(this IDictionary <TKey, TValue> dictionary, TKey key) { return(dictionary.TryGetValue(key, out TValue obj) ? obj : default(TValue)); }
public static string GetReasonPhrase(int statusCode) { return Phrases.TryGetValue(statusCode, out var phrase) ? phrase : string.Empty; }
/// <summary> /// Performs the same resolution and validation as /// <see cref="ResolveParams"/> but also assigns the resolved /// parameter values to their corresponding same-named properties /// of the target object. /// </summary> /// <param name="strictTarget"> /// If <c>true</c> and the target is missing one of the resolved /// parameters, an exception will be thrown. /// </param> public static T ResolveParams <T>( IEnumerable <ExtParamInfo> paramInfos, IDictionary <string, object> paramVals, T target = default(T), bool strictTarget = false) { Type targetType = null; TypeInfo targetTypeInfo = null; if (target != null) { targetType = target.GetType(); targetTypeInfo = targetType.GetTypeInfo(); } foreach (var pi in paramInfos) { object val = null; if (!(paramVals?.TryGetValue(pi.Name, out val)).GetValueOrDefault()) { if (pi.IsRequired) { throw new ArgumentNullException(pi.Name, AsmRes.EXCEPTIONS["missing required provider parameter"]); } } else { try { switch (pi.Type) { case ExtParamType.STRING: case ExtParamType.TEXT: val = (string)val; break; case ExtParamType.NUMBER: val = (int)val; break; case ExtParamType.BOOLEAN: val = (bool)val; break; case ExtParamType.SECRET: val = (SecureString)val; break; case ExtParamType.SEQ_STRING: val = (IEnumerable <string>)val; break; case ExtParamType.KVP_STRING: val = (IDictionary <string, string>)val; break; default: throw new NotImplementedException(AsmRes.EXCEPTIONS.With( "parameter type [{0}] is not supported", pi.Type)); } } catch (InvalidCastException) { throw new ArgumentException( AsmRes.EXCEPTIONS["incompatible type for provider parameter"], pi.Name); } if (targetTypeInfo != null) { var prop = targetTypeInfo.GetProperty(pi.Name, BindingFlags.Public | BindingFlags.Instance); if (prop == null) { if (strictTarget) { throw new MissingMemberException(AsmRes.EXCEPTIONS.With( "target object is missing expected property [{0}]", pi.Name)); } } else { prop.SetValue(target, val); } } } } return(target); }
static void AddPreflightOperationSelector( OperationDescription operation, string[] allowedOrigins = null, int maxAge = 600, IDictionary <string, PreflightOperationBehavior> uriTemplates = null) { if (operation == null) { throw new ArgumentNullException(nameof(operation)); } if (operation.IsOneWay) { // no support for 1-way messages return; } string originalUriTemplate; string originalMethod; var webInvoke = operation.Behaviors.Find <WebInvokeAttribute>(); if (webInvoke != null) { if (webInvoke.Method == "OPTIONS") { return; } originalMethod = webInvoke.Method ?? "POST"; originalUriTemplate = webInvoke.UriTemplate; } else { var webGet = operation.Behaviors.Find <WebGetAttribute>(); if (webGet == null) { return; } originalMethod = "GET"; originalUriTemplate = webGet.UriTemplate; } originalUriTemplate = originalUriTemplate != null?NormalizeTemplate(originalUriTemplate) : operation.Name; if (originalUriTemplate.IsNullOrWhiteSpace()) { originalUriTemplate = "/"; } PreflightOperationBehavior preflightOperationBehavior = null; if (uriTemplates?.TryGetValue(originalUriTemplate, out preflightOperationBehavior) == true) { // there is already an OPTIONS operation for this URI, we can reuse it, just add the method preflightOperationBehavior?.AddAllowedMethod(originalMethod); return; } var contract = operation.DeclaringContract; var inputMessage = new MessageDescription(operation.Messages[0].Action + Constants.PreflightSuffix, MessageDirection.Input); inputMessage .Body .Parts .Add( new MessagePartDescription("input", contract.Namespace) { Index = 0, Type = typeof(Message), }); var outputMessage = new MessageDescription(operation.Messages[1].Action + Constants.PreflightSuffix, MessageDirection.Output); outputMessage .Body .ReturnValue = new MessagePartDescription(operation.Name + Constants.PreflightSuffix + "Return", contract.Namespace) { Type = typeof(Message), }; preflightOperationBehavior = new PreflightOperationBehavior(allowedOrigins, maxAge); preflightOperationBehavior.AddAllowedMethod(originalMethod); var preflightOperation = new OperationDescription(operation.Name + Constants.PreflightSuffix, contract); preflightOperation.Messages.Add(inputMessage); preflightOperation.Messages.Add(outputMessage); preflightOperation.Behaviors.Add(new WebInvokeAttribute { Method = "OPTIONS", UriTemplate = originalUriTemplate, }); preflightOperation.Behaviors.Add(new DataContractSerializerOperationBehavior(preflightOperation)); preflightOperation.Behaviors.Add(preflightOperationBehavior); contract.Operations.Add(preflightOperation); uriTemplates?.Add(originalUriTemplate, preflightOperationBehavior); }
/// <inheritdoc/> public bool TryGetRaw(string key, out object value) { _ = key ?? throw new ArgumentNullException(nameof(key)); value = default; return((Dictionary?.TryGetValue(key, out value) ?? false) || (_previous?.TryGetRaw(key, out value) ?? false)); }
private void EnhanceRun( IEnumerable <string> analysisTargets, OptionallyEmittedData dataToInsert, OptionallyEmittedData dataToRemove, IEnumerable <string> invocationTokensToRedact, IEnumerable <string> invocationPropertiesToLog, string defaultFileEncoding = null, IDictionary <string, HashData> filePathToHashDataMap = null) { _run.Invocations ??= new List <Invocation>(); if (defaultFileEncoding != null) { _run.DefaultEncoding = defaultFileEncoding; } Encoding encoding = SarifUtilities.GetEncodingFromName(_run.DefaultEncoding); if (analysisTargets != null) { _run.Artifacts ??= new List <Artifact>(); foreach (string target in analysisTargets) { Uri uri = new Uri(UriHelper.MakeValidUri(target), UriKind.RelativeOrAbsolute); HashData hashData = null; if (dataToInsert.HasFlag(OptionallyEmittedData.Hashes)) { filePathToHashDataMap?.TryGetValue(target, out hashData); } var artifact = Artifact.Create( new Uri(target, UriKind.RelativeOrAbsolute), dataToInsert, encoding, hashData: hashData); var fileLocation = new ArtifactLocation { Uri = uri }; artifact.Location = fileLocation; // This call will insert the file object into run.Files if not already present artifact.Location.Index = _run.GetFileIndex( artifact.Location, addToFilesTableIfNotPresent: true, dataToInsert: dataToInsert, encoding: encoding, hashData: hashData); } } var invocation = Invocation.Create( emitMachineEnvironment: dataToInsert.HasFlag(OptionallyEmittedData.EnvironmentVariables), emitTimestamps: !dataToRemove.HasFlag(OptionallyEmittedData.NondeterministicProperties), invocationPropertiesToLog); // TODO we should actually redact across the complete log file context // by a dedicated rewriting visitor or some other approach. if (invocationTokensToRedact != null) { invocation.CommandLine = Redact(invocation.CommandLine, invocationTokensToRedact); invocation.Machine = Redact(invocation.Machine, invocationTokensToRedact); invocation.Account = Redact(invocation.Account, invocationTokensToRedact); if (invocation.WorkingDirectory != null) { invocation.WorkingDirectory.Uri = Redact(invocation.WorkingDirectory.Uri, invocationTokensToRedact); } if (invocation.EnvironmentVariables != null) { string[] keys = invocation.EnvironmentVariables.Keys.ToArray(); foreach (string key in keys) { string value = invocation.EnvironmentVariables[key]; invocation.EnvironmentVariables[key] = Redact(value, invocationTokensToRedact); } } } _run.Invocations.Add(invocation); }
private bool TryGetActiveProcess(string fusionId, out IFusionProcess process) { process = default(IFusionProcess); return(processes?.TryGetValue(fusionId, out process) == true); }
public static async Task <(Stack Stack, bool Success)> TrackStackUpdateAsync( this IAmazonCloudFormation cfClient, string stackName, string mostRecentStackEventId, IDictionary <string, string> resourceNameMappings = null, IDictionary <string, string> typeNameMappings = null, Action <string, Exception> logError = null ) { var seenEventIds = new HashSet <string>(); var foundMostRecentStackEvent = (mostRecentStackEventId == null); var request = new DescribeStackEventsRequest { StackName = stackName }; var eventList = new List <StackEvent>(); var ansiLinesPrinted = 0; // iterate as long as the stack is being created/updated var active = true; var success = false; while (active) { await Task.Delay(TimeSpan.FromSeconds(3)); // fetch as many events as possible for the current stack var events = new List <StackEvent>(); try { var response = await cfClient.DescribeStackEventsAsync(request); events.AddRange(response.StackEvents); } catch (System.Net.Http.HttpRequestException e) when((e.InnerException is System.Net.Sockets.SocketException) && (e.InnerException.Message == "No such host is known")) { // ignore network issues and just try again continue; } events.Reverse(); // skip any events that preceded the most recent event before the stack update operation while (!foundMostRecentStackEvent && events.Any()) { var evt = events.First(); if (evt.EventId == mostRecentStackEventId) { foundMostRecentStackEvent = true; } seenEventIds.Add(evt.EventId); events.RemoveAt(0); } if (!foundMostRecentStackEvent) { throw new ApplicationException($"unable to find starting event for stack: {stackName}"); } // report only on new events foreach (var evt in events.Where(evt => !seenEventIds.Contains(evt.EventId))) { UpdateEvent(evt); if (!seenEventIds.Add(evt.EventId)) { // we found an event we already saw in the past, no point in looking at more events break; } if (IsFinalStackEvent(evt) && (evt.LogicalResourceId == stackName)) { // event signals stack creation/update completion; time to stop active = false; success = IsSuccessfulFinalStackEvent(evt); break; } } RenderEvents(); } // describe stack and report any output values var description = await cfClient.DescribeStacksAsync(new DescribeStacksRequest { StackName = stackName }); return(Stack : description.Stacks.FirstOrDefault(), Success : success); // local function string TranslateLogicalIdToFullName(string logicalId) { var fullName = logicalId; resourceNameMappings?.TryGetValue(logicalId, out fullName); return(fullName ?? logicalId); } string TranslateResourceTypeToFullName(string awsType) { var fullName = awsType; typeNameMappings?.TryGetValue(awsType, out fullName); return(fullName ?? awsType); } void RenderEvents() { if (Settings.UseAnsiConsole) { if (ansiLinesPrinted > 0) { Console.Write(AnsiTerminal.MoveLineUp(ansiLinesPrinted)); } var maxResourceStatusLength = eventList.Any() ? eventList.Max(evt => evt.ResourceStatus.ToString().Length) : 0; var maxResourceTypeNameLength = eventList.Any() ? eventList.Max(evt => TranslateResourceTypeToFullName(evt.ResourceType).Length) : 0; foreach (var evt in eventList) { var resourceStatus = evt.ResourceStatus.ToString(); var resourceType = TranslateResourceTypeToFullName(evt.ResourceType); if (_ansiStatusColorCodes.TryGetValue(evt.ResourceStatus, out var ansiColor)) { // print resource status Console.Write(ansiColor); Console.Write(resourceStatus); Console.Write(AnsiTerminal.Reset); Console.Write("".PadRight(maxResourceStatusLength - resourceStatus.Length + 4)); // print resource type Console.Write(resourceType); Console.Write("".PadRight(maxResourceTypeNameLength - resourceType.Length + 4)); // print resource name Console.Write(TranslateLogicalIdToFullName(evt.LogicalResourceId)); // print status reason if ((logError == null) && (evt.ResourceStatusReason != null)) { Console.Write($" ({evt.ResourceStatusReason})"); } } else { Console.Write($"{resourceStatus} {resourceType} {TranslateLogicalIdToFullName(evt.LogicalResourceId)}{(evt.ResourceStatusReason != null ? $" ({evt.ResourceStatusReason})" : "")}"); } Console.Write(AnsiTerminal.ClearEndOfLine); Console.WriteLine(); } ansiLinesPrinted = eventList.Count; } } void UpdateEvent(StackEvent evt) { if (Settings.UseAnsiConsole) { var index = eventList.FindIndex(e => e.LogicalResourceId == evt.LogicalResourceId); if (index < 0) { eventList.Add(evt); } else { eventList[index] = evt; } } else { Console.WriteLine($"{evt.ResourceStatus,-35} {TranslateResourceTypeToFullName(evt.ResourceType),-55} {TranslateLogicalIdToFullName(evt.LogicalResourceId)}{(evt.ResourceStatusReason != null ? $" ({evt.ResourceStatusReason})" : "")}"); } // capture failed operation as an error switch (evt.ResourceStatus) { case "CREATE_FAILED": case "ROLLBACK_FAILED": case "UPDATE_FAILED": case "DELETE_FAILED": case "UPDATE_ROLLBACK_FAILED": if (evt.ResourceStatusReason != "Resource creation cancelled") { logError?.Invoke($"{evt.ResourceStatus} {TranslateLogicalIdToFullName(evt.LogicalResourceId)} [{TranslateResourceTypeToFullName(evt.ResourceType)}]: {evt.ResourceStatusReason}", /*Exception*/ null); } break; } } }
/// <summary> /// /// </summary> /// <param name="message"></param> /// <returns></returns> /// <exception cref="BadRequestRestException"></exception> /// <exception cref="InsufficientCreditsRestException"></exception> /// <exception cref="HttpRequestException">The request failed due to an underlying issue such as network connectivity, DNS failure, server certificate validation or timeout.</exception> public static async Task <HttpResponseMessage> EnsureSuccessAsync(this HttpResponseMessage message) { if (!message.IsSuccessStatusCode) { try { IDictionary <string, object> additionalDetails = null; string serviceMessage = null; var resultContent = await message.Content.ReadAsStringAsync(); try { var errorDetail = resultContent != null ? JsonConvert.DeserializeObject <IDictionary <string, object> >(resultContent) : null; if (errorDetail?.ContainsKey("message") == true) { serviceMessage = errorDetail["message"].ToString(); } if (errorDetail?.ContainsKey("additional_details") == true && errorDetail["additional_details"] != null) { additionalDetails = JsonConvert.DeserializeObject <IDictionary <string, object> >( errorDetail["additional_details"] .ToString()); } } catch (JsonException) { // response did not contain valid Json serviceMessage = resultContent; } // assume bad request equates to invalid data provided by the end user switch (message.StatusCode) { case HttpStatusCode.BadRequest: throw new BadRequestRestException(serviceMessage, message, additionalDetails); case HttpStatusCode.Forbidden: object reason = null; if (additionalDetails?.TryGetValue("reason", out reason) == true && (reason as string)?.Equals("Billing: credit balance", StringComparison.OrdinalIgnoreCase) == true) { throw new InsufficientCreditsRestException(serviceMessage, message, additionalDetails); } break; } throw new RestException( serviceMessage ?? $"Failed request with status code {message.StatusCode} reason {message.ReasonPhrase}", message, additionalDetails); } finally { message.Content?.Dispose(); } } return(message); }