Welcome to mirror list, hosted at ThFree Co, Russian Federation.

ContentTypeRegistryServiceImpl.cs « ContentType « Impl « Core « src - github.com/microsoft/vs-editor-api.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 943c6c318191d2af22bd8db490c625deb469f9d5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
//
//  Copyright (c) Microsoft Corporation. All rights reserved.
//  Licensed under the MIT License. See License.txt in the project root for license information.
//
// This file contain implementations details that are subject to change without notice.
// Use at your own risk.
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;

namespace Microsoft.VisualStudio.Utilities.Implementation
{
    public interface IContentTypeDefinitionMetadata
    {
        string Name { get; }

        [System.ComponentModel.DefaultValue(null)]
        IEnumerable<string> BaseDefinition { get; }

        [System.ComponentModel.DefaultValue(null)]
        string MimeType { get; }
    }

    [Export(typeof(IFileExtensionRegistryService))]
    [Export(typeof(IFileExtensionRegistryService2))]
    [Export(typeof(IFilePathRegistryService))]
    [Export(typeof(IContentTypeRegistryService))]
    [Export(typeof(IContentTypeRegistryService2))]
    internal sealed partial class ContentTypeRegistryImpl : IContentTypeRegistryService2, IFileExtensionRegistryService, IFileExtensionRegistryService2, IFilePathRegistryService
    {
        [ImportMany]
        internal List<Lazy<ContentTypeDefinition, IContentTypeDefinitionMetadata>> ContentTypeDefinitions { get; set; }

        [ImportMany]
        internal List<IContentTypeDefinitionSource> ExternalSources { get; set; }

        [ImportMany]
        internal List<Lazy<FileExtensionToContentTypeDefinition, IFileToContentTypeMetadata>> FileToContentTypeProductions { get; set; }

        [ImportMany]
        private List<Lazy<IFilePathToContentTypeProvider, IFilePathToContentTypeMetadata>> UnorderedFilePathToContentTypeProductions { get; set; }

        private IList<Lazy<IFilePathToContentTypeProvider, IFilePathToContentTypeMetadata>> _orderedFilePathToContentTypeProductions;
        internal IList<Lazy<IFilePathToContentTypeProvider, IFilePathToContentTypeMetadata>> OrderedFilePathToContentTypeProductions
        {
            get
            {
                if (_orderedFilePathToContentTypeProductions == null)
                {
                    if (UnorderedFilePathToContentTypeProductions != null)
                    {
                        _orderedFilePathToContentTypeProductions = Orderer.Order(UnorderedFilePathToContentTypeProductions);
                    }
                    else
                    {
                        _orderedFilePathToContentTypeProductions = new List<Lazy<IFilePathToContentTypeProvider, IFilePathToContentTypeMetadata>>();
                    }
                }
                return _orderedFilePathToContentTypeProductions;
            }
        }

        private MapCollection maps;

        /// <summary>
        /// The name of the unknown content type, guaranteed to exists no matter what other content types are produced
        /// </summary>
        private const string UnknownContentTypeName = "UNKNOWN";
        internal readonly static ContentTypeImpl UnknownContentTypeImpl = new ContentTypeImpl(ContentTypeRegistryImpl.UnknownContentTypeName, null, null);

