Esempio n. 1
0
        private IWriteHandler CheckBaseTypes(Type type, IEnumerable<Type> baseTypes)
        {
            IDictionary<Type, IWriteHandler> possibles = new Dictionary<Type, IWriteHandler>();

            foreach (Type item in baseTypes)
            {
                // TODO Better way to decide the most appropriate possibility
                if (possibles.Count < 1)
                {
                    IWriteHandler h;
                    if (handlers.TryGetValue(item, out h))
                    {
                        possibles.Add(item, h);
                    }
                }
            }

            switch (possibles.Count)
            {
                case 0: return null;
                case 1:
                    {
                        IWriteHandler h = possibles.First().Value;
                        handlers = handlers.Add(type, h);
                        return h;
                    }
                default:
                    throw new TransitException("More thane one match for " + type);
            }
        }
 public static void Add(RecursiveAsyncLock mutex, Task<IDisposable> key)
 {
     Tuple<int, Task<IDisposable>> value;
     if (!OwnedLocks.TryGetValue(mutex, out value))
         value = Tuple.Create(0, key);
     OwnedLocks = OwnedLocks.SetItem(mutex, Tuple.Create(value.Item1 + 1, value.Item2));
 }
Esempio n. 3
0
 public ReferencesEventArgs(int contextId, ReferencesMessage message)
     : base(contextId)
 {
     _root = message.RootDependency;
     _dependencies = message.Dependencies.Select(kvp => new KeyValuePair<string, Package>(
         kvp.Key, new Package(message.LongFrameworkName, kvp.Value))).ToImmutableDictionary();
 }
Esempio n. 4
0
        protected Statement(IImmutableDictionary<Id, Id> attributes)
        {
            if (attributes == null)
            {
                throw new ArgumentNullException("attributes");
            }

            this.attributes = attributes;
        }
Esempio n. 5
0
        public NodeStatement(Id id, IImmutableDictionary<Id, Id> attributes)
            : base(attributes)
        {
            if (id == null)
            {
                throw new ArgumentNullException("id");
            }

            this.id = id;
        }
