Ejemplo n.º 1
0
        public bool TryGetAssembly(string name, FrameworkName targetFramework, out string path, out Version version)
        {
            path    = null;
            version = null;

            var information = _cache.GetOrAdd(targetFramework, GetFrameworkInformation);

            if (information == null || !information.Exists)
            {
                return(false);
            }

            lock (information.Assemblies)
            {
                AssemblyEntry entry;
                if (information.Assemblies.TryGetValue(name, out entry))
                {
                    if (string.IsNullOrEmpty(entry.Path))
                    {
                        entry.Path = GetAssemblyPath(information.Path, name);
                    }

                    if (!string.IsNullOrEmpty(entry.Path) && entry.Version == null)
                    {
                        // This code path should only run on mono
                        entry.Version = VersionUtility.GetAssemblyVersion(entry.Path).Version;
                    }

                    path    = entry.Path;
                    version = entry.Version;
                }
            }

            return(!string.IsNullOrEmpty(path));
        }
Ejemplo n.º 2
0
        /// <summary>
        /// 设置mqtt服务路由。
        /// </summary>
        /// <param name="routes">服务路由集合。</param>
        /// <returns>一个任务。</returns>
        protected override async Task SetRoutesAsync(IEnumerable <MqttServiceDescriptor> routes)
        {
            if (_logger.IsEnabled(LogLevel.Information))
            {
                _logger.LogInformation("准备添加mqtt服务路由。");
            }
            var zooKeeperClients = await _zookeeperClientProvider.GetZooKeeperClients();

            foreach (var zooKeeperClient in zooKeeperClients)
            {
                await CreateSubdirectory(zooKeeperClient, _configInfo.MqttRoutePath);

                var path = _configInfo.MqttRoutePath;

                routes = routes.ToArray();

                foreach (var serviceRoute in routes)
                {
                    var nodePath = $"{path}{serviceRoute.MqttDescriptor.Topic}";
                    var nodeData = _serializer.Serialize(serviceRoute);

                    using (var locker = await _lockerProvider.CreateLockAsync(nodePath))
                    {
                        await locker.Lock(async() => {
                            if (!nodeWatchers.ContainsKey(nodePath))
                            {
                                var nodeWathcher = nodeWatchers.GetOrAdd(nodePath, f => new NodeMonitorWatcher(path, async(oldData, newData) => await NodeChange(oldData, newData)));
                                await zooKeeperClient.SubscribeDataChange(nodePath, nodeWathcher.HandleNodeDataChange);
                            }

                            if (!await zooKeeperClient.ExistsAsync(nodePath))
                            {
                                if (_logger.IsEnabled(LogLevel.Debug))
                                {
                                    _logger.LogDebug($"节点:{nodePath}不存在将进行创建。");
                                }
                                await zooKeeperClient.CreateAsync(nodePath, nodeData, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
                            }
                            else
                            {
                                if (_logger.IsEnabled(LogLevel.Debug))
                                {
                                    _logger.LogDebug($"将更新节点:{nodePath}的数据。");
                                }
                                var onlineData = (await zooKeeperClient.GetDataAsync(nodePath)).ToArray();
                                if (!DataEquals(nodeData, onlineData))
                                {
                                    await zooKeeperClient.SetDataAsync(nodePath, nodeData);
                                }
                            }
                        });
                    }
                }
                if (_logger.IsEnabled(LogLevel.Information))
                {
                    _logger.LogInformation("mqtt服务路由添加成功。");
                }
            }
        }
        public TAnalyzable Get <TAnalyzable>(params object[] parameters) where TAnalyzable : IAnalyzable
        {
            var cacheKey = $"{typeof(TAnalyzable).Name}#{string.Join("|", parameters)}";

            IAnalyzable analyzable() => AnalyzableFactory.CreateAnalyzable <TAnalyzable, TInput>(BackingList, parameters);

            return((TAnalyzable)_cache.GetOrAdd(cacheKey, analyzable));
        }
Ejemplo n.º 4
0
        public override async Task SetCachesAsync(IEnumerable <ServiceCacheDescriptor> cacheDescriptors)
        {
            if (_logger.IsEnabled(LogLevel.Information))
            {
                _logger.LogInformation("准备添加服务命令。");
            }
            var path             = _configInfo.CachePath;
            var zooKeeperClients = await _zookeeperClientProvider.GetZooKeeperClients();

            foreach (var zooKeeperClient in zooKeeperClients)
            {
                await CreateSubdirectory(zooKeeperClient, _configInfo.CachePath);

                if (!path.EndsWith("/"))
                {
                    path += "/";
                }

                cacheDescriptors = cacheDescriptors.ToArray();

                foreach (var cacheDescriptor in cacheDescriptors)
                {
                    var nodePath = $"{path}{cacheDescriptor.CacheDescriptor.Id}";
                    var nodeData = _serializer.Serialize(cacheDescriptor);
                    var watcher  = nodeWatchers.GetOrAdd(nodePath, f => new NodeMonitorWatcher(path, async(oldData, newData) => await NodeChange(oldData, newData)));
                    await zooKeeperClient.SubscribeDataChange(nodePath, watcher.HandleNodeDataChange);

                    if (!await zooKeeperClient.ExistsAsync(nodePath))
                    {
                        if (_logger.IsEnabled(LogLevel.Debug))
                        {
                            _logger.LogDebug($"节点:{nodePath}不存在将进行创建。");
                        }

                        await zooKeeperClient.CreateAsync(nodePath, nodeData, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
                    }
                    else
                    {
                        if (_logger.IsEnabled(LogLevel.Debug))
                        {
                            _logger.LogDebug($"将更新节点:{nodePath}的数据。");
                        }

                        var onlineData = (await zooKeeperClient.GetDataAsync(nodePath)).ToArray();
                        if (!DataEquals(nodeData, onlineData))
                        {
                            await zooKeeperClient.SetDataAsync(nodePath, nodeData);
                        }
                    }
                }
                if (_logger.IsEnabled(LogLevel.Information))
                {
                    _logger.LogInformation("服务缓存添加成功。");
                }
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// 设置服务命令。
        /// </summary>
        /// <param name="routes">服务命令集合。</param>
        /// <returns>一个任务。</returns>
        public override async Task SetServiceCommandsAsync(IEnumerable <ServiceCommandDescriptor> serviceCommands)
        {
            var zooKeeperClients = await _zookeeperClientProvider.GetZooKeeperClients();

            foreach (var zooKeeperClient in zooKeeperClients)
            {
                _logger.LogInformation($"准备向服务注册中心{zooKeeperClient.Options.ConnectionString}添加服务命令。");
                await CreateSubdirectory(zooKeeperClient, _configInfo.CommandPath);

                var path = _configInfo.CommandPath;
                if (!path.EndsWith("/"))
                {
                    path += "/";
                }

                serviceCommands = serviceCommands.ToArray();
                var addCount   = 0;
                var exsitCount = 0;
                foreach (var command in serviceCommands)
                {
                    var nodePath = $"{path}{command.ServiceId}";
                    var nodeData = _serializer.Serialize(command);
                    if (!nodeWatchers.ContainsKey(nodePath))
                    {
                        var watcher = nodeWatchers.GetOrAdd(nodePath, f => new NodeMonitorWatcher(path, async(oldData, newData) => await NodeChange(oldData, newData)));
                        await zooKeeperClient.SubscribeDataChange(nodePath, watcher.HandleNodeDataChange);
                    }

                    if (!await zooKeeperClient.ExistsAsync(nodePath))
                    {
                        _logger.LogDebug($"节点:{nodePath}不存在将进行创建。");
                        await zooKeeperClient.CreateAsync(nodePath, nodeData, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);

                        addCount++;
                    }
                    else
                    {
                        _logger.LogDebug($"将更新节点:{nodePath}的数据。");
                        var onlineData = (await zooKeeperClient.GetDataAsync(nodePath)).ToArray();
                        if (!DataEquals(nodeData, onlineData))
                        {
                            await zooKeeperClient.SetDataAsync(nodePath, nodeData);

                            addCount++;
                        }
                        else
                        {
                            exsitCount++;
                        }
                    }
                    NodeChange(command);
                }
                _logger.LogInformation($"共发现{serviceCommands.Count()}个服务命令,其中,成功向服务注册中心添加{addCount}个,服务注册中心已经存在{exsitCount}个");
            }
        }
Ejemplo n.º 6
0
        public bool TryGetAssembly(string name, NuGetFramework targetFramework, out string path, out NuGetVersion version)
        {
            path    = null;
            version = null;

            // Rewrite DNX framework names.
            // DNX versions match 1:1 with .NET Framework versions
            if (string.Equals(targetFramework.Framework, FrameworkConstants.FrameworkIdentifiers.Dnx))
            {
                targetFramework = new NuGetFramework(
                    FrameworkConstants.FrameworkIdentifiers.Net,
                    targetFramework.Version);
            }

            var information = _cache.GetOrAdd(targetFramework, GetFrameworkInformation);

            if (information == null || !information.Exists)
            {
                Log.LogWarning($"No framework information found for {targetFramework}");
                return(false);
            }

            lock (information.Assemblies)
            {
                AssemblyEntry entry;
                if (information.Assemblies.TryGetValue(name, out entry))
                {
                    if (string.IsNullOrEmpty(entry.Path))
                    {
                        entry.Path = GetAssemblyPath(information.Path, name);
                    }

                    if (!string.IsNullOrEmpty(entry.Path) && entry.Version == null)
                    {
                        // This code path should only run on mono
                        entry.Version = AssemblyUtils.GetAssemblyVersion(entry.Path);
                    }

                    path    = entry.Path;
                    version = new NuGetVersion(entry.Version);

                    if (Log.IsEnabled(LogLevel.Verbose))
                    {
                        // Trim back the path
                        Log.LogVerbose($"Resolved {name} {version} to {path.Substring(information.Path.Length + 1)}");
                    }
                }
            }

            return(!string.IsNullOrEmpty(path));
        }
Ejemplo n.º 7
0
        protected override async Task <bool> SetRouteAsync(ServiceRouteDescriptor route)
        {
            try
            {
                _logger.LogDebug($"准备添加{route.ServiceDescriptor.Id}服务路由。");
                var zooKeeperClients = await _zookeeperClientProvider.GetZooKeeperClients();

                foreach (var zooKeeperClient in zooKeeperClients)
                {
                    await CreateSubdirectory(zooKeeperClient, _configInfo.RoutePath);

                    var path = _configInfo.RoutePath;
                    if (!path.EndsWith("/"))
                    {
                        path += "/";
                    }

                    var nodePath = $"{path}{route.ServiceDescriptor.Id}";
                    var nodeData = _serializer.Serialize(route);
                    _logger.LogDebug($"服务路由内容为:{Encoding.UTF8.GetString(nodeData)}。");
                    if (!nodeWatchers.ContainsKey(nodePath))
                    {
                        var watcher = nodeWatchers.GetOrAdd(nodePath, f => new NodeMonitorWatcher(path, async(oldData, newData) => await NodeChange(oldData, newData)));
                        await zooKeeperClient.SubscribeDataChange(nodePath, watcher.HandleNodeDataChange);
                    }
                    if (!await zooKeeperClient.ExistsAsync(nodePath))
                    {
                        _logger.LogDebug($"节点:{nodePath}不存在将进行创建。");
                        await zooKeeperClient.CreateAsync(nodePath, nodeData, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
                    }
                    else
                    {
                        var onlineData = (await zooKeeperClient.GetDataAsync(nodePath)).ToArray();
                        if (!DataEquals(nodeData, onlineData))
                        {
                            await zooKeeperClient.SetDataAsync(nodePath, nodeData);

                            _logger.LogDebug($"{nodePath}节点的缓存的服务路由与服务注册中心不一致,路由数据已被更新。");
                        }
                    }
                }

                return(true);
            }
            catch (Exception ex)
            {
                _logger.LogError($"{route.ServiceDescriptor.Id}服务的路由注册失败,原因:{ex.Message}");
                return(false);
            }
        }
Ejemplo n.º 8
0
        internal FormatterExpression GetProfile(string profileName)
        {
            FormatterExpression expr = _formatterProfiles.GetOrAdd(profileName,
                                                                   name => new FormatterExpression(t => (IValueFormatter)_serviceCtor(t)));

            return(expr);
        }
Ejemplo n.º 9
0
 public static object ToArrayOfType(this IEnumerable <object> enumerable, Type collectionType)
 {
     return(_toArrayMethods.GetOrAdd(collectionType, () => _toArrayMethod.MakeGenericMethod(collectionType))
            .Invoke(null, new[] {
         enumerable.CastToIEnumerableOfType(collectionType)
     }));
 }
Ejemplo n.º 10
0
        public LateBoundCtor CreateCtor(Type type)
        {
            LateBoundCtor ctor = _ctorCache.GetOrAdd(type, t =>
            {
                //handle valuetypes
                if (!type.IsClass)
                {
                    var ctorExpression = Expression.Lambda <LateBoundCtor>(Expression.Convert(Expression.New(type), typeof(object)));
                    return(ctorExpression.Compile());
                }
                else
                {
                    var constructors = type.GetConstructors(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);

                    //find a ctor with only optional args
                    var ctorWithOptionalArgs = constructors.FirstOrDefault(c => c.GetParameters().All(p => p.IsOptional));
                    if (ctorWithOptionalArgs == null)
                    {
                        throw new ArgumentException("Type needs to have a constructor with 0 args or only optional args", "type");
                    }

                    //get all optional default values
                    var args = ctorWithOptionalArgs
                               .GetParameters()
                               .Select(p => Expression.Constant(p.DefaultValue, p.ParameterType)).ToArray();

                    //create the ctor expression
                    var ctorExpression = Expression.Lambda <LateBoundCtor>(Expression.Convert(Expression.New(ctorWithOptionalArgs, args), typeof(object)));
                    return(ctorExpression.Compile());
                }
            });

            return(ctor);
        }
Ejemplo n.º 11
0
        private async Task OnEventAppearead(IStreamSubscription arg1,
                                            ResolvedEvent arg2,
                                            IDictionary <string, Func <IStreamSubscription, ResolvedEvent, CancellationToken, Task> > methods,
                                            IDictionary <string, Type> handlers,
                                            IDictionary <string, Type> eventToTypeDict,
                                            CancellationToken arg3)
        {
            var eventType = arg2.Event.EventType;
            var func      = methods.GetOrAdd(eventType, key =>
            {
                var p1 = Expression.Parameter(typeof(IStreamSubscription), "arg1");
                var p2 = Expression.Parameter(typeof(ResolvedEvent), "arg2");
                var p3 = Expression.Parameter(typeof(CancellationToken), "arg3");

                var t  = Expression.Constant(this);
                var et = eventToTypeDict[key];
                var h  = handlers[key];

                var c   = Expression.Call(t, _onSpecMeth.MakeGenericMethod(et, h), p1, p2, p3);
                var ret = Expression
                          .Lambda <Func <IStreamSubscription, ResolvedEvent, CancellationToken, Task> >(c, new[] { p1, p2, p3 })
                          .Compile();
                return(ret);
            });

            await func(arg1, arg2, arg3);
        }
        public static MetricsLogger GetMetricsLogger(string dimensions)
        {
            if (_instance == null)
            {
                return(new MetricsLogger("service=Dummy"));
            }

            var dimensionsMap = Dimensions.ParseDimensions(dimensions);

            if (!dimensionsMap.Any())
            {
                throw new InvalidOperationException("Dimensions must be valid and non-empty");
            }

            dimensionsMap.AddOrUpdate("service", _serviceName);

            if (_environment.Length > 0)
            {
                dimensionsMap.AddOrUpdate("env", _environment);
            }

            var serializedDimensions = Dimensions.SerializeDimensionsToString(dimensionsMap);

            return(MetricsLoggers.GetOrAdd(serializedDimensions, new MetricsLogger(dimensionsMap)));
        }
Ejemplo n.º 13
0
        /// <inheritdoc />
        protected override void Execute(object sender, EventArgs e)
        {
            var dte = (DTE2)ServiceProvider.GetService(typeof(DTE));

            if (dte?.ActiveDocument.Object("TextDocument") is TextDocument textDocument)
            {
                var patterns = _patterns.GetOrAdd(textDocument.Language, CreateCommentPatterns);
                if (0 < patterns.Length)
                {
                    var text      = GetTextOfSelectedLines(textDocument.Selection);
                    var isComment = patterns.Any(x => x.IsComment(text));

                    var commandId = isComment ? VSConstants.VSStd2KCmdID.UNCOMMENT_BLOCK : VSConstants.VSStd2KCmdID.COMMENT_BLOCK;

                    ExecuteCommand(commandId);
                }
                else if (ExecuteCommand(VSConstants.VSStd2KCmdID.COMMENT_BLOCK) == false)
                {
                    ShowMessageBox(
                        "Toggle Comment is not executable.",
                        $"{textDocument.Language} files is not supported.",
                        OLEMSGICON.OLEMSGICON_INFO);
                }
            }
        }
Ejemplo n.º 14
0
 /// <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>
 /// <param name="factory">A factory method used to create the value if not found in the dictionary</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 GetOrAdd <TKey, TValue>(
     this IDictionary <TKey, TValue> dictionary,
     TKey key,
     Func <TValue> factory)
 {
     return(dictionary.GetOrAdd(key, _ => factory()));
 }
Ejemplo n.º 15
0
        public static IArgsTuple <TArg1, TArg2, TArg3, TArg4, TArg5> Create <TArg1, TArg2, TArg3, TArg4, TArg5>(TArg1 arg1, TArg2 arg2, TArg3 arg3, TArg4 arg4, TArg5 arg5)
        {
            var typesKey =
                new TypeTuple5(
                    arg1?.GetType() ?? typeof(TArg1),
                    arg2?.GetType() ?? typeof(TArg2),
                    arg3?.GetType() ?? typeof(TArg3),
                    arg4?.GetType() ?? typeof(TArg4),
                    arg5?.GetType() ?? typeof(TArg5));
            var createFunc = default(P_CreateFuncBase);

            if (!__CreateFuncsSpinLock.Invoke(() => __CreateFuncs5.TryGetValue(typesKey, out createFunc)))
            {
                createFunc = ActivationUtilities.RequireConstructor <P_CreateFuncBase>(
                    typeof(P_CreateFunc <, , , ,>)
                    .MakeGenericType(
                        typesKey.Item1,
                        typesKey.Item2,
                        typesKey.Item3,
                        typesKey.Item4,
                        typesKey.Item5))();
                createFunc =
                    __CreateFuncs5
                    .GetOrAdd(
                        spinLock: __CreateFuncsSpinLock,
                        key: typesKey,
                        factory: key => createFunc);
            }
            return(createFunc.Create(arg1, arg2, arg3, arg4, arg5));
        }
Ejemplo n.º 16
0
        public void Intercept(IInvocation invocation)
        {
            var cacheKey = GenerateCacheKey(invocation.Method.Name, invocation.Arguments);

            invocation.ReturnValue = _cache.GetOrAdd(cacheKey, () => new InvocationInfo(this, cacheKey, invocation))
                                     .ReturnValue;
        }
Ejemplo n.º 17
0
 public Icon GetIcon(string resourceName)
 {
     return(_resourceIcons.GetOrAdd(resourceName, name => {
         var image = GetImageSource(name);
         return ImageSourceToIcon(image);
     }).Value);
 }
Ejemplo n.º 18
0
        private async Task <MqttServiceRoute> GetRoute(string path)
        {
            MqttServiceRoute result = null;
            var client = await GetConsulClient();

            if (client != null)
            {
                if (!nodeWatchers.ContainsKey(path))
                {
                    var watcher = nodeWatchers.GetOrAdd(path, f => new NodeMonitorWatcher(GetConsulClient, _manager, path,
                                                                                          async(oldData, newData) => await NodeChange(oldData, newData), null));
                }

                var queryResult = await client.KV.Keys(path);

                if (queryResult.Response != null)
                {
                    var data = (await client.GetDataAsync(path));
                    if (data != null)
                    {
                        result = await GetRoute(data);
                    }
                }
            }

            return(result);
        }
        private void GetLiveProjectAndDocumentErrors(
            out IDictionary <ProjectId, IList <DiagnosticData> > projectErrors,
            out IDictionary <DocumentId, IList <DiagnosticData> > documentErrors)
        {
            projectErrors  = null;
            documentErrors = null;

            foreach (var diagnostic in _diagnosticService.GetDiagnostics(_workspace, id: null, projectId: null, documentId: null, cancellationToken: CancellationToken.None))
            {
                if (diagnostic.DocumentId != null)
                {
                    documentErrors = documentErrors ?? new Dictionary <DocumentId, IList <DiagnosticData> >();

                    var errors = documentErrors.GetOrAdd(diagnostic.DocumentId, _ => new List <DiagnosticData>());
                    errors.Add(diagnostic);
                    continue;
                }

                if (diagnostic.ProjectId != null)
                {
                    projectErrors = projectErrors ?? new Dictionary <ProjectId, IList <DiagnosticData> >();

                    var errors = projectErrors.GetOrAdd(diagnostic.ProjectId, _ => new List <DiagnosticData>());
                    errors.Add(diagnostic);
                    continue;
                }

                Contract.Requires(false, "shouldn't happen");
            }

            projectErrors  = projectErrors ?? SpecializedCollections.EmptyDictionary <ProjectId, IList <DiagnosticData> >();
            documentErrors = documentErrors ?? SpecializedCollections.EmptyDictionary <DocumentId, IList <DiagnosticData> >();
        }
Ejemplo n.º 20
0
        public static string CreateTestFile(string code, IDictionary <string, IList <TextSpan> > spans, int cursor = -1)
        {
            StringBuilder    sb             = new StringBuilder();
            IList <TextSpan> anonymousSpans = spans.GetOrAdd(string.Empty, () => new List <TextSpan>());

            for (int i = 0; i <= code.Length; i++)
            {
                if (i == cursor)
                {
                    sb.Append(PositionString);
                }

                AddSpanString(sb, spans.Where(kvp => kvp.Key != string.Empty), i, start: true);
                AddSpanString(sb, spans.Where(kvp => kvp.Key == string.Empty), i, start: true);
                AddSpanString(sb, spans.Where(kvp => kvp.Key == string.Empty), i, start: false);
                AddSpanString(sb, spans.Where(kvp => kvp.Key != string.Empty), i, start: false);

                if (i < code.Length)
                {
                    sb.Append(code[i]);
                }
            }

            return(sb.ToString());
        }
Ejemplo n.º 21
0
        /// <inheritdoc />
        protected override void Execute(object sender, EventArgs e)
        {
            var dte          = (DTE2)ServiceProvider.GetService(typeof(DTE));
            var textDocument = dte.ActiveDocument.Object("TextDocument") as TextDocument;

            if (textDocument != null)
            {
                var patterns = _patterns.GetOrAdd(textDocument.Language, CreateCommentPatterns);
                if (0 < patterns.Length)
                {
                    var selection         = textDocument.Selection;
                    var originalSelection = new Tuple <EditPoint, EditPoint>(selection.TopPoint.CreateEditPoint(), selection.BottomPoint.CreateEditPoint());
                    SelectLines(selection);
                    var text = selection.Text;

                    var isComment = patterns.Any(x => x.IsComment(text));
                    var commandId = isComment ? VSConstants.VSStd2KCmdID.UNCOMMENT_BLOCK : VSConstants.VSStd2KCmdID.COMMENT_BLOCK;

                    ExecuteCommand(commandId);
                    SetSelection(selection, originalSelection);
                }
                else if (ExecuteCommand(VSConstants.VSStd2KCmdID.COMMENT_BLOCK) == false)
                {
                    ShowMessageBox(
                        "Toggle Comment is not executable.",
                        $"{textDocument.Language} files is not supported.",
                        OLEMSGICON.OLEMSGICON_INFO);
                }
            }
        }
Ejemplo n.º 22
0
 public IPersistentCollection GetCollection(string collectionId)
 {
     PersistentObjectValidator.ValidateCollectionId(collectionId);
     return(collections.GetOrAdd(collectionId,
                                 () =>
                                 new PersistentCollection(collectionId, persistenceStrategy, serializationStrategy,
                                                          deserializationErrorHandlingStrategy)));
 }
Ejemplo n.º 23
0
 public static object CastToIEnumerableOfType(this IEnumerable <object> enumerable, Type collectionType)
 {
     lock (collectionType) {
         return(_castMethods.GetOrAdd(collectionType, () => _castMethod.MakeGenericMethod(collectionType)).Invoke(null, new object[] {
             enumerable
         }));
     }
 }
Ejemplo n.º 24
0
 public void Add(string fileName, string backupedFileHash, string dbFileHash)
 {
     files.GetOrAdd
     (
         backupedFileHash ?? string.Empty,
         () => new DbErrorFile(fileName, backupedFileHash)
     ).Add(dbFileHash);
 }
Ejemplo n.º 25
0
 public IEnumerable <IInterceptor> GetInterceptors(MethodInfo method)
 {
     if (method == null)
     {
         throw new ArgumentNullException(nameof(method));
     }
     return(interceptorCache.GetOrAdd(method, _ => RemovalMultiple(SelectInterceptors(_)).OrderBy(x => x.Order).ToArray()));
 }
Ejemplo n.º 26
0
        private DataType GetOrRegister(Type type, bool deferIfComplex, Queue <Type> deferredTypes)
        {
            if (_customMappings.ContainsKey(type))
            {
                return(_customMappings[type]());
            }

            if (PrimitiveMappings.ContainsKey(type))
            {
                return(PrimitiveMappings[type]());
            }

            if (type.IsEnum)
            {
                return new DataType {
                           Type = "string", Enum = type.GetEnumNames()
                }
            }
            ;

            Type innerType;

            if (type.IsNullable(out innerType))
            {
                return(GetOrRegister(innerType, deferIfComplex, deferredTypes));
            }

            Type itemType;

            if (type.IsEnumerable(out itemType))
            {
                if (itemType.IsEnumerable() && !PrimitiveMappings.ContainsKey(itemType))
                {
                    throw new InvalidOperationException(
                              String.Format("Type {0} is not supported. Swagger does not support containers of containers", type));
                }

                return(new DataType {
                    Type = "array", Items = GetOrRegister(itemType, true, deferredTypes)
                });
            }

            // Anthing else is complex
            if (deferIfComplex)
            {
                if (!_complexMappings.ContainsKey(type))
                {
                    deferredTypes.Enqueue(type);
                }

                // Just return a reference for now
                return(new DataType {
                    Ref = UniqueIdFor(type)
                });
            }

            return(_complexMappings.GetOrAdd(type, () => CreateComplexDataType(type, deferredTypes)));
        }
Ejemplo n.º 27
0
        object IMappingEngineRunner.Map(ResolutionContext context)
        {
            try
            {
                var contextTypePair = new TypePair(context.SourceType, context.DestinationType);

                Func <TypePair, IObjectMapper> missFunc =
                    tp => _mappers.FirstOrDefault(mapper => mapper.IsMatch(context));

                IObjectMapper mapperToUse = _objectMapperCache.GetOrAdd(contextTypePair, missFunc);

                if (mapperToUse == null)
                {
                    if (context.Options.CreateMissingTypeMaps)
                    {
                        var typeMap = ConfigurationProvider.CreateTypeMap(context.SourceType, context.DestinationType);

                        context = context.CreateTypeContext(typeMap, context.SourceValue, context.DestinationValue,
                                                            context.SourceType, context.DestinationType);

                        mapperToUse = _objectMapperCache.GetOrAdd(contextTypePair, missFunc);
                    }
                    else
                    {
                        if (context.SourceValue != null)
                        {
                            throw new AutoMapperMappingException(context,
                                                                 "Missing type map configuration or unsupported mapping.");
                        }

                        return(ObjectCreator.CreateDefaultValue(context.DestinationType));
                    }
                }

                return(mapperToUse.Map(context, this));
            }
            catch (AutoMapperMappingException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new AutoMapperMappingException(context, ex);
            }
        }
Ejemplo n.º 28
0
        public Icon GetFileExtensionIcon(string fileExtension)
        {
            var kvp = _fileExtensionImageSources.GetOrAdd(fileExtension, GetImageSourceForFileExtension);

            return(_imageSourceIdIcons.GetOrAdd(kvp.Key, kvp.Value, (key, value) => {
                Logger.LogInfo("Creating icon for resource id {0}", key);
                return ImageSourceToIcon(value);
            }).Value);
        }
Ejemplo n.º 29
0
 public ImageSource GetImageSource(string resourceName)
 {
     return(_resourceImages.GetOrAdd(resourceName, name => {
         var bitmapImage = new BitmapImage();
         bitmapImage.BeginInit();
         bitmapImage.UriSource = GetUri(string.Format("Views/Images/{0}.png", name));
         bitmapImage.EndInit();
         return bitmapImage;
     }));
 }
Ejemplo n.º 30
0
        public static object FindModel(this ModelTreeInfo tree, string path, object currentModel, IDictionary <object, object> cache)
        {
            var value = cache.GetOrAdd($"{tree.GetHashCode()}|{path}", _ => tree.FindModel(path));

            return(!(value is string) &&
                   value is IEnumerable enumerable &&
                   enumerable.Cast <object>().Contains(currentModel)
                ? currentModel
                : value);
        }
Ejemplo n.º 31
0
 /// <summary>
 /// Handles links embedded in HTTP response headers.
 /// </summary>
 /// <param name="headers">The headers to check for links.</param>
 /// <param name="links">A dictionary to add found links to.</param>
 /// <param name="linkTemplates">A dictionary to add found link templates to.</param>
 protected virtual void HandleHeaderLinks(HttpResponseHeaders headers, IDictionary<string, Dictionary<Uri, string>> links, IDictionary<string, UriTemplate> linkTemplates)
 {
     foreach (var header in headers.GetLinkHeaders().Where(x => x.Rel != null))
     {
         if (header.Templated)
             linkTemplates[header.Rel] = new UriTemplate(header.Href);
         else
             links.GetOrAdd(header.Rel)[new Uri(Uri, header.Href)] = header.Title;
     }
 }
Ejemplo n.º 32
0
        public static string CreateTestFile(string code, IDictionary<string, IList<TextSpan>> spans, int cursor = -1)
        {
            var sb = new StringBuilder();
            var anonymousSpans = spans.GetOrAdd(string.Empty, () => new List<TextSpan>());

            for (int i = 0; i <= code.Length; i++)
            {
                if (i == cursor)
                {
                    sb.Append(PositionString);
                }

                AddSpanString(sb, spans.Where(kvp => kvp.Key != string.Empty), i, start: true);
                AddSpanString(sb, spans.Where(kvp => kvp.Key == string.Empty), i, start: true);
                AddSpanString(sb, spans.Where(kvp => kvp.Key == string.Empty), i, start: false);
                AddSpanString(sb, spans.Where(kvp => kvp.Key != string.Empty), i, start: false);

                if (i < code.Length)
                {
                    sb.Append(code[i]);
                }
            }

            return sb.ToString();
        }
Ejemplo n.º 33
0
 public CommandAttribute(IDictionary<string, object> attributes)
     : this((string)attributes.GetOrAdd("PackageId", _ => Guid.Empty.ToString()), (string)attributes["GroupId"], (int)attributes["CommandId"])
 {
 }
Ejemplo n.º 34
0
        private static void PopSpan(
            Stack<Tuple<int, string>> spanStartStack,
            IDictionary<string, IList<TextSpan>> spans,
            int finalIndex)
        {
            var spanStartTuple = spanStartStack.Pop();

            var span = TextSpan.FromBounds(spanStartTuple.Item1, finalIndex);
            spans.GetOrAdd(spanStartTuple.Item2, () => new List<TextSpan>()).Add(span);
        }
Ejemplo n.º 35
0
        /// <summary>
        /// Handles links embedded in JSON response bodies.
        /// </summary>
        /// <param name="jsonBody">The body to check for links.</param>
        /// <param name="links">A dictionary to add found links to.</param>
        /// <param name="linkTemplates">A dictionary to add found link templates to.</param>
        protected virtual void HandleBodyLinks(JToken jsonBody, IDictionary<string, Dictionary<Uri, string>> links, IDictionary<string, UriTemplate> linkTemplates)
        {
            if (jsonBody.Type != JTokenType.Object) return;
            var linksNode = jsonBody["_links"] ?? jsonBody["links"];
            if (linksNode == null) return;

            foreach (var linkNode in linksNode.OfType<JProperty>())
            {
                string rel = linkNode.Name;
                var linksForRel = links.GetOrAdd(rel);

                switch (linkNode.Value.Type)
                {
                    case JTokenType.Array:
                        foreach (var subobj in linkNode.Value.OfType<JObject>())
                            ParseLinkObject(rel, subobj, linksForRel, linkTemplates);
                        break;

                    case JTokenType.Object:
                        ParseLinkObject(rel, (JObject)linkNode.Value, linksForRel, linkTemplates);
                        break;
                }
            }
        }