        /// <summary>
        /// Builds the list of available content types
        /// Note: This function must be called after acquiring a lock on syncLock
        /// </summary>
        /// <remarks>
        /// Building the content type mappings should not throw exceptions, but should rather be logging issues 
        /// with some kind of common error reporting service and try to recover by ignoring the asset productions 
        /// that are deemed to cause the problem.
        /// </remarks>
        private void BuildContentTypes()
        {
            var oldMaps = Volatile.Read(ref this.maps);
            if (oldMaps == null)
            {
                var nameToContentTypeBuilder = MapCollection.Empty.NameToContentTypeMap.ToBuilder();
                var mimeTypeToContentTypeBuilder = MapCollection.Empty.MimeTypeToContentTypeMap.ToBuilder();

                // Add the singleton Unknown content type to the dictionary
                nameToContentTypeBuilder.Add(ContentTypeRegistryImpl.UnknownContentTypeName, ContentTypeRegistryImpl.UnknownContentTypeImpl);


                // For each content type provision, create an IContentType.
                foreach (Lazy<ContentTypeDefinition, IContentTypeDefinitionMetadata> contentTypeDefinition in ContentTypeDefinitions)
                {
                    AddContentTypeFromMetadata(contentTypeDefinition.Metadata.Name,
                                               contentTypeDefinition.Metadata.MimeType,
                                               contentTypeDefinition.Metadata.BaseDefinition, nameToContentTypeBuilder, mimeTypeToContentTypeBuilder);
                }

                // Now consider the external sources. This allows us to consider legacy content types together with MEF-defined
                // content types.
                foreach (IContentTypeDefinitionSource source in this.ExternalSources)
                {
                    if (source.Definitions != null)
                    {
                        foreach (IContentTypeDefinition metadata in source.Definitions)
                        {
                            AddContentTypeFromMetadata(metadata.Name,
                                                       /* mimeType*/ null,
                                                       metadata.BaseDefinitions, nameToContentTypeBuilder, mimeTypeToContentTypeBuilder);
                        }
                    }
                }

                List<ContentTypeImpl> allTypes = new List<ContentTypeImpl>(nameToContentTypeBuilder.Count);
                allTypes.AddRange(nameToContentTypeBuilder.Values);
                foreach (var type in allTypes)
                {
                    type.ProcessBaseTypes(nameToContentTypeBuilder, mimeTypeToContentTypeBuilder);
                }

#if DEBUG
                foreach (var type in nameToContentTypeBuilder.Values)
                {
                    Debug.Assert(type.IsProcessed);
                }
#endif

                foreach (var type in nameToContentTypeBuilder.Values)
                {
                    type.CheckForCycle(breakCycle: true);
                }

                var fileExtensionToContentTypeMapBuilder = MapCollection.Empty.FileExtensionToContentTypeMap.ToBuilder();
                var fileNameToContentTypeMapBuilder = MapCollection.Empty.FileNameToContentTypeMap.ToBuilder();
                foreach (var fileExtensionDefinition in this.FileToContentTypeProductions)
                {
                    // MEF ensures that there will be at least one content type in the metadata. We take the first one. 
                    // We prefer this over defining a different attribute from ContentType[] for this purpose.
                    var contentTypeName = fileExtensionDefinition.Metadata.ContentTypes.FirstOrDefault();
                    ContentTypeImpl contentType;
                    if ((contentTypeName != null) && nameToContentTypeBuilder.TryGetValue(contentTypeName, out contentType))
                    {
                        if (!string.IsNullOrEmpty(fileExtensionDefinition.Metadata.FileExtension))
                        {
                            foreach (var ext in fileExtensionDefinition.Metadata.FileExtension.Split(';'))
                            {
                                if (ext != null)
                                {
                                    var extension = RemoveExtensionDot(ext);
                                    if (!(string.IsNullOrWhiteSpace(extension) || fileExtensionToContentTypeMapBuilder.ContainsKey(extension)))
                                        fileExtensionToContentTypeMapBuilder.Add(extension, contentType);
                                }
                            }
                        }

                        if (!string.IsNullOrEmpty(fileExtensionDefinition.Metadata.FileName))
                        {
                            foreach (var name in fileExtensionDefinition.Metadata.FileName.Split(';'))
                            {
                                if (!(string.IsNullOrWhiteSpace(name) || fileNameToContentTypeMapBuilder.ContainsKey(name)))
                                    fileNameToContentTypeMapBuilder.Add(name, contentType);
                            }
                        }
                    }
                }

                var newMaps = new MapCollection(nameToContentTypeBuilder.ToImmutable(), mimeTypeToContentTypeBuilder.ToImmutable(), fileExtensionToContentTypeMapBuilder.ToImmutable(), fileNameToContentTypeMapBuilder.ToImmutable());
                Interlocked.CompareExchange(ref this.maps, newMaps, oldMaps);

                // We actually don't care whether or not the CompareExchange succeeded.
                // Eitehr it succeeded (normally the case) or someone else successfully completed BuildContentTypes on another thread and we shouldn't do anything.
            }
        }

        private const string BaseMimePrefix = @"text/";
        private const string MimePrefix = BaseMimePrefix + @"x-";

        internal static ContentTypeImpl AddContentTypeFromMetadata(string contentTypeName, string mimeType, IEnumerable<string> baseTypes,
                                                                   IDictionary<string, ContentTypeImpl> nameToContentTypeBuilder,
                                                                   IDictionary<string, ContentTypeImpl> mimeTypeToContentTypeBuilder)
        {
            if (!string.IsNullOrEmpty(contentTypeName))
            {
                ContentTypeImpl type;
                if (!nameToContentTypeBuilder.TryGetValue(contentTypeName, out type))
                {
                    bool addToMimeTypeMap = false;
                    if (string.IsNullOrWhiteSpace(mimeType))
                    {
                        mimeType = MimePrefix + contentTypeName.ToLowerInvariant();
                    }
                    else if (mimeTypeToContentTypeBuilder.ContainsKey(mimeType))
                    {
                        mimeType = null;
                    }
                    else
                    {
                        addToMimeTypeMap = true;
                    }

                    type = new ContentTypeImpl(contentTypeName, mimeType, baseTypes);

                    nameToContentTypeBuilder.Add(contentTypeName, type);
                    if (addToMimeTypeMap)
                    {
                        mimeTypeToContentTypeBuilder.Add(mimeType, type);
                    }
                }
                else
                {
                    type.AddUnprocessedBaseTypes(baseTypes);
                }

                return type;
            }

            return null;
        }

        /// <summary>
        /// Checks whether the specified type is base type for another content type
        /// </summary>
        /// <param name="typeToCheck">The type to check for being a base type</param>
        /// <param name="derivedType">An out parameter to receive the first discovered derived type</param>
        /// <returns><c>True</c> if the given <paramref name="typeToCheck"/> content type is a base type</returns>
        private bool IsBaseType(ContentTypeImpl typeToCheck, out ContentTypeImpl derivedType)
        {
            derivedType = null;

            foreach (ContentTypeImpl type in this.maps.NameToContentTypeMap.Values)
            {
                if (type != typeToCheck)
                {
                    foreach (IContentType baseType in type.BaseTypes)
                    {
                        if (baseType == typeToCheck)
                        {
                            derivedType = type;
                            return true;
                        }
                    }
                }
            }

            return false;
        }

        #region IContentTypeRegistryService Members
        public IContentType GetContentType(string typeName)
        {
            if (string.IsNullOrWhiteSpace(typeName))
            {
                throw new ArgumentException(nameof(typeName));
            }

            this.BuildContentTypes();

            ContentTypeImpl contentType = null;
            this.maps.NameToContentTypeMap.TryGetValue(typeName, out contentType);

            return contentType;
        }

        public IContentType UnknownContentType
        {
            get { return ContentTypeRegistryImpl.UnknownContentTypeImpl; }
        }

        public IEnumerable<IContentType> ContentTypes
        {
            get
            {
                this.BuildContentTypes();
                var map = this.maps.NameToContentTypeMap;

                return map.Values;
            }
        }

        public IContentType AddContentType(string typeName, IEnumerable<string> baseTypeNames)
        {
            if (string.IsNullOrWhiteSpace(typeName))
            {
                throw new ArgumentException(nameof(typeName));
            }

            // This has the side effect of building the content types.
            if (this.GetContentType(typeName) != null)
            {
                // Cannot dynamically add a new content type if a content type with the same name already exists
                throw new ArgumentException(String.Format(System.Globalization.CultureInfo.CurrentUICulture, Strings.ContentTypeRegistry_CannotAddExistentType, typeName));
            }

            var oldMaps = Volatile.Read(ref this.maps);
            while (true)
            {
                var nameToContentTypeMap = new PseudoBuilder<string, ContentTypeImpl>(oldMaps.NameToContentTypeMap);
                var mimeTypeToContentTypeMap = new PseudoBuilder<string, ContentTypeImpl>(oldMaps.MimeTypeToContentTypeMap);

                var type = AddContentTypeFromMetadata(typeName, null, baseTypeNames,
                                                      nameToContentTypeMap, mimeTypeToContentTypeMap);

                type.ProcessBaseTypes(nameToContentTypeMap, mimeTypeToContentTypeMap);

                if (type.CheckForCycle(breakCycle: false))
                {
                    throw new InvalidOperationException(String.Format(System.Globalization.CultureInfo.CurrentUICulture, Strings.ContentTypeRegistry_CausesCycles, type.TypeName));
                }

                var newMaps = new MapCollection(nameToContentTypeMap.Source, mimeTypeToContentTypeMap.Source, oldMaps.FileExtensionToContentTypeMap, oldMaps.FileNameToContentTypeMap);
                var results = Interlocked.CompareExchange(ref this.maps, newMaps, oldMaps);
                if (results == oldMaps)
                {
                    return type;
                }

                // Two people tried to add content types simultaneously.
                oldMaps = results;
            }
        }

        public void RemoveContentType(string typeName)
        {
            if (string.IsNullOrWhiteSpace(typeName))
            {
                throw new ArgumentException(nameof(typeName));
            }

            this.BuildContentTypes();

            var oldMaps = Volatile.Read(ref this.maps);
            while (true)
            {
                ContentTypeImpl type;
                if (!oldMaps.NameToContentTypeMap.TryGetValue(typeName, out type))
                {
                    // No type == no type to remove;
                    return;
                }

                if (type == ContentTypeRegistryImpl.UnknownContentTypeImpl)
                {
                    // Check if the type to be removed is not the Unknown content type
                    throw new InvalidOperationException(Strings.ContentTypeRegistry_CannotRemoveTheUnknownType);
                }

                ContentTypeImpl derivedType;
                if (IsBaseType(type, out derivedType))
                {
                    // Check if the type is base type for another registered type
                    throw new InvalidOperationException(String.Format(System.Globalization.CultureInfo.CurrentUICulture, Strings.ContentTypeRegistry_CannotRemoveBaseType, type.TypeName, derivedType.TypeName));
                }

                // If there are file extensions using this content type we won't allow removing it
                if (this.maps.FileExtensionToContentTypeMap.Values.Any(c => c == type))
                {
                    // If there are file extensions using this content type we won't allow removing it
                    throw new InvalidOperationException(String.Format(System.Globalization.CultureInfo.CurrentUICulture, Strings.ContentTypeRegistry_CannotRemoveTypeUsedByFileExtensions, type.TypeName));
                }

                // If there are file extensions using this content type we won't allow removing it
                if (this.maps.FileNameToContentTypeMap.Values.Any(c => c == type))
                {
                    // If there are file extensions using this content type we won't allow removing it
                    throw new InvalidOperationException(String.Format(System.Globalization.CultureInfo.CurrentUICulture, Strings.ContentTypeRegistry_CannotRemoveTypeUsedByFileExtensions, type.TypeName));
                }

                var newMaps = new MapCollection(oldMaps.NameToContentTypeMap.Remove(typeName),
                                                (type.MimeType != null) ? oldMaps.MimeTypeToContentTypeMap.Remove(type.MimeType) : oldMaps.MimeTypeToContentTypeMap,
                                                oldMaps.FileExtensionToContentTypeMap, oldMaps.FileNameToContentTypeMap);
                var results = Interlocked.CompareExchange(ref this.maps, newMaps, oldMaps);
                if (results == oldMaps)
                {
                    return;
                }

                // Two people tried to remove content types simultaneously.
                oldMaps = results;
            }
        }
        #endregion

        #region IContentTypeRegistryService2 Members
        public string GetMimeType(IContentType type)
        {
            var typeImpl = type as ContentTypeImpl;
            if (typeImpl == null)
            {
                throw new ArgumentException(nameof(type));
            }
            else if (typeImpl == UnknownContentTypeImpl)
            {
                return null;
            }

            return typeImpl.MimeType;
        }

        public IContentType GetContentTypeForMimeType(string mimeType)
        {
            if (string.IsNullOrWhiteSpace(mimeType))
            {
                throw new ArgumentException(nameof(mimeType));
            }

            this.BuildContentTypes();

            ContentTypeImpl contentType = null;
            if (!this.maps.MimeTypeToContentTypeMap.TryGetValue(mimeType, out contentType))
            {
                if (mimeType.StartsWith(BaseMimePrefix))
                {
                    if (!(mimeType.StartsWith(MimePrefix) && this.maps.NameToContentTypeMap.TryGetValue(mimeType.Substring(MimePrefix.Length), out contentType)))
                    {
                        this.maps.NameToContentTypeMap.TryGetValue(mimeType.Substring(BaseMimePrefix.Length), out contentType);
                    }
                }
            }

            return contentType;
        }
        #endregion

        #region IFileExtensionRegistryService Members
        public IContentType GetContentTypeForExtension(string extension)
        {
            if (extension == null)
            {
                throw new ArgumentNullException(nameof(extension));
            }

            this.BuildContentTypes();

            ContentTypeImpl contentType = null;
            this.maps.FileExtensionToContentTypeMap.TryGetValue(RemoveExtensionDot(extension), out contentType);

            // TODO: should we return null if contentType is null?
            return contentType ?? ContentTypeRegistryImpl.UnknownContentTypeImpl;
        }

        public IEnumerable<string> GetExtensionsForContentType(IContentType contentType)
        {
            if (contentType == null)
            {
                throw new ArgumentNullException(nameof(contentType));
            }

            this.BuildContentTypes();

            // We don't expect this to be called on a perf critical thread so we can use the dictionary.
            foreach (var kvp in this.maps.FileExtensionToContentTypeMap)
            {
                if (contentType == kvp.Value)
                {
                    yield return kvp.Key;
                }
            }
        }

        public void AddFileExtension(string extension, IContentType contentType)
        {
            if (string.IsNullOrWhiteSpace(extension))
            {
                throw new ArgumentException(nameof(extension));
            }

            var contentTypeImpl = contentType as ContentTypeImpl;
            if ((contentTypeImpl == null) || (contentTypeImpl == UnknownContentTypeImpl))
            {
                throw new ArgumentException(nameof(contentType));
            }

            this.BuildContentTypes();
            extension = RemoveExtensionDot(extension);

            var oldMaps = Volatile.Read(ref this.maps);
            while (true)
            {
                ContentTypeImpl type;
                if (oldMaps.FileExtensionToContentTypeMap.TryGetValue(extension, out type))
                {
                    if (type != contentTypeImpl)
                    {
                        throw new InvalidOperationException
                                    (String.Format(System.Globalization.CultureInfo.CurrentUICulture,
                                        Strings.FileExtensionRegistry_NoMultipleContentTypes, extension));
                    }

                    return;
                }

                var newMaps = new MapCollection(oldMaps.NameToContentTypeMap, oldMaps.MimeTypeToContentTypeMap,
                                                oldMaps.FileExtensionToContentTypeMap.Add(extension, contentTypeImpl),
                                                oldMaps.FileNameToContentTypeMap);

                var results = Interlocked.CompareExchange(ref this.maps, newMaps, oldMaps);
                if (results == oldMaps)
                {
                    return;
                }

                // Two people tried to remove content types simultaneously.
                oldMaps = results;
            }
        }

        public void RemoveFileExtension(string extension)
        {
            if (extension == null)
            {
                throw new ArgumentNullException(nameof(extension));
            }

            this.BuildContentTypes();

            extension = RemoveExtensionDot(extension);

            var oldMaps = Volatile.Read(ref this.maps);
            while (true)
            {
                if (!oldMaps.FileExtensionToContentTypeMap.ContainsKey(extension))
                {
                    return;
                }

                var newMaps = new MapCollection(oldMaps.NameToContentTypeMap, oldMaps.MimeTypeToContentTypeMap,
                                                oldMaps.FileExtensionToContentTypeMap.Remove(extension),
                                                oldMaps.FileNameToContentTypeMap);

                var results = Interlocked.CompareExchange(ref this.maps, newMaps, oldMaps);
                if (results == oldMaps)
                {
                    return;
                }

                // Two people tried to remove content types simultaneously.
                oldMaps = results;
            }
        }
        #endregion

        #region IFileExtensionRegistryService2 Members
        public IContentType GetContentTypeForFileName(string fileName)
        {
            if (fileName == null)
            {
                throw new ArgumentNullException(nameof(fileName));
            }

            this.BuildContentTypes();

            ContentTypeImpl contentType = null;
            this.maps.FileNameToContentTypeMap.TryGetValue(fileName, out contentType);

            // TODO: should we return null if contentType is null?
            return contentType ?? ContentTypeRegistryImpl.UnknownContentTypeImpl;
        }

        public IContentType GetContentTypeForFileNameOrExtension(string name)
        {
            if (name == null)
            {
                throw new ArgumentNullException(nameof(name));
            }

            // No need to lock, we are calling locking public method.
            var fileNameContentType = this.GetContentTypeForFileName(name);

            // Attempt to use extension as fallback ContentType if file name isn't recognized.
            if (fileNameContentType == ContentTypeRegistryImpl.UnknownContentTypeImpl)
            {
                var extension = Path.GetExtension(name);

                if (!string.IsNullOrEmpty(extension))
                {
                    // No need to lock, we are calling locking public method.
                    return this.GetContentTypeForExtension(extension);
                }
            }

            return fileNameContentType;
        }

        public IEnumerable<string> GetFileNamesForContentType(IContentType contentType)
        {
            if (contentType == null)
            {
                throw new ArgumentNullException(nameof(contentType));
            }

            this.BuildContentTypes();

            // We don't expect this to be called on a perf critical thread so we can use the dictionary.
            foreach (var kvp in this.maps.FileNameToContentTypeMap)
            {
                if (contentType == kvp.Value)
                {
                    yield return kvp.Key;
                }
            }
        }

        public void AddFileName(string fileName, IContentType contentType)
        {
            if (string.IsNullOrWhiteSpace(fileName))
            {
                throw new ArgumentException(nameof(fileName));
            }

            var contentTypeImpl = contentType as ContentTypeImpl;
            if ((contentTypeImpl == null) || (contentTypeImpl == UnknownContentTypeImpl))
            {
                throw new ArgumentException(nameof(contentType));
            }

            this.BuildContentTypes();

            var oldMaps = Volatile.Read(ref this.maps);
            while (true)
            {
                ContentTypeImpl type;
                if (oldMaps.FileNameToContentTypeMap.TryGetValue(fileName, out type))
                {
                    if (type != contentTypeImpl)
                    {
                        throw new InvalidOperationException
                                    (String.Format(System.Globalization.CultureInfo.CurrentUICulture,
                                        Strings.FileExtensionRegistry_NoMultipleContentTypes, fileName));
                    }

                    return;
                }

                var newMaps = new MapCollection(oldMaps.NameToContentTypeMap, oldMaps.MimeTypeToContentTypeMap,
                                                oldMaps.FileExtensionToContentTypeMap,
                                                oldMaps.FileNameToContentTypeMap.Add(fileName, contentTypeImpl));

                var results = Interlocked.CompareExchange(ref this.maps, newMaps, oldMaps);
                if (results == oldMaps)
                {
                    return;
                }

                // Two people tried to remove content types simultaneously.
                oldMaps = results;
            }
        }

        public void RemoveFileName(string fileName)
        {
            if (fileName == null)
            {
                throw new ArgumentNullException(nameof(fileName));
            }

            this.BuildContentTypes();

            var oldMaps = Volatile.Read(ref this.maps);
            while (true)
            {
                if (!oldMaps.FileNameToContentTypeMap.ContainsKey(fileName))
                {
                    return;
                }

                var newMaps = new MapCollection(oldMaps.NameToContentTypeMap, oldMaps.MimeTypeToContentTypeMap,
                                                oldMaps.FileExtensionToContentTypeMap,
                                                oldMaps.FileNameToContentTypeMap.Remove(fileName));

                var results = Interlocked.CompareExchange(ref this.maps, newMaps, oldMaps);
                if (results == oldMaps)
                {
                    return;
                }

                // Two people tried to remove content types simultaneously.
                oldMaps = results;
            }
        }
        #endregion

        #region IFilePathRegistryService Members
        public IContentType GetContentTypeForPath(string filePath)
        {
            if (filePath == null)
            {
                throw new ArgumentNullException(nameof(filePath));
            }

            string fileName = Path.GetFileName(filePath);
            string extension = Path.GetExtension(filePath);
            var providers = OrderedFilePathToContentTypeProductions.Where(md =>
                (md.Metadata.FileExtension == null || md.Metadata.FileExtension.Equals(extension, StringComparison.OrdinalIgnoreCase)) &&
                (md.Metadata.FileName == null || md.Metadata.FileName.Equals(fileName, StringComparison.OrdinalIgnoreCase)));

            IContentType contentType = null;
            foreach(var curProvider in providers)
            {
                if (curProvider.Value.TryGetContentTypeForFilePath(filePath, out IContentType curContentType))
                {
                    contentType = curContentType;
                    break;
                }
            }

            return contentType ?? ContentTypeRegistryImpl.UnknownContentTypeImpl;
        }
        #endregion

