/// <summary> /// Diagnostics the specified base URL. /// </summary> /// <param name="baseUrl">The base URL.</param> /// <param name="paths">The paths.</param> /// <returns></returns> public static Dictionary<string, bool> Diagnostic(string baseUrl, params string[] paths) { Dictionary<string, bool> result = new Dictionary<string, bool>(); if (!string.IsNullOrWhiteSpace(baseUrl) && paths.HasItem()) { Parallel.ForEach(paths, (path) => { var httpRequest = string.Format("{0}/{1}", baseUrl.TrimEnd(' ', '/'), path.TrimStart('/', ' ')).CreateHttpWebRequest(); try { var response = httpRequest.GetResponse(); var length = response.ContentLength; result.Merge(httpRequest.RequestUri.ToString(), true); } catch { result.Merge(httpRequest.RequestUri.ToString(), false); } }); } return result; }
private Dictionary<ApiDocumentationAttribute, Type> GetApiDocumentationAttributesAndReturnTypes( Type controllerType ) { var result = new Dictionary<ApiDocumentationAttribute, Type>(); var methods = GetControllerMethods( controllerType ); var methodAttributesAndReturnTypes = GetMethodsAttributesAndReturnTypes( methods ); var classAttributesAndReturnTypes = GetClassAttributesAndReturnTypes( controllerType ); result.Merge( methodAttributesAndReturnTypes ); result.Merge( classAttributesAndReturnTypes ); return result; }
public static ICode V(ICode ast) { var ctx = ast.Ctx; var blockInfo = VisitorSubstituteIrreducable.FindSuitableBlocks.GetInfo(ast); var bInfo = blockInfo.Select(x => new { toCount = VisitorContToCounter.GetCount(x.Key, ast), ast = x.Key, codeCount = x.Value.numICodes, }).ToArray(); var block = bInfo.Where(x => x.toCount >= 2).OrderBy(x => x.toCount * x.codeCount).FirstOrDefault(); if (block == null) { return ast; } var phis = new Dictionary<Expr,Expr>(); var blockCopies = Enumerable.Range(0, block.toCount - 1) .Select(x => { var v = new VisitorDuplicateCode(); var ret = v.Visit(block.ast); phis = phis.Merge(v.phiMap, (a, b) => new ExprVarPhi(ctx) { Exprs = new[] { a, b } }); return ret; }) .Concat(block.ast) .ToArray(); var contTos = VisitorFindContinuationsRecursive.Get(ast).Where(x => x.To == block.ast).ToArray(); for (int i = 0; i < contTos.Length; i++) { var contTo = contTos[i]; var blockCopy = blockCopies[i]; ast = VisitorReplace.V(ast, contTo, blockCopy); } ast = VisitorReplaceExprUse.V(ast, phis); return ast; }
public void MergeReturnsSourceIfDictToMergeIsNull() { var source = new Dictionary<string, string> { { "key", "value" } }; var candidate = source.Merge(null); Assert.IsNotNull(candidate); Assert.AreSame(source, candidate); }
/// <summary> /// Gets the API contracts. /// </summary> /// <returns>RemoteInvokeResult.</returns> public SandboxMarshalInvokeResult GetApiContracts() { SandboxMarshalInvokeResult result = new SandboxMarshalInvokeResult(); try { Dictionary<string, string> interfaces = new Dictionary<string, string>(); foreach (var one in EnvironmentCore.DescendingAssemblyDependencyChain) { foreach (var item in one.GetTypes()) { if (item.IsInterface && item.HasAttribute<ApiContractAttribute>() && !item.IsGenericTypeDefinition) { interfaces.Merge(item.GetFullName(), item.Name, false); } } } result.SetValue(interfaces); } catch (Exception ex) { result.SetException(ex.Handle()); } return result; }
public IDictionary<string, object> ForScope(string path) { IDictionary<string, object> result = new Dictionary<string, object>(); if (path == null) return result; if (path.Length > 0) { result = result.Merge(ForScope(Path.GetDirectoryName(path))); } if (_scopedValues.ContainsKey(path)) { result = result.Merge(_scopedValues[path]); } return result; }
public void Merge_with_object_should_add_specified_items() { IDictionary<string, object> target = new Dictionary<string, object>(); target.Merge(new { foo = "bar" }); Assert.Equal("bar", target["foo"]); }
public void Merge_with_object_should_not_replace_the_existing_items() { IDictionary<string, object> target = new Dictionary<string, object> { { "foo", "bar" } }; target.Merge(new { foo = "bar2" }, false); Assert.Equal("bar", target["foo"]); }
public void DuplicatesAreNotOverwrittenByDefault() { var source = new Dictionary<string, string> { { "key", "value" } }; var candidate = source.Merge(new Dictionary<string, string> { { "key", "value2" } }); Assert.IsNotNull(candidate); Assert.AreEqual(1, candidate.Count); Assert.AreEqual("value", candidate["key"]); }
public void DuplicatesOverwriteIfSpecified() { var source = new Dictionary<string, string> { { "key", "value" } }; var candidate = source.Merge(new Dictionary<string, string> { { "key", "value2" } }, true); Assert.IsNotNull(candidate); Assert.AreEqual(1, candidate.Count); Assert.AreEqual("value2", candidate["key"]); }
public void Should_be_able_to_merge_item() { IDictionary<string, object> target = new Dictionary<string, object>(); target.Merge("key", "value", true); Assert.True(target.ContainsKey("key")); }
/// <summary> /// Sets the Discover operation using anonymous object. /// </summary> public PivotCustomDataSourceTransportBuilder Discover(object settings) { var json = new Dictionary<string, object>(); json.Merge(settings); transport.CustomDiscover = json; return this; }
public static void LogWarning(Exception ex, Dictionary<string, string> attributes = null) { var attr = attributes.Merge(new Dictionary<string, string> { {"Exception", ex.Message}, {"Stack", ex.StackTrace} }); Session.TagEvent("Warning", attr); }
public void DictionariesAreMerged() { var source = new Dictionary<string, string> { { "key", "value" } }; var candidate = source.Merge(new Dictionary<string, string> { { "key2", "value2" } }); Assert.IsNotNull(candidate); Assert.AreEqual(2, candidate.Count); Assert.AreEqual("value", candidate["key"]); Assert.AreEqual("value2", candidate["key2"]); }
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) { var attributeRoute = (IAttributeRoute)route; var allDefaults = new Dictionary<string, object>(); allDefaults.Merge(attributeRoute.Defaults); allDefaults.Merge(attributeRoute.QueryStringDefaults); // If the param is optional and has no value, then pass the constraint if (allDefaults.ContainsKey(parameterName) && allDefaults[parameterName] == UrlParameter.Optional) { if (values[parameterName].HasNoValue()) { return true; } } return _constraint.Match(httpContext, route, parameterName, values, routeDirection); }
public Dictionary<string, ApiDocModel> GetControllerModels( Type controllerType ) { var result = new Dictionary<String, ApiDocModel>(); foreach ( var apiDocumentationAttributesAndReturnType in GetApiDocumentationAttributesAndReturnTypes( controllerType ) ) { result.Merge( _modelsGenerator.GetModels( apiDocumentationAttributesAndReturnType.Key.ReturnType ?? apiDocumentationAttributesAndReturnType.Value ) ); } return result; }
public void Merge_DoesNothingIfObjectToMergeIsNull() { var dict1 = new Dictionary<int, string>(); dict1.Add(1, "One"); dict1.Add(2, "Two"); Dictionary<int, string> nullDict = null; dict1.Merge(nullDict); Assert.That(dict1.Count, Is.EqualTo(2)); }
public void Merge_with_null_returns_copy_of_first() { var first = new Dictionary<string, string> { { "A", "a-first" }, { "B", "b-first" }, }; var merged = first.Merge(null); Assert.NotSame(merged, first); Assert.Equal(2, merged.Count); Assert.Equal("a-first", merged["A"]); Assert.Equal("b-first", merged["B"]); }
public Operation ApiDescriptionToOperation(ApiDescription apiDescription, Dictionary<string, DataType> complexModels) { var apiPath = apiDescription.RelativePathSansQueryString(); var parameters = apiDescription.ParameterDescriptions .Select(paramDesc => CreateParameter(paramDesc, apiPath, complexModels)) .ToList(); var operation = new Operation { Method = apiDescription.HttpMethod.Method, Nickname = apiDescription.Nickname(), Summary = apiDescription.Documentation, Parameters = parameters, ResponseMessages = new List<ResponseMessage>() }; var responseType = apiDescription.ActualResponseType(); if (responseType == null) { operation.Type = "void"; } else { IDictionary<string, DataType> complexModelsForResponseType; var dataType = _dataTypeGenerator.TypeToDataType(responseType, out complexModelsForResponseType); complexModels.Merge(complexModelsForResponseType); if (dataType.Type == "object") { operation.Type = dataType.Id; } else { operation.Type = dataType.Type; operation.Format = dataType.Format; operation.Items = dataType.Items; operation.Enum = dataType.Enum; } } foreach (var filter in _operationFilters) { filter.Apply(operation, complexModels, _dataTypeGenerator, apiDescription); } return operation; }
public void Merge_ReplacingExistingValues() { var dict1 = new Dictionary<int, string>(); dict1.Add(1, "One"); dict1.Add(2, "Two"); var dict2 = new Dictionary<int, string>(); dict1.Add(2, "Two New"); dict1.Add(3, "Three"); dict1.Merge(dict2, true); Assert.That(dict1.Count, Is.EqualTo(3)); Assert.That(dict1[1], Is.EqualTo("One")); Assert.That(dict1[2], Is.EqualTo("Two New")); Assert.That(dict1[3], Is.EqualTo("Three")); }
public void Merge_two_dictionaries_returns_new_merged_dictionary() { var first = new Dictionary<string, string> { { "A", "a-first" }, { "B", "b-first" }, }; var second = new Dictionary<string, string> { { "A", "a-second" }, { "C", "c-second" }, }; var merged = first.Merge(second); Assert.Equal(3, merged.Count); Assert.Equal("a-second", merged["A"]); Assert.Equal("b-first", merged["B"]); Assert.Equal("c-second", merged["C"]); }
private void ProcessType( Type type, Dictionary<string, ApiDocModel> apiDocModels ) { foreach ( var property in type.GetProperties() ) { var propertyType = property.PropertyType; var modelProperty = DefaultModelProperty( property ); if ( IsAList( propertyType ) ) { propertyType = GetGenericArgument( propertyType, 0 ); modelProperty = GetArrayModelProperty( propertyType ); } else if ( IsArray( propertyType ) ) { propertyType = propertyType.GetElementType(); modelProperty = GetArrayModelProperty( propertyType ); } else if ( IsDictionary( propertyType ) ) { var key = GetGenericArgument( propertyType, 0 ); var value = GetGenericArgument( propertyType, 1 ); GetNonPrimitiveModels( key, apiDocModels ); GetNonPrimitiveModels( value, apiDocModels ); apiDocModels.Merge( GetKeyValuePairModel( key, value ) ); modelProperty = GetArrayModelProperty( typeof( KeyValuePair<,> ) ); } GetNonPrimitiveModels( propertyType, apiDocModels ); apiDocModels.First().Value.properties.Add( property.Name, modelProperty ); if ( property.GetCustomAttributes( typeof( OptionalAttribute ), true ).Length == 0 ) apiDocModels.First().Value.required.Add( property.Name ); } }
public void Merge_Test() { var from = new Dictionary<string, string>(); var to = new Dictionary<string, string>(); from["existing"] = "existing"; from["overwrite"] = "success"; to["new"] = "new"; to["overwrite"] = "failure"; to.Merge(from); //merge success? Assert.AreEqual(3, to.Keys.Count); Assert.AreEqual("existing", to["existing"]); Assert.AreEqual("new", to["new"]); Assert.AreEqual("success", to["overwrite"]); //ensure from not modified Assert.AreEqual(2, from.Keys.Count); Assert.AreEqual("existing", from["existing"]); Assert.AreEqual("success", from["overwrite"]); }
/// <summary> /// Initializes the type of the API. /// </summary> /// <param name="doneInterfaceTypes">The done interface types.</param> /// <param name="routes">The routes.</param> /// <param name="interfaceType">Type of the interface.</param> /// <param name="instance">The instance.</param> /// <param name="settings">The settings.</param> /// <param name="parentApiContractAttribute">The parent API class attribute.</param> /// <param name="parentApiModuleAttribute">The parent API module attribute.</param> protected void InitializeApiType(List<string> doneInterfaceTypes, Dictionary<string, RuntimeRoute> routes, Type interfaceType, object instance, RestApiSettings settings = null, ApiContractAttribute parentApiContractAttribute = null, ApiModuleAttribute parentApiModuleAttribute = null) { if (routes != null && interfaceType != null && doneInterfaceTypes != null) { if (doneInterfaceTypes.Contains(interfaceType.FullName)) { return; } var ApiContract = parentApiContractAttribute ?? interfaceType.GetCustomAttribute<ApiContractAttribute>(true); var apiModule = parentApiModuleAttribute ?? interfaceType.GetCustomAttribute<ApiModuleAttribute>(true); var moduleName = apiModule?.ToString(); if (ApiContract != null && !string.IsNullOrWhiteSpace(ApiContract.Version)) { var apiContractName = ApiContract.Name.SafeToString(interfaceType.FullName); if (ApiContract.Version.SafeToLower().Equals(BuildInFeatureVersionKeyword)) { throw new InvalidObjectException("ApiContract.Version", reason: "<buildin> cannot be used as version due to it is used internally."); } foreach (var method in interfaceType.GetMethods()) { var apiOperationAttribute = method.GetCustomAttribute<ApiOperationAttribute>(true); var apiTransportAttribute = method.GetCustomAttribute<ApiTransportAttribute>(); #region Initialize based on ApiOperation if (apiOperationAttribute != null) { var permissions = new Dictionary<string, ApiPermission>(); var additionalHeaderKeys = new HashSet<string>(); var apiPermissionAttributes = method.GetCustomAttributes<ApiPermissionAttribute>(true); if (apiPermissionAttributes != null) { foreach (var one in apiPermissionAttributes) { permissions.Merge(one.PermissionIdentifier, one.Permission); } } var headerKeyAttributes = method.GetCustomAttributes<ApiHeaderAttribute>(true); if (headerKeyAttributes != null) { foreach (var one in headerKeyAttributes) { additionalHeaderKeys.Add(one.HeaderKey); } } var routeKey = GetRouteKey(ApiContract.Version, apiOperationAttribute.ResourceName, apiOperationAttribute.HttpMethod, apiOperationAttribute.Action); RuntimeRoute runtimeRoute = null; if (apiTransportAttribute != null) { runtimeRoute = new RuntimeRoute(apiTransportAttribute); } else { var tokenRequired = method.GetCustomAttribute<TokenRequiredAttribute>(true) ?? interfaceType.GetCustomAttribute<TokenRequiredAttribute>(true); runtimeRoute = new RuntimeRoute(method, interfaceType, instance, !string.IsNullOrWhiteSpace(apiOperationAttribute.Action), tokenRequired != null && tokenRequired.TokenRequired, moduleName, apiContractName, settings, permissions, additionalHeaderKeys.ToList()); } if (routes.ContainsKey(routeKey)) { throw new DataConflictException("Route", objectIdentity: routeKey, data: new { existed = routes[routeKey].SafeToString(), newMethod = method.GetFullName(), newInterface = interfaceType.FullName }); } routes.Add(routeKey, runtimeRoute); } #endregion } foreach (var one in interfaceType.GetInterfaces()) { InitializeApiType(doneInterfaceTypes, routes, one, instance, settings, ApiContract, apiModule); } } doneInterfaceTypes.Add(interfaceType.FullName); } }
/// <summary> /// Fills the command mappings. /// </summary> /// <param name="container">The container.</param> /// <param name="staticType">Type of the static.</param> /// <param name="xmlRow">The XML row.</param> private void FillCommandMappings(Dictionary<string, MethodInfo> container, Type staticType, XElement xmlRow) { //// <Item Key="" FullName="" /> if (staticType != null && container != null && xmlRow != null) { var key = xmlRow.GetAttributeValue("Key"); var fullName = xmlRow.GetAttributeValue("FullName"); var methodInfo = staticType.GetMethod(fullName); if (methodInfo != null && methodInfo.IsStatic && !string.IsNullOrWhiteSpace(key)) { container.Merge(key, methodInfo); } } }
private void GetNonPrimitiveModels( Type propertyType, Dictionary<string, ApiDocModel> apiDocModels ) { if ( TypeShouldBeProcessed( propertyType ) && TypeHasNotAlreadyBeenProcessed( propertyType ) ) { _processedTypes.Add( propertyType ); apiDocModels.Merge( GetModels( propertyType ) ); } }
/// <summary> /// Gets the parameter key value pairs. /// </summary> /// <param name="parameterString">The parameter string.</param> /// <returns>Dictionary{System.StringSystem.String}.</returns> private Dictionary<string, string> GetParameterKeyValuePairs(string parameterString) { var result = new Dictionary<string, string>(); if (!string.IsNullOrWhiteSpace(parameterString)) { var matches = regex_ParameterExpression.Matches(parameterString); if (matches != null && matches.Count > 0) { foreach (Match match in matches) { var name = match.Result("${Name}"); var value = match.Result("${Value}"); result.Merge(name, value); } } } return result; }
/// <summary> /// Initializes the type of the API. /// </summary> /// <param name="doneInterfaceTypes">The done interface types.</param> /// <param name="routes">The routes.</param> /// <param name="interfaceType">Type of the interface.</param> /// <param name="instance">The instance.</param> /// <param name="settings">The settings.</param> /// <param name="parentApiContractAttribute">The parent API class attribute.</param> /// <param name="parentApiModuleAttribute">The parent API module attribute.</param> protected void InitializeApiType(List<string> doneInterfaceTypes, Dictionary<string, RuntimeRoute> routes, Type interfaceType, object instance, RestApiSettings settings = null, ApiContractAttribute parentApiContractAttribute = null, ApiModuleAttribute parentApiModuleAttribute = null) { if (routes != null && interfaceType != null && doneInterfaceTypes != null) { if (doneInterfaceTypes.Contains(interfaceType.FullName)) { return; } var apiContract = parentApiContractAttribute ?? interfaceType.GetCustomAttribute<ApiContractAttribute>(true); var apiModule = parentApiModuleAttribute ?? interfaceType.GetCustomAttribute<ApiModuleAttribute>(true); var moduleName = apiModule?.ToString(); if (apiContract != null && !string.IsNullOrWhiteSpace(apiContract.Version)) { if (apiContract.Version.SafeToLower().Equals(BuiltInFeatureVersionKeyword)) { throw ExceptionFactory.CreateInvalidObjectException("apiContract.Version", reason: "<builtin> cannot be used as version due to it is used internally."); } foreach (var method in interfaceType.GetMethods()) { var apiOperationAttribute = method.GetCustomAttribute<ApiOperationAttribute>(true); #region Initialize based on ApiOperation if (apiOperationAttribute != null) { var permissions = new Dictionary<string, ApiPermission>(); var additionalHeaderKeys = new HashSet<string>(); var apiPermissionAttributes = method.GetCustomAttributes<ApiPermissionAttribute>(true); if (apiPermissionAttributes != null) { foreach (var one in apiPermissionAttributes) { permissions.Merge(one.PermissionIdentifier, one.Permission); } } var headerKeyAttributes = method.GetCustomAttributes<ApiHeaderAttribute>(true); if (headerKeyAttributes != null) { foreach (var one in headerKeyAttributes) { additionalHeaderKeys.Add(one.HeaderKey); } } var routeKey = GetRouteKey(apiContract.Version, apiOperationAttribute.ResourceName, apiOperationAttribute.HttpMethod, apiOperationAttribute.Action); var tokenRequired = method.GetCustomAttribute<TokenRequiredAttribute>(true) ?? interfaceType.GetCustomAttribute<TokenRequiredAttribute>(true); var runtimeRoute = new RuntimeRoute(method, interfaceType, instance, !string.IsNullOrWhiteSpace(apiOperationAttribute.Action), tokenRequired != null && tokenRequired.TokenRequired, moduleName, settings, permissions, additionalHeaderKeys.ToList()); if (routes.ContainsKey(routeKey)) { throw new DataConflictException("Route", objectIdentity: routeKey, data: new { existed = routes[routeKey].SafeToString(), newMethod = method.GetFullName(), newInterface = interfaceType.FullName }); } routes.Add(routeKey, runtimeRoute); } #endregion } foreach (var one in interfaceType.GetInterfaces()) { InitializeApiType(doneInterfaceTypes, routes, one, instance, settings, apiContract, apiModule); } //Special NOTE: // Move this add action in scope of if apiContract is valid. // Reason: in complicated cases, when [A:Interface1] without ApiContract, but [Interface2: Interface] with defining ApiContract, and [B: A, Interface2], then correct contract definition might be missed. doneInterfaceTypes.Add(interfaceType.FullName); } } }
static Dictionary<string, string> LoadImagesMap(string linkTemplate) { var grabber = new Grabber(); var images = new Dictionary<string, string>(); for (var i = 1; i <= 13; i++) images = images.Merge(grabber.GetImages(string.Format("{0}{1}", linkTemplate, i))); return images; }
private Parameter CreateParameter(ApiParameterDescription apiParamDesc, string apiPath, Dictionary<string, DataType> complexModels) { var paramType = ""; switch (apiParamDesc.Source) { case ApiParameterSource.FromBody: paramType = "body"; break; case ApiParameterSource.FromUri: paramType = apiPath.Contains(String.Format("{{{0}}}", apiParamDesc.Name)) ? "path" : "query"; break; } var parameter = new Parameter { ParamType = paramType, Name = apiParamDesc.Name, Description = apiParamDesc.Documentation, Required = !apiParamDesc.ParameterDescriptor.IsOptional }; IDictionary<string, DataType> complexModelsForParameter; var dataType = _dataTypeGenerator.TypeToDataType(apiParamDesc.ParameterDescriptor.ParameterType, out complexModelsForParameter); complexModels.Merge(complexModelsForParameter); if (dataType.Type == "object") { parameter.Type = dataType.Id; } else { parameter.Type = dataType.Type; parameter.Format = dataType.Format; parameter.Items = dataType.Items; parameter.Enum = dataType.Enum; } return parameter; }