Esempio n. 6
0
 public Build(string id,
              string number,
              IImmutableDictionary<PackageVersionId, Package> createdPackages,
              IImmutableDictionary<PackageVersionId, Package> dependencies)
 {
     CreatedPackages = createdPackages;
     Dependencies = dependencies;
     Id = id;
     Number = number;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="AbstractParser"/> class.
 /// </summary>
 /// <param name="handlers">The handlers.</param>
 /// <param name="defaultHandler">The default handler.</param>
 /// <param name="dictionaryBuilder">The dictionary builder.</param>
 /// <param name="listBuilder">The list builder.</param>
 protected AbstractParser(IImmutableDictionary<string, IReadHandler> handlers,
     IDefaultReadHandler<object> defaultHandler,
     IDictionaryReader dictionaryBuilder,
     IListReader listBuilder)
 {
     this.handlers = handlers;
     this.defaultHandler = defaultHandler;
     this.dictionaryBuilder = (IDictionaryReader)dictionaryBuilder;
     this.listBuilder = (IListReader)listBuilder;
 }
Esempio n. 8
0
 /// <summary>
 /// Initializes a new instance of the <see cref="JsonParser"/> class.
 /// </summary>
 /// <param name="jsonTextReader">The json text reader.</param>
 /// <param name="handlers">The handlers.</param>
 /// <param name="defaultHandler">The default handler.</param>
 /// <param name="dictionaryBuilder">The dictionary builder.</param>
 /// <param name="listBuilder">The list builder.</param>
 public JsonParser(
     JsonTextReader jsonTextReader,
     IImmutableDictionary<string, IReadHandler> handlers,
     IDefaultReadHandler<object> defaultHandler,
     IDictionaryReader dictionaryBuilder,
     IListReader listBuilder)
     : base(handlers, defaultHandler, dictionaryBuilder, listBuilder)
 {
     this.jp = jsonTextReader;
 }
 public static void Remove(RecursiveAsyncLock mutex)
 {
     var value = OwnedLocks[mutex];
     if (value.Item1 == 1)
     {
         OwnedLocks = OwnedLocks.Remove(mutex);
         value.Item2.Result.Dispose();
     }
     else
     {
         OwnedLocks = OwnedLocks.SetItem(mutex, Tuple.Create(value.Item1 - 1, value.Item2));
     }
 }
Esempio n. 10
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ParReader"/> class based on the specified stream and using ASCII encoding.
        /// </summary>
        /// <param name="output">The output stream.</param>
        /// <param name="leaveOpen">true to leave the stream open after the <see cref="ParWriter"/> object is disposed; otherwise, false.</param>
        public ParWriter(Stream output, bool leaveOpen) : base(output, Encoding.ASCII, leaveOpen)
        {
            var origin = BaseStream.Position;
            BaseStream.Seek(0, SeekOrigin.Begin);

            if (output.CanRead && output.CanSeek)
            {
                using (var reader = new BinaryReader(output, Encoding.ASCII, true))
                {
                    while (BaseStream.Position < BaseStream.Length)
                    {
                        int b;

                        do
                        {
                            b = BaseStream.ReadByte();

                            if (b == 'P')
                            {
                                byte[] buffer = new byte[8];
                                BaseStream.Read(buffer, 1, 7);
                                buffer[0] = (byte)b;

                                if (Encoding.UTF8.GetString(buffer) == "PAR2\0PKT")
                                {
                                    var pos = BaseStream.Position - 8;
                                    var ok = Verify(reader);
                                    var end = BaseStream.Position;

                                    if (ok)
                                    {
                                        BaseStream.Seek(pos + 8, SeekOrigin.Begin);
                                        packets = packets.Add(pos, reader.ReadInt64());
                                        BaseStream.Seek(end, SeekOrigin.Begin);
                                    }
                                    else
                                    {
                                        BaseStream.Seek(pos + 1, SeekOrigin.Begin);
                                    }
                                }
                            }
                        }
                        while (b != 'P');
                    }
                }

                BaseStream.Seek(origin, SeekOrigin.Begin);
            }
        }
Esempio n. 11
0
        public EdgeStatement(NodeId fromId, NodeId toId, IImmutableDictionary<Id, Id> attributes)
            : base(attributes)
        {
            if (fromId == null)
            {
                throw new ArgumentNullException("fromId");
            }
            if (toId == null)
            {
                throw new ArgumentNullException("toId");
            }

            this.fromId = fromId;
            this.toId = toId;
        }
Esempio n. 12
0
        private IWriteHandler CheckBaseClasses(Type type)
        {
            Type baseType = type.GetTypeInfo().BaseType;
            while (baseType != null && baseType != typeof(object))
            {
                IWriteHandler handler;
                if (handlers.TryGetValue(baseType, out handler))
                {
                    handlers = handlers.Add(type, handler);
                    return handler;
                }

                baseType = baseType.GetTypeInfo().BaseType;
            }

            return null;
        }
Esempio n. 13
0
        public Configuration(XContainer xml)
        {
            var settings = xml
                .Descendants("Setting")
                .Select(e =>
                {
                    var keyElement = e.Element("Key");
                    var valueElement = e.Element("Value");
                    if (valueElement != null && keyElement != null)
                    {
                        return new
                        {
                            Key = keyElement.Value,
                            Value = valueElement.Value
                        };
                    }
                    return null;
                })
                .Where(e => e != null)
                .ToImmutableDictionary(e => e.Key, e => e.Value);

            IgnoreHeaderComments = "true".Equals(settings["sonar.cs.ignoreHeaderComments"]);

            Files = xml.Descendants("File").Select(e => e.Value).ToImmutableList();

            AnalyzerIds = xml.Descendants("Rule").Select(e => e.Elements("Key").Single().Value).ToImmutableHashSet();

            var builder = ImmutableDictionary.CreateBuilder<string, List<IImmutableDictionary<string, string>>>();
            foreach (var rule in xml.Descendants("Rule").Where(e => e.Elements("Parameters").Any()))
            {
                var analyzerId = rule.Elements("Key").Single().Value;

                var parameters = rule
                                 .Elements("Parameters").Single()
                                 .Elements("Parameter")
                                 .ToImmutableDictionary(e => e.Elements("Key").Single().Value, e => e.Elements("Value").Single().Value);

                if (!builder.ContainsKey(analyzerId))
                {
                    builder.Add(analyzerId, new List<IImmutableDictionary<string, string>>());
                }
                builder[analyzerId].Add(parameters);
            }
            Parameters = builder.ToImmutable();
        }
Esempio n. 14
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ParReader"/> class based on the specified stream and using ASCII encoding, and optionally leaves the stream open.
        /// </summary>
        /// <param name="input">The input stream.</param>
        /// <param name="leaveOpen">true to leave the stream open after the <see cref="ParReader"/> object is disposed; otherwise, false.</param>
        public ParReader(Stream input, bool leaveOpen) : base(input, Encoding.ASCII, leaveOpen)
        {
            var origin = BaseStream.Position;
            BaseStream.Seek(0, SeekOrigin.Begin);

            while (BaseStream.Position < BaseStream.Length)
            {
                int b;

                do
                {
                    b = BaseStream.ReadByte();

                    if (b == 'P')
                    {
                        byte[] buffer = new byte[8];
                        BaseStream.Read(buffer, 1, 7);
                        buffer[0] = (byte)b;

                        if (Encoding.UTF8.GetString(buffer) == "PAR2\0PKT")
                        {
                            var pos = BaseStream.Position - 8;
                            var ok = Verify();
                            var end = BaseStream.Position;

                            if (ok)
                            {
                                BaseStream.Seek(pos + 48, SeekOrigin.Begin);
                                var type = this.ReadBytes(16);
                                BaseStream.Seek(end, SeekOrigin.Begin);
                                packets = packets.Add(pos, new PacketType(type));
                            }
                            else
                            {
                                BaseStream.Seek(pos + 1, SeekOrigin.Begin);
                            }
                        }
                    }
                }
                while (b != 'P');
            }

            BaseStream.Seek(origin, SeekOrigin.Begin);
        }
Esempio n. 15
0
		/// <summary>
		/// Creates a new instance of the SyntaxTreeGeneratorData class
		/// </summary>
		/// <param name="ilGenerator">The IL generator</param>
		/// <param name="symbolTable">The symbol table</param>
		public SyntaxTreeGeneratorData(ILGenerator ilGenerator, IImmutableDictionary<string, Symbol> symbolTable)
		{
			this.ILGenerator = ilGenerator;
			this.SymbolTable = symbolTable;
		}
Esempio n. 16
0
 private NormalChildrenContainer(IImmutableDictionary<string, IChildStats> children)
     : base(children)
 {
 }
Esempio n. 17
0
 public ImmutableInbox(IImmutableDictionary<StuffId, ImmutableStuff> dict)
 {
     _dict = dict;
 }
Esempio n. 18
0
 public Bucket(Address owner, long version, IImmutableDictionary<string, ValueHolder> content) : this()
 {
     Owner = owner;
     Version = version;
     Content = content;
 }
 internal PackageResolver(IImmutableDictionary<string, ImmutableArray<string>> map)
 {
     _map = map;
 }
Esempio n. 20
0
        public static void DictionaryOfList()
        {
            const string JsonString = @"{""Key1"":[1,2],""Key2"":[3,4]}";

            {
                IDictionary obj = JsonSerializer.Parse <IDictionary>(JsonString);

                Assert.Equal(2, obj.Count);

                int expectedNumber = 1;

                JsonElement element = (JsonElement)obj["Key1"];
                foreach (JsonElement value in element.EnumerateArray())
                {
                    Assert.Equal(expectedNumber++, value.GetInt32());
                }

                element = (JsonElement)obj["Key2"];
                foreach (JsonElement value in element.EnumerateArray())
                {
                    Assert.Equal(expectedNumber++, value.GetInt32());
                }

                string json = JsonSerializer.ToString(obj);
                Assert.Equal(JsonString, json);
            }

            {
                IDictionary <string, List <int> > obj = JsonSerializer.Parse <IDictionary <string, List <int> > >(JsonString);

                Assert.Equal(2, obj.Count);
                Assert.Equal(2, obj["Key1"].Count);
                Assert.Equal(1, obj["Key1"][0]);
                Assert.Equal(2, obj["Key1"][1]);
                Assert.Equal(2, obj["Key2"].Count);
                Assert.Equal(3, obj["Key2"][0]);
                Assert.Equal(4, obj["Key2"][1]);

                string json = JsonSerializer.ToString(obj);
                Assert.Equal(JsonString, json);
            }

            {
                ImmutableDictionary <string, List <int> > obj = JsonSerializer.Parse <ImmutableDictionary <string, List <int> > >(JsonString);

                Assert.Equal(2, obj.Count);
                Assert.Equal(2, obj["Key1"].Count);
                Assert.Equal(1, obj["Key1"][0]);
                Assert.Equal(2, obj["Key1"][1]);
                Assert.Equal(2, obj["Key2"].Count);
                Assert.Equal(3, obj["Key2"][0]);
                Assert.Equal(4, obj["Key2"][1]);

                string       json = JsonSerializer.ToString(obj);
                const string ReorderedJsonString = @"{""Key2"":[3,4],""Key1"":[1,2]}";
                Assert.True(JsonString == json || ReorderedJsonString == json);
            }

            {
                IImmutableDictionary <string, List <int> > obj = JsonSerializer.Parse <IImmutableDictionary <string, List <int> > >(JsonString);

                Assert.Equal(2, obj.Count);
                Assert.Equal(2, obj["Key1"].Count);
                Assert.Equal(1, obj["Key1"][0]);
                Assert.Equal(2, obj["Key1"][1]);
                Assert.Equal(2, obj["Key2"].Count);
                Assert.Equal(3, obj["Key2"][0]);
                Assert.Equal(4, obj["Key2"][1]);


                string       json = JsonSerializer.ToString(obj);
                const string ReorderedJsonString = @"{""Key2"":[3,4],""Key1"":[1,2]}";
                Assert.True(JsonString == json || ReorderedJsonString == json);
            }
        }
Esempio n. 21
0
        public static void DictionaryOfString()
        {
            const string JsonString          = @"{""Hello"":""World"",""Hello2"":""World2""}";
            const string ReorderedJsonString = @"{""Hello2"":""World2"",""Hello"":""World""}";

            {
                IDictionary obj = JsonSerializer.Parse <IDictionary>(JsonString);
                Assert.Equal("World", ((JsonElement)obj["Hello"]).GetString());
                Assert.Equal("World2", ((JsonElement)obj["Hello2"]).GetString());

                string json = JsonSerializer.ToString(obj);
                Assert.Equal(JsonString, json);

                json = JsonSerializer.ToString <object>(obj);
                Assert.Equal(JsonString, json);
            }

            {
                Dictionary <string, string> obj = JsonSerializer.Parse <Dictionary <string, string> >(JsonString);
                Assert.Equal("World", obj["Hello"]);
                Assert.Equal("World2", obj["Hello2"]);

                string json = JsonSerializer.ToString(obj);
                Assert.Equal(JsonString, json);

                json = JsonSerializer.ToString <object>(obj);
                Assert.Equal(JsonString, json);
            }

            {
                SortedDictionary <string, string> obj = JsonSerializer.Parse <SortedDictionary <string, string> >(JsonString);
                Assert.Equal("World", obj["Hello"]);
                Assert.Equal("World2", obj["Hello2"]);

                string json = JsonSerializer.ToString(obj);
                Assert.Equal(JsonString, json);

                json = JsonSerializer.ToString <object>(obj);
                Assert.Equal(JsonString, json);
            }

            {
                IDictionary <string, string> obj = JsonSerializer.Parse <IDictionary <string, string> >(JsonString);
                Assert.Equal("World", obj["Hello"]);
                Assert.Equal("World2", obj["Hello2"]);

                string json = JsonSerializer.ToString(obj);
                Assert.Equal(JsonString, json);

                json = JsonSerializer.ToString <object>(obj);
                Assert.Equal(JsonString, json);
            }

            {
                IReadOnlyDictionary <string, string> obj = JsonSerializer.Parse <IReadOnlyDictionary <string, string> >(JsonString);
                Assert.Equal("World", obj["Hello"]);
                Assert.Equal("World2", obj["Hello2"]);

                string json = JsonSerializer.ToString(obj);
                Assert.Equal(JsonString, json);

                json = JsonSerializer.ToString <object>(obj);
                Assert.Equal(JsonString, json);
            }

            {
                ImmutableDictionary <string, string> obj = JsonSerializer.Parse <ImmutableDictionary <string, string> >(JsonString);
                Assert.Equal("World", obj["Hello"]);
                Assert.Equal("World2", obj["Hello2"]);

                string json = JsonSerializer.ToString(obj);
                Assert.True(JsonString == json || ReorderedJsonString == json);

                json = JsonSerializer.ToString <object>(obj);
                Assert.True(JsonString == json || ReorderedJsonString == json);
            }

            {
                IImmutableDictionary <string, string> obj = JsonSerializer.Parse <IImmutableDictionary <string, string> >(JsonString);
                Assert.Equal("World", obj["Hello"]);
                Assert.Equal("World2", obj["Hello2"]);

                string json = JsonSerializer.ToString(obj);
                Assert.True(JsonString == json || ReorderedJsonString == json);

                json = JsonSerializer.ToString <object>(obj);
                Assert.True(JsonString == json || ReorderedJsonString == json);
            }

            {
                ImmutableSortedDictionary <string, string> obj = JsonSerializer.Parse <ImmutableSortedDictionary <string, string> >(JsonString);
                Assert.Equal("World", obj["Hello"]);
                Assert.Equal("World2", obj["Hello2"]);

                string json = JsonSerializer.ToString(obj);
                Assert.True(JsonString == json);

                json = JsonSerializer.ToString <object>(obj);
                Assert.True(JsonString == json);
            }

            {
                Hashtable obj = JsonSerializer.Parse <Hashtable>(JsonString);
                Assert.Equal("World", ((JsonElement)obj["Hello"]).GetString());
                Assert.Equal("World2", ((JsonElement)obj["Hello2"]).GetString());

                string json = JsonSerializer.ToString(obj);
                Assert.True(JsonString == json || ReorderedJsonString == json);

                json = JsonSerializer.ToString <object>(obj);
                Assert.True(JsonString == json || ReorderedJsonString == json);
            }

            {
                SortedList obj = JsonSerializer.Parse <SortedList>(JsonString);
                Assert.Equal("World", ((JsonElement)obj["Hello"]).GetString());
                Assert.Equal("World2", ((JsonElement)obj["Hello2"]).GetString());

                string json = JsonSerializer.ToString(obj);
                Assert.Equal(JsonString, json);

                json = JsonSerializer.ToString <object>(obj);
                Assert.Equal(JsonString, json);
            }
        }
 internal static int CountShards(IImmutableDictionary <IActorRef, IImmutableList <string> > allocations)
 {
     return(CountShardsPerRegion(allocations).Sum());
 }
 internal static ImmutableList <int> CountShardsPerRegion(IImmutableDictionary <IActorRef, IImmutableList <string> > newAllocations)
 {
     return(newAllocations.Values.Select(i => i.Count).ToImmutableList());
 }
 public void SetCommands(IImmutableDictionary <string, CommandBase> commands)
 {
     this.commands = commands;
 }
 public CommandExecutor(TextReader inIO = null, TextWriter outIO = null)
 {
     this.commands = new Dictionary <string, CommandBase>().ToImmutableDictionary();
     _inIO         = inIO ?? Console.In;
     _outIO        = outIO ?? Console.Out;
 }
Esempio n. 26
0
 protected abstract void AddToContext(string fullPath, IImmutableDictionary <string, string> metadata, bool isActiveContext, IProjectLogger logger);
 public AbstractEmitter(IImmutableDictionary<Type, IWriteHandler> handlers)
 {
     this.handlers = handlers;
 }
Esempio n. 28
0
        public async Task ReconcileAsync(CancellationToken token)
        {
            DeploymentStatus status            = DeploymentStatus.Unknown;
            ModuleSet        moduleSetToReport = null;

            using (await this.reconcileLock.LockAsync(token))
            {
                try
                {
                    Events.StartingReconcile();
                    (ModuleSet current, DeploymentConfigInfo deploymentConfigInfo, Exception exception) = await this.GetReconcileData(token);

                    moduleSetToReport = current;
                    if (exception != null)
                    {
                        ExceptionDispatchInfo.Capture(exception).Throw();
                    }

                    DeploymentConfig deploymentConfig = deploymentConfigInfo.DeploymentConfig;
                    if (deploymentConfig.Equals(DeploymentConfig.Empty))
                    {
                        status = DeploymentStatus.Success;
                    }
                    else
                    {
                        ModuleSet desiredModuleSet = deploymentConfig.GetModuleSet();
                        _ = Task.Run(() => this.availabilityMetric.ComputeAvailability(desiredModuleSet, current))
                            .ContinueWith(t => Events.UnknownFailure(t.Exception), TaskContinuationOptions.OnlyOnFaulted)
                            .ConfigureAwait(false);

                        // TODO - Update this logic to create identities only when needed, in the Command factory, instead of creating all the identities
                        // up front here. That will allow handling the case when only the state of the system has changed (say one module crashes), and
                        // no new identities need to be created. This will simplify the logic to allow EdgeAgent to work when offline.
                        // But that required ModuleSet.Diff to be updated to include modules updated by deployment, and modules updated by state change.
                        IImmutableDictionary <string, IModuleIdentity> identities = await this.moduleIdentityLifecycleManager.GetModuleIdentitiesAsync(desiredModuleSet, current);

                        Plan plan = await this.planner.PlanAsync(desiredModuleSet, current, deploymentConfig.Runtime, identities);

                        if (plan.IsEmpty)
                        {
                            status = DeploymentStatus.Success;
                        }
                        else
                        {
                            try
                            {
                                bool result = await this.planRunner.ExecuteAsync(deploymentConfigInfo.Version, plan, token);

                                await this.UpdateCurrentConfig(deploymentConfigInfo);

                                if (result)
                                {
                                    status = DeploymentStatus.Success;
                                }
                            }
                            catch (Exception ex) when(!ex.IsFatal())
                            {
                                Events.PlanExecutionFailed(ex);
                                await this.UpdateCurrentConfig(deploymentConfigInfo);

                                throw;
                            }
                        }
                    }
                }
                catch (Exception ex) when(!ex.IsFatal())
                {
                    switch (ex)
                    {
                    case ConfigEmptyException _:
                        status = new DeploymentStatus(DeploymentStatusCode.ConfigEmptyError, ex.Message);
                        Events.EmptyConfig(ex);
                        break;

                    case InvalidSchemaVersionException _:
                        status = new DeploymentStatus(DeploymentStatusCode.InvalidSchemaVersion, ex.Message);
                        Events.InvalidSchemaVersion(ex);
                        break;

                    case ConfigFormatException _:
                        status = new DeploymentStatus(DeploymentStatusCode.ConfigFormatError, ex.Message);
                        Events.InvalidConfigFormat(ex);
                        break;

                    default:
                        status = new DeploymentStatus(DeploymentStatusCode.Failed, ex.Message);
                        Events.UnknownFailure(ex);
                        break;
                    }
                }

                await this.reporter.ReportAsync(token, moduleSetToReport, await this.environment.GetRuntimeInfoAsync(), this.currentConfig.Version, status);

                Events.FinishedReconcile();
            }
        }
Esempio n. 29
0
 public JsonVerboseEmitter(JsonWriter jsonWriter, IImmutableDictionary<Type, IWriteHandler> handlers)
     : base(jsonWriter, handlers)
 {
 }
Esempio n. 30
0
        /// <summary>
        ///     Visits the entire tree, calling <see cref="IProjectTreePropertiesProvider.CalculatePropertyValues(IProjectTreeCustomizablePropertyContext, IProjectTreeCustomizablePropertyValues)"/>
        ///     for every node.
        /// </summary>
        public static IProjectTree ChangePropertyValuesForEntireTree(this IProjectTreePropertiesProvider propertiesProvider, IProjectTree tree, IImmutableDictionary <string, string>?projectTreeSettings = null)
        {
            // Cheat here, because the IProjectTree that we get from ProjectTreeParser is mutable, we want to clone it
            // so that any properties providers changes don't affect the "original" tree. If we implemented a completely
            // immutable tree, then we wouldn't have to do that - but that's currently a lot of work for test-only purposes.
            string treeAsString = ProjectTreeWriter.WriteToString(tree);

            return(ChangePropertyValuesWalkingTree(propertiesProvider, ProjectTreeParser.Parse(treeAsString), projectTreeSettings));
        }
Esempio n. 31
0
 private async Task<long> NextTagSequenceNr(string tag)
 {
     long value;
     if (!_tagSequenceNr.TryGetValue(tag, out value))
     {
         value = await ReadHighestSequenceNrAsync(TagId(tag), 0L);
     }
     value++;
     _tagSequenceNr = _tagSequenceNr.SetItem(tag, value);
     return value;
 }
Esempio n. 32
0
        private static IProjectTree ChangePropertyValuesWalkingTree(IProjectTreePropertiesProvider propertiesProvider, IProjectTree tree, IImmutableDictionary <string, string>?projectTreeSettings)
        {
            tree = ChangePropertyValues(propertiesProvider, tree, projectTreeSettings);

            foreach (IProjectTree child in tree.Children)
            {
                tree = ChangePropertyValuesWalkingTree(propertiesProvider, child, projectTreeSettings).Parent !;
            }

            return(tree);
        }
Esempio n. 33
0
        /// <summary>
        /// Caches the write.
        /// </summary>
        /// <param name="s">The s.</param>
        /// <param name="asDictionaryKey">if set to <c>true</c> [as dictionary key].</param>
        /// <returns></returns>
        public string CacheWrite(string s, bool asDictionaryKey)
        {
            if (enabled && IsCacheable(s, asDictionaryKey))
            {
                string val;
                if (cache.TryGetValue(s, out val))
                {
                    return val;
                }
                else
                {
                    if (index == MaxCacheEntries)
                    {
                        Init();
                    }

                    cache = cache.SetItem(s, IndexToCode(index++));
                }
            }

            // TODO Either s or val is returned. Weird?!
            return s;
        }
Esempio n. 34
0
        private static IProjectTree ChangePropertyValues(IProjectTreePropertiesProvider propertiesProvider, IProjectTree child, IImmutableDictionary <string, string>?projectTreeSettings)
        {
            var propertyContextAndValues = new ProjectTreeCustomizablePropertyContextAndValues(child, projectTreeSettings);

            propertiesProvider.CalculatePropertyValues(propertyContextAndValues, propertyContextAndValues);

            return(propertyContextAndValues.Tree);
        }
        public override IImmutableDictionary <string, ITypeSpecBuilder> Process(IReflector reflector, Type type, IMethodRemover methodRemover, ISpecificationBuilder specification, IImmutableDictionary <string, ITypeSpecBuilder> metamodel)
        {
            if (LongValueSemanticsProvider.IsAdaptedType(type))
            {
                var result = reflector.LoadSpecification(LongValueSemanticsProvider.AdaptedType, metamodel);

                metamodel = result.Item2;
                var spec = result.Item1 as IObjectSpecImmutable;
                AddValueFacets(new LongValueSemanticsProvider(spec, specification), specification);
            }
            return(metamodel);
        }
Esempio n. 36
0
 public ProjectTreeCustomizablePropertyContextAndValues(IProjectTree tree, IImmutableDictionary <string, string>?projectTreeSettings)
 {
     _tree = tree;
     ProjectTreeSettings = projectTreeSettings ?? ImmutableDictionary <string, string> .Empty;
 }
Esempio n. 37
0
 protected abstract void UpdateInContext(string fullPath, IImmutableDictionary <string, string> previousMetadata, IImmutableDictionary <string, string> currentMetadata, bool isActiveContext, IProjectLogger logger);
        public override IImmutableDictionary <string, ITypeSpecBuilder> Process(IReflector reflector, Type type, IMethodRemover methodRemover, ISpecificationBuilder specification, IImmutableDictionary <string, ITypeSpecBuilder> metamodel)
        {
            var attribute = type.GetCustomAttribute <MultiLineAttribute>();

            FacetUtils.AddFacet(Create(attribute, specification));
            return(metamodel);
        }
Esempio n. 39
0
 public static IChildrenContainer Create(IImmutableDictionary<string, IChildStats> children)
 {
     if (children.Count == 0) return EmptyChildrenContainer.Instance;
     return new NormalChildrenContainer(children);
 }
 public override IImmutableDictionary <string, ITypeSpecBuilder> Process(IReflector reflector, MethodInfo method, IMethodRemover methodRemover, ISpecificationBuilder specification, IImmutableDictionary <string, ITypeSpecBuilder> metamodel)
 {
     Process(method, specification);
     return(metamodel);
 }
Esempio n. 41
0
        /// <summary>
        /// Writes a <see cref="Packet"/> object to the currrent stream.
        /// </summary>
        /// <param name="packet">The <see cref="Packet"/> object.</param>
        public void Write(Packet packet)
        {
            var range = new Range<long>();
            range.Minimum = BaseStream.Position;
            
            packet.Header.CopyTo(BaseStream);
            packet.Body.CopyTo(BaseStream);

            range.Maximum = BaseStream.Position - 1;

            var overwrittenPackets = packets
                .Where(x => range.IsInsideRange(new Range<long>
                {
                    Minimum = x.Key,
                    Maximum = x.Key + x.Value - 1
                }))
                .Select(x => x.Key);

            foreach (var key in overwrittenPackets)
            {
                packets = packets.Remove(key);
            }

            packets = packets.Add(range.Minimum, range.Maximum - range.Minimum + 1);
        }
        public override IImmutableDictionary <string, ITypeSpecBuilder> Process(IReflector reflector, PropertyInfo property, IMethodRemover methodRemover, ISpecificationBuilder specification, IImmutableDictionary <string, ITypeSpecBuilder> metamodel)
        {
            if (property.GetGetMethod() != null && TypeUtils.IsString(property.PropertyType))
            {
                Process(property, specification);
            }

            return(metamodel);
        }
Esempio n. 43
0
        /// <summary>
        ///     Applies the specified version of the project evaluation <see cref="IProjectChangeDiff"/> and metadata to the underlying
        ///     <see cref="IWorkspaceProjectContext"/>, indicating if the context is the currently active one.
        /// </summary>
        /// <exception cref="ArgumentNullException">
        ///     <paramref name="version"/> is <see langword="null"/>.
        ///     <para>
        ///         -or-
        ///     </para>
        ///     <paramref name="difference" /> is <see langword="null"/>.
        ///     <para>
        ///         -or-
        ///     </para>
        ///     <paramref name="previousMetadata" /> is <see langword="null"/>.
        ///     <para>
        ///         -or-
        ///     </para>
        ///     <paramref name="currentMetadata" /> is <see langword="null"/>.
        ///     <para>
        ///         -or-
        ///     </para>
        ///     <paramref name="logger" /> is <see langword="null"/>.
        /// </exception>
        public void ApplyProjectEvaluation(IComparable version, IProjectChangeDiff difference, IImmutableDictionary <string, IImmutableDictionary <string, string> > previousMetadata, IImmutableDictionary <string, IImmutableDictionary <string, string> > currentMetadata, bool isActiveContext, IProjectLogger logger)
        {
            Requires.NotNull(version, nameof(version));
            Requires.NotNull(difference, nameof(difference));
            Requires.NotNull(previousMetadata, nameof(previousMetadata));
            Requires.NotNull(currentMetadata, nameof(currentMetadata));
            Requires.NotNull(logger, nameof(logger));

            if (!difference.AnyChanges)
            {
                return;
            }

            difference = HandlerServices.NormalizeRenames(difference);
            EnqueueProjectEvaluation(version, difference);

            ApplyChangesToContext(difference, previousMetadata, currentMetadata, isActiveContext, logger, evaluation: true);
        }
        public override IImmutableDictionary <string, ITypeSpecBuilder> ProcessParams(IReflector reflector, MethodInfo method, int paramNum, ISpecificationBuilder holder, IImmutableDictionary <string, ITypeSpecBuilder> metamodel)
        {
            ParameterInfo parameter = method.GetParameters()[paramNum];

            if (TypeUtils.IsString(parameter.ParameterType))
            {
                var attribute = parameter.GetCustomAttribute <MultiLineAttribute>();
                FacetUtils.AddFacet(Create(attribute, holder));
            }

            return(metamodel);
        }
Esempio n. 45
0
 public AttributeStatement(AttributeKinds attributeKind, IImmutableDictionary<Id, Id> attributes)
     : base(attributes)
 {
     this.attributeKind = attributeKind;
 }
Esempio n. 46
0
        public static string GenerateCompoundDurationTimex(Dictionary <string, string> unitToTimexComponents, IImmutableDictionary <string, long> unitValueMap)
        {
            var unitList = new List <string>(unitToTimexComponents.Keys);

            unitList.Sort((x, y) => (unitValueMap[x] < unitValueMap[y] ? 1 : -1));
            var isTimeDurationAlreadyExist = false;
            var timexBuilder = new StringBuilder(Constants.GeneralPeriodPrefix);

            for (int i = 0; i < unitList.Count; i++)
            {
                var timexComponent = unitToTimexComponents[unitList[i]];

                // The Time Duration component occurs first time,
                if (!isTimeDurationAlreadyExist && IsTimeDurationTimex(timexComponent))
                {
                    timexBuilder.Append($"{Constants.TimeTimexPrefix}{GetDurationTimexWithoutPrefix(timexComponent)}");
                    isTimeDurationAlreadyExist = true;
                }
                else
                {
                    timexBuilder.Append($"{GetDurationTimexWithoutPrefix(timexComponent)}");
                }
            }

            return(timexBuilder.ToString());
        }
Esempio n. 47
0
 public JsonEmitter(JsonWriter jsonWriter, IImmutableDictionary<Type, IWriteHandler> handlers)
     : base(handlers)
 {
     this.jsonWriter = jsonWriter;
 }
Esempio n. 48
0
        public override IImmutableDictionary <string, ITypeSpecBuilder> Process(IReflector reflector, Type type, IMethodRemover methodRemover, ISpecificationBuilder specification, IImmutableDictionary <string, ITypeSpecBuilder> metamodel)
        {
            if (!StringValueSemanticsProvider.IsAdaptedType(type))
            {
                return(metamodel);
            }

            var(oSpec, mm) = reflector.LoadSpecification <IObjectSpecImmutable>(StringValueSemanticsProvider.AdaptedType, metamodel);
            AddValueFacets(new StringValueSemanticsProvider(oSpec, specification), specification);
            return(mm);
        }
Esempio n. 49
0
        private async Task <Dictionary <DocumentId, DocumentStateChecksums> > GetDocumentMapAsync <T>(Project project, IImmutableDictionary <DocumentId, T> states, HashSet <Checksum> documents)
            where T : TextDocumentState
        {
            var map = new Dictionary <DocumentId, DocumentStateChecksums>();

            foreach (var kv in states)
            {
                var documentChecksums = await kv.Value.GetStateChecksumsAsync(_cancellationToken).ConfigureAwait(false);

                if (documents.Contains(documentChecksums.Checksum))
                {
                    map.Add(kv.Key, documentChecksums);
                }
            }

            return(map);
        }
Esempio n. 50
0
 protected override void LoadPlainValueInternal(IImmutableDictionary <string, IValue> plainValue)
 {
     avatarAddress = plainValue["avatarAddress"].ToAddress();
     slotIndex     = plainValue["slotIndex"].ToInteger();
 }
Esempio n. 51
0
 public DiagramOperationResult(
     [NotNull] IImmutableDictionary <ModelNodeId, IDiagramNode> nodes,
     [NotNull] IImmutableDictionary <ModelRelationshipId, IDiagramConnector> connectors)
     : this(nodes, connectors, ImmutableList.Create <DiagramShapeEventBase>())
 {
 }
Esempio n. 52
0
        public override IImmutableDictionary <string, ITypeSpecBuilder> Process(IReflector reflector, Type type, IMethodRemover methodRemover, ISpecificationBuilder specification, IImmutableDictionary <string, ITypeSpecBuilder> metamodel)
        {
            var method = FindMethod(reflector, type, MethodType.Class, RecognisedMethodsAndPrefixes.MenuMethod, null, null);

            if (method != null)
            {
                RemoveMethod(methodRemover, method);
                FacetUtils.AddFacet(new MenuFacetViaMethod(method, specification));
            }
            else
            {
                FacetUtils.AddFacet(new MenuFacetDefault(specification));
            }

            return(metamodel);
        }
 public IImmutableDictionary <string, ITypeSpecBuilder> IntrospectType(Type typeToIntrospect, ITypeSpecImmutable specification, IImmutableDictionary <string, ITypeSpecBuilder> metamodel) => throw new NotImplementedException();
Esempio n. 54
0
        public async Task <IRule?> GetBrowseObjectRuleAsync(IDependency dependency, IProjectCatalogSnapshot?catalogs)
        {
            Requires.NotNull(dependency, nameof(dependency));

            IImmutableDictionary <string, IPropertyPagesCatalog> namedCatalogs = await GetNamedCatalogsAsync();

            Requires.NotNull(namedCatalogs, nameof(namedCatalogs));

            if (!namedCatalogs.TryGetValue(PropertyPageContexts.BrowseObject, out IPropertyPagesCatalog browseObjectsCatalog))
            {
                // Issue https://github.com/dotnet/project-system/issues/4860 suggests this code path
                // can exist, however a repro was not found to dig deeper into the underlying cause.
                // For now just return null as the upstream caller handles null correctly anyway.
                return(null);
            }

            Rule?schema = browseObjectsCatalog.GetSchema(dependency.SchemaName);

            string itemSpec = string.IsNullOrEmpty(dependency.OriginalItemSpec)
                ? dependency.Path
                : dependency.OriginalItemSpec;

            var context = ProjectPropertiesContext.GetContext(
                UnconfiguredProject,
                itemType: dependency.SchemaItemType,
                itemName: itemSpec);

            if (schema == null)
            {
                // Since we have no browse object, we still need to create *something* so
                // that standard property pages can pop up.
                Rule emptyRule = RuleExtensions.SynthesizeEmptyRule(context.ItemType);

                return(GetConfiguredProjectExports().PropertyPagesDataModelProvider.GetRule(
                           emptyRule,
                           context.File,
                           context.ItemType,
                           context.ItemName));
            }

            if (dependency.Resolved)
            {
                return(GetConfiguredProjectExports().RuleFactory.CreateResolvedReferencePageRule(
                           schema,
                           context,
                           dependency.Name,
                           dependency.BrowseObjectProperties));
            }

            return(browseObjectsCatalog.BindToContext(schema.Name, context));

            async Task <IImmutableDictionary <string, IPropertyPagesCatalog> > GetNamedCatalogsAsync()
            {
                if (catalogs != null)
                {
                    return(catalogs.NamedCatalogs);
                }

                if (_namedCatalogs == null)
                {
                    Assumes.NotNull(ActiveConfiguredProject);
                    Assumes.Present(ActiveConfiguredProject.Services.PropertyPagesCatalog);

                    // Note: it is unlikely that we end up here, however for cases when node providers
                    // getting their node data not from Design time build events, we might have OnDependenciesChanged
                    // event coming before initial design time build event updates NamedCatalogs in this class.
                    // Thus, just in case, explicitly request it here (GetCatalogsAsync will acquire a project read lock)
                    _namedCatalogs = await ActiveConfiguredProject.Services.PropertyPagesCatalog.GetCatalogsAsync();
                }

                return(_namedCatalogs);
            }

            ConfiguredProjectExports GetConfiguredProjectExports()
            {
                Assumes.NotNull(ActiveConfiguredProject);

                ConfiguredProject project = dependency.TargetFramework.Equals(TargetFramework.Any)
                    ? ActiveConfiguredProject
                    : _dependenciesSnapshotProvider.GetConfiguredProject(dependency.TargetFramework) ?? ActiveConfiguredProject;

                return(GetActiveConfiguredProjectExports(project));
            }
        }
        private bool IsNamespaceMatch(Type type) {
            if (!namespaceScratchPad.ContainsKey(type)) {
                var ns = type.Namespace ?? "";
                var match = config.ModelNamespaces.Any(ns.StartsWith);
                namespaceScratchPad = namespaceScratchPad.Add(type, match);
            }

            return namespaceScratchPad[type];
        }
Esempio n. 56
0
        private void ApplyChangesToContext(IProjectChangeDiff difference, IImmutableDictionary <string, IImmutableDictionary <string, string> > previousMetadata, IImmutableDictionary <string, IImmutableDictionary <string, string> > currentMetadata, bool isActiveContext, IProjectLogger logger, bool evaluation)
        {
            foreach (string includePath in difference.RemovedItems)
            {
                RemoveFromContextIfPresent(includePath, logger);
            }

            foreach (string includePath in difference.AddedItems)
            {
                AddToContextIfNotPresent(includePath, currentMetadata, isActiveContext, logger);
            }

            if (evaluation)
            {   // No need to look at metadata for design-time builds, the items that come from
                // that aren't traditional items, but are just command-line args we took from
                // the compiler and converted them to look like items.

                foreach (string includePath in difference.ChangedItems)
                {
                    UpdateInContextIfPresent(includePath, previousMetadata, currentMetadata, isActiveContext, logger);
                }
            }

            Assumes.True(difference.RenamedItems.Count == 0, "We should have normalized renames.");
        }
Esempio n. 57
0
 /// <summary>
 /// Initializes this instance.
 /// </summary>
 /// <returns>The write cache.</returns>
 public WriteCache Init()
 {
     index = 0;
     cache = cache.Clear();
     return this;
 }
 public Task ClearAsync()
 {
     _cache = _cache.Clear();
     return Task.FromResult(true);
 }
Esempio n. 59
0
 public AggregateAnalysisDetail(AggregateAnalysisDetailAnalysis analysis, string job, string workItem, IImmutableDictionary <string, string> key)
 {
     Analysis = analysis;
     Job      = job;
     WorkItem = workItem;
     Key      = key;
 }
Esempio n. 60
0
        private void UpdateInContextIfPresent(string includePath, IImmutableDictionary <string, IImmutableDictionary <string, string> > previousMetadata, IImmutableDictionary <string, IImmutableDictionary <string, string> > currentMetadata, bool isActiveContext, IProjectLogger logger)
        {
            string fullPath = _project.MakeRooted(includePath);

            if (_paths.Contains(fullPath))
            {
                IImmutableDictionary <string, string> previousItemMetadata = previousMetadata.GetValueOrDefault(includePath, ImmutableStringDictionary <string> .EmptyOrdinal);
                IImmutableDictionary <string, string> currentItemMetadata  = currentMetadata.GetValueOrDefault(includePath, ImmutableStringDictionary <string> .EmptyOrdinal);

                UpdateInContext(fullPath, previousItemMetadata, currentItemMetadata, isActiveContext, logger);
            }
        }