        private static string RemoveExtensionDot(string extension)
        {
            if (extension.StartsWith("."))
            {
                return extension.TrimStart('.');
            }
            else
            {
                return extension;
            }
        }

        class MapCollection
        {
            public readonly static MapCollection Empty = new MapCollection();

            public readonly ImmutableDictionary<string, ContentTypeImpl> NameToContentTypeMap;
            public readonly ImmutableDictionary<string, ContentTypeImpl> MimeTypeToContentTypeMap;
            public readonly ImmutableDictionary<string, ContentTypeImpl> FileExtensionToContentTypeMap;
            public readonly ImmutableDictionary<string, ContentTypeImpl> FileNameToContentTypeMap;

            private MapCollection()
            {
                this.NameToContentTypeMap = ImmutableDictionary<string, ContentTypeImpl>.Empty.WithComparers(StringComparer.OrdinalIgnoreCase);
                this.MimeTypeToContentTypeMap = ImmutableDictionary<string, ContentTypeImpl>.Empty.WithComparers(StringComparer.Ordinal);
                this.FileExtensionToContentTypeMap = ImmutableDictionary<string, ContentTypeImpl>.Empty.WithComparers(StringComparer.OrdinalIgnoreCase);
                this.FileNameToContentTypeMap = ImmutableDictionary<string, ContentTypeImpl>.Empty.WithComparers(StringComparer.OrdinalIgnoreCase);
            }

            public MapCollection(ImmutableDictionary<string, ContentTypeImpl> nameToContentType, ImmutableDictionary<string, ContentTypeImpl> mimeTypeToContentTypeMap,
                                 ImmutableDictionary<string, ContentTypeImpl> fileExtensionToContentTypeMap, ImmutableDictionary<string, ContentTypeImpl> fileNameToContentTypeMap)
            {
                this.NameToContentTypeMap = nameToContentType;
                this.MimeTypeToContentTypeMap = mimeTypeToContentTypeMap;
                this.FileExtensionToContentTypeMap = fileExtensionToContentTypeMap;
                this.FileNameToContentTypeMap = fileNameToContentTypeMap;

#if DEBUG
                foreach (var c in nameToContentType.Values)
                {
                    Debug.Assert(c.IsCheckedForCycles);
                }
#endif
            }
        }

        class PseudoBuilder<K, V> : IDictionary<K, V>
        {
            public ImmutableDictionary<K, V> Source { get; private set; }

            public PseudoBuilder(ImmutableDictionary<K, V> source)
            {
                this.Source = source;
            }

            public void Add(K key, V value)
            {
                this.Source = this.Source.Add(key, value);
            }

            public bool ContainsKey(K key)
            {
                return this.Source.ContainsKey(key);
            }

            public bool TryGetValue(K key, out V value)
            {
                return this.Source.TryGetValue(key, out value);
            }

            #region NotImplemented
            public V this[K key] { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }

            public ICollection<K> Keys => throw new NotImplementedException();

            public ICollection<V> Values => throw new NotImplementedException();

            public int Count => throw new NotImplementedException();

            public bool IsReadOnly => throw new NotImplementedException();

            public void Add(KeyValuePair<K, V> item)
            {
                throw new NotImplementedException();
            }

            public void Clear()
            {
                throw new NotImplementedException();
            }

            public bool Contains(KeyValuePair<K, V> item)
            {
                throw new NotImplementedException();
            }

            public void CopyTo(KeyValuePair<K, V>[] array, int arrayIndex)
            {
                throw new NotImplementedException();
            }

            public IEnumerator<KeyValuePair<K, V>> GetEnumerator()
            {
                throw new NotImplementedException();
            }

            public bool Remove(K key)
            {
                throw new NotImplementedException();
            }

            public bool Remove(KeyValuePair<K, V> item)
            {
                throw new NotImplementedException();
            }

            IEnumerator IEnumerable.GetEnumerator()
            {
                throw new NotImplementedException();
            }
            #endregion
        }
    }
}