예제 #1
0
        internal InteractiveEvaluator(
            IContentType contentType,
            HostServices hostServices,
            IViewClassifierAggregatorService classifierAggregator,
            IInteractiveWindowCommandsFactory commandsFactory,
            ImmutableArray<IInteractiveWindowCommand> commands,
            string responseFilePath,
            string initialWorkingDirectory,
            string interactiveHostPath,
            Type replType)
        {
            Debug.Assert(responseFilePath == null || PathUtilities.IsAbsolute(responseFilePath));

            _contentType = contentType;
            _responseFilePath = responseFilePath;
            _workspace = new InteractiveWorkspace(this, hostServices);
            _contentTypeChangedHandler = new EventHandler<ContentTypeChangedEventArgs>(LanguageBufferContentTypeChanged);
            _classifierAggregator = classifierAggregator;
            _initialWorkingDirectory = initialWorkingDirectory;
            _commandsFactory = commandsFactory;
            _commands = commands;

            var hostPath = interactiveHostPath;
            _interactiveHost = new InteractiveHost(replType, hostPath, initialWorkingDirectory);
            _interactiveHost.ProcessStarting += ProcessStarting;
        }
        public static void SetLanguage(this IInteractiveWindow window, Guid languageServiceGuid, IContentType contentType)
        {
            VsInteractiveWindowEditorFactoryService.GetDispatcher(window).CheckAccess();

            var commandFilter = VsInteractiveWindowEditorFactoryService.GetCommandFilter(window);
            window.Properties[typeof(IContentType)] = contentType;
            commandFilter.firstLanguageServiceCommandFilter = null;
            var provider = commandFilter._oleCommandTargetProviders.OfContentType(contentType, commandFilter._contentTypeRegistry);
            if (provider != null)
            {
                var targetFilter = commandFilter.firstLanguageServiceCommandFilter ?? commandFilter.EditorServicesCommandFilter;
                var target = provider.GetCommandTarget(window.TextView, targetFilter);
                if (target != null)
                {
                    commandFilter.firstLanguageServiceCommandFilter = target;
                }
            }

            if (window.CurrentLanguageBuffer != null)
            {
                window.CurrentLanguageBuffer.ChangeContentType(contentType, null);
            }

            VsInteractiveWindowEditorFactoryService.SetEditorOptions(window.TextView.Options, languageServiceGuid);
        }
예제 #3
0
        public SystemSettingsTreeController()
        {
            Services = ApplicationContext.Current.Services;
            contentType_settings = Services.ContentTypeService.GetContentType("Setting");


        }
예제 #4
0
        public IVsInteractiveWindow CreateInteractiveWindow(
            IContentType contentType,
            string/*!*/ title,
            Guid languageServiceGuid,
            string replId
        ) {
            int curId = 0;

            InteractiveWindowInfo window;
            do {
                curId++;
                window = FindReplWindowInternal(curId);
            } while (window != null);

            foreach (var provider in _evaluators) {
                var evaluator = provider.GetEvaluator(replId);
                if (evaluator != null) {
                    string[] roles = evaluator.GetType().GetCustomAttributes(typeof(InteractiveWindowRoleAttribute), true)
                        .OfType<InteractiveWindowRoleAttribute>()
                        .Select(r => r.Name)
                        .ToArray();
                    window = CreateInteractiveWindowInternal(evaluator, contentType, roles, curId, title, languageServiceGuid, replId);

                    return window.Window;
                }
            }

            throw new InvalidOperationException(String.Format("ReplId {0} was not provided by an IInteractiveWindowProvider", replId));
        }
예제 #5
0
        public static Content CreateAllTypesContent(IContentType contentType, string name, int parentId)
        {
            var content = new Content("Random Content Name", parentId, contentType) { Language = "en-US", Level = 1, SortOrder = 1, CreatorId = 0, WriterId = 0 };

            content.SetValue("isTrue", true);
            content.SetValue("number", 42);
            content.SetValue("bodyText", "Lorem Ipsum Body Text Test");
            content.SetValue("singleLineText", "Single Line Text Test");
            content.SetValue("multilineText", "Multiple lines \n in one box");
            content.SetValue("upload", "/media/1234/koala.jpg");
            content.SetValue("label", "Non-editable label");
            content.SetValue("dateTime", DateTime.Now.AddDays(-20));
            content.SetValue("colorPicker", "black");
            content.SetValue("folderBrowser", "");
            content.SetValue("ddlMultiple", "1234,1235");
            content.SetValue("rbList", "random");
            content.SetValue("date", DateTime.Now.AddDays(-10));
            content.SetValue("ddl", "1234");
            content.SetValue("chklist", "randomc");
            content.SetValue("contentPicker", 1090);
            content.SetValue("mediaPicker", 1091);
            content.SetValue("memberPicker", 1092);
            content.SetValue("simpleEditor", "This is simply edited");
            content.SetValue("ultimatePicker", "1234,1235");
            content.SetValue("relatedLinks", "<links><link title=\"google\" link=\"http://google.com\" type=\"external\" newwindow=\"0\" /></links>");
            content.SetValue("tags", "this,is,tags");
            content.SetValue("macroContainer", "");
            content.SetValue("imgCropper", "");

            return content;
        }
 public IVsTextBuffer CreateVsTextBufferAdapter(OLE.Interop.IServiceProvider serviceProvider, IContentType contentType)
 {
     VsTextBufferMock tb = new VsTextBufferMock(contentType);
     _textBufferAdapters[tb.TextBuffer] = tb;
     _vsTextBufferAdapters[tb] = tb.TextBuffer;
     return tb;
 }
예제 #7
0
        internal InteractiveEvaluator(
            IContentType contentType,
            HostServices hostServices,
            IViewClassifierAggregatorService classifierAggregator,
            IInteractiveWindowCommandsFactory commandsFactory,
            ImmutableArray<IInteractiveWindowCommand> commands,
            string responseFilePath,
            string initialWorkingDirectory,
            string interactiveHostPath,
            Type replType)
        {
            Debug.Assert(responseFilePath == null || PathUtilities.IsAbsolute(responseFilePath));

            _contentType = contentType;
            _responseFilePath = responseFilePath;
            _workspace = new InteractiveWorkspace(this, hostServices);
            _contentTypeChangedHandler = new EventHandler<ContentTypeChangedEventArgs>(LanguageBufferContentTypeChanged);
            _classifierAggregator = classifierAggregator;
            _initialWorkingDirectory = initialWorkingDirectory;
            _commandsFactory = commandsFactory;
            _commands = commands;

            // The following settings will apply when the REPL starts without .rsp file.
            // They are discarded once the REPL is reset.
            ReferenceSearchPaths = ImmutableArray<string>.Empty;
            SourceSearchPaths = ImmutableArray<string>.Empty;
            WorkingDirectory = initialWorkingDirectory;
            var metadataService = _workspace.CurrentSolution.Services.MetadataService;
            _metadataReferenceResolver = CreateMetadataReferenceResolver(metadataService, ReferenceSearchPaths, _initialWorkingDirectory);
            _sourceReferenceResolver = CreateSourceReferenceResolver(SourceSearchPaths, _initialWorkingDirectory);

            _interactiveHost = new InteractiveHost(replType, interactiveHostPath, initialWorkingDirectory);
            _interactiveHost.ProcessStarting += ProcessStarting;
        }
		public static IContentType GetContentType(this IContentTypeRegistryService contentTypeRegistryService, IContentType contentType, string contentTypeString) {
			if (contentType != null)
				return contentType;
			if (contentTypeString != null)
				return contentTypeRegistryService.GetContentType(contentTypeString);
			return null;
		}
        private int ExecuteAppCommand(ref Guid pguidCmdGroup, uint commandId, uint executeInformation, IntPtr pvaIn, IntPtr pvaOut, ITextBuffer subjectBuffer, IContentType contentType)
        {
            int result = VSConstants.S_OK;
            var guidCmdGroup = pguidCmdGroup;
            Action executeNextCommandTarget = () =>
            {
                result = NextCommandTarget.Exec(ref guidCmdGroup, commandId, executeInformation, pvaIn, pvaOut);
            };

            switch ((VSConstants.AppCommandCmdID)commandId)
            {
                case VSConstants.AppCommandCmdID.BrowserBackward:
                    ExecuteBrowserBackward(subjectBuffer, contentType, executeNextCommandTarget);
                    break;

                case VSConstants.AppCommandCmdID.BrowserForward:
                    ExecuteBrowserForward(subjectBuffer, contentType, executeNextCommandTarget);
                    break;

                default:
                    return NextCommandTarget.Exec(ref pguidCmdGroup, commandId, executeInformation, pvaIn, pvaOut);
            }

            return result;
        }
예제 #10
0
 private void Initialize(string targetFileContents, string mapFileContents, string directory, IContentType contentType)
 {
     _contentType = contentType;
     _parser = CssParserLocator.FindComponent(_contentType).CreateParser();
     _directory = directory;
     PopulateMap(targetFileContents, mapFileContents); // Begin two-steps initialization.
 }
예제 #11
0
        private static bool CompareAllowedTemplates(IContentType contentType, DocumentTypeAttribute docTypeAttr, Type typeDocType)
        {
            List<ITemplate> allowedTemplates = DocumentTypeManager.GetAllowedTemplates(docTypeAttr, typeDocType);

            IEnumerable<ITemplate> existingTemplates = contentType.AllowedTemplates;

            if (allowedTemplates.Count != existingTemplates.Count())
            {
                return false;
            }

            foreach (Template template in allowedTemplates)
            {
                if (!existingTemplates.Any(t => t.Alias == template.Alias))
                {
                    return false;
                }
            }

            ITemplate defaultTemplate = DocumentTypeManager.GetDefaultTemplate(docTypeAttr, typeDocType, allowedTemplates);

            if (defaultTemplate != null)
            {
                return (contentType.DefaultTemplate.Id == defaultTemplate.Id);
            }

            if (allowedTemplates.Count == 1)
            {
                return (contentType.DefaultTemplate.Id == allowedTemplates.First().Id);
            }

            return true;
        }
예제 #12
0
 public EditorTextFactoryService(
         ITextBufferFactoryService textBufferFactoryService,
         IContentTypeRegistryService contentTypeRegistryService)
 {
     _textBufferFactory = textBufferFactoryService;
     _unknownContentType = contentTypeRegistryService.UnknownContentType;
 }
예제 #13
0
 static BlogFacade()
 {
     if (_blogContentType == null)
     {
         _blogContentType = _contentTypeService.GetContentType(BLOG_POST_CONTENT_TYPE_ALIAS);
     }
 }
예제 #14
0
        public IReplWindow CreateReplWindow(IContentType contentType, string/*!*/ title, Guid languageServiceGuid, string replId)
        {
            int curId = 0;

            ReplWindow window;
            do {
                curId++;
                window = FindReplWindowInternal(curId);
            } while (window != null);

            foreach (var provider in _evaluators) {
                var evaluator = provider.GetEvaluator(replId);
                if (evaluator != null) {
                    string[] roles = provider.GetType().GetCustomAttributes(typeof(ReplRoleAttribute), true).Select(r => ((ReplRoleAttribute)r).Name).ToArray();
                    window = CreateReplWindowInternal(evaluator, contentType, roles, curId, title, languageServiceGuid, replId);
                    if ((null == window) || (null == window.Frame)) {
                        throw new NotSupportedException(Resources.CanNotCreateWindow);
                    }

                    return window;
                }
            }

            throw new InvalidOperationException(String.Format("ReplId {0} was not provided by an IReplWindowProvider", replId));
        }
예제 #15
0
 private void Initialize(string targetFileName, string mapFileName, IContentType contentType)
 {
     _contentType = contentType;
     _parser = CssParserLocator.FindComponent(_contentType).CreateParser();
     _directory = Path.GetDirectoryName(mapFileName);
     PopulateMap(targetFileName, mapFileName); // Begin two-steps initialization.
 }
예제 #16
0
        public JadeClassifierProvider(IClassificationTypeRegistryService registryService,   
            ITextBufferFactoryService bufferFact,
            IContentTypeRegistryService contentTypeService,
            [ImportMany(typeof(ITaggerProvider))]Lazy<ITaggerProvider, TaggerProviderMetadata>[] taggerProviders,
            [ImportMany(typeof(IClassifierProvider))]Lazy<IClassifierProvider, IClassifierProviderMetadata>[] classifierProviders) {
            ClassificationRegistryService = registryService;
            BufferFactoryService = bufferFact;
            JsContentType = contentTypeService.GetContentType(NodejsConstants.JavaScript);
            CssContentType = contentTypeService.GetContentType(NodejsConstants.CSS);

            var jsTagger = taggerProviders.Where(
                provider =>
                    provider.Metadata.ContentTypes.Contains(NodejsConstants.JavaScript) &&
                    provider.Metadata.TagTypes.Any(tagType => tagType.IsSubclassOf(typeof(ClassificationTag)))
            ).FirstOrDefault();
            if (JsTaggerProvider != null) {
                JsTaggerProvider = jsTagger.Value;
            }

            var cssTagger = classifierProviders.Where(
                provider => provider.Metadata.ContentTypes.Any(x => x.Equals("css", StringComparison.OrdinalIgnoreCase))
            ).FirstOrDefault();
            if (cssTagger != null) {
                CssClassifierProvider = cssTagger.Value;
            }
        }
예제 #17
0
        /// <summary>
        /// Constructor for creating a Content object
        /// </summary>
        /// <param name="name">Name of the content</param>
        /// <param name="parentId">Id of the Parent content</param>
        /// <param name="contentType">ContentType for the current Content object</param>
        /// <param name="properties">Collection of properties</param>
        public Content(string name, int parentId, IContentType contentType, PropertyCollection properties) 
			: base(name, parentId, contentType, properties)
        {
            Mandate.ParameterNotNull(contentType, "contentType");

            _contentType = contentType;
        }
예제 #18
0
 private static void MapComposition(IContentType umbracoContentType, ContentType type)
 {
     type.Composition = umbracoContentType.ContentTypeComposition
         .Where(cmp => cmp.Id != umbracoContentType.ParentId)
         .Select(MapContentTypeBase)
         .ToList();
 }
예제 #19
0
		public AnyTextStructureNavigator(ITextBuffer textBuffer, IContentType contentType) {
			if (textBuffer == null)
				throw new ArgumentNullException(nameof(textBuffer));
			if (contentType == null)
				throw new ArgumentNullException(nameof(contentType));
			this.textBuffer = textBuffer;
			ContentType = contentType;
		}
 public IEnumerable<ParserConfiguration> GetParsers(IContentType contentType)
 {
     foreach (var entry in Configuration) {
         if (entry.ContentType.Equals(contentType.TypeName, StringComparison.OrdinalIgnoreCase)) {
             yield return entry.Configuration;
         }
     }
 }
예제 #21
0
        public async static Task<CssSourceMap> Create(string targetFileContents, string mapFileContents, string directory, IContentType contentType)
        {
            CssSourceMap map = new CssSourceMap();

            await Task.Run(() => map.Initialize(targetFileContents, mapFileContents, directory, contentType));

            return map;
        }
예제 #22
0
 internal static InteractiveSmartIndenter Create(
     IEnumerable<Lazy<ISmartIndentProvider, ContentTypeMetadata>> smartIndenterProviders,
     IContentType contentType,
     ITextView view)
 {
     var provider = GetProvider(smartIndenterProviders, contentType);
     return (provider == null) ? null : new InteractiveSmartIndenter(contentType, view, provider.Item2.Value);
 }
예제 #23
0
 public MockTextBuffer(string content, IContentType contentType, string filename = null) {
     _snapshot = new MockTextSnapshot(this, content);
     _contentType = contentType;
     if (filename == null) {
         filename = Path.Combine(TestData.GetTempPath(), Path.GetRandomFileName(), "file.py");
     }
     Properties[typeof(ITextDocument)] = new MockTextDocument(this, filename);
 }
        private async static Task MinifyFile(IContentType contentType, string sourcePath, string minPath, IMinifierSettings settings)
        {
            IFileMinifier minifier = Mef.GetImport<IFileMinifier>(contentType);
            bool changed = await minifier.MinifyFile(sourcePath, minPath);

            if (settings.GzipMinifiedFiles && (changed || !File.Exists(minPath + ".gzip")))
                FileHelpers.GzipFile(minPath);
        }
        private static string SortProperties(string text, IContentType contentType)
        {
            Sorter sorter = new Sorter();

            if (contentType.IsOfType("LESS"))
                return sorter.SortLess(text);

            return sorter.SortStyleSheet(text);
        }
예제 #26
0
        public void ChangeContentType(IContentType newContentType, object editTag)
        {
            var before = ContentType;

            ContentType = newContentType;

            if (ContentTypeChanged != null)
                ContentTypeChanged(this, new ContentTypeChangedEventArgs(CurrentSnapshot, CurrentSnapshot, before, newContentType, new object()));
        }
예제 #27
0
        // Content type

        private static object CreateContentType(IContentType contentType)
        {
            return new
            {
                id = contentType.Id,
                name = contentType.DisplayName,
                category = contentType.Category
            };
        }
예제 #28
0
        protected CompilerRunnerBase(IContentType contentType)
        {
            Mef.SatisfyImportsOnce(this);
            SourceContentType = contentType;
            TargetContentType = FileExtensionRegistry.GetContentTypeForExtension(TargetExtension.TrimEnd('.'));

            _listeners = Mef.GetAllImports<IFileSaveListener>(TargetContentType);
            Settings = WESettings.Instance.ForContentType<ICompilerInvocationSettings>(contentType);
        }
예제 #29
0
 public ILanguage TryCreateLanguage(IContentType contentType)
 {
     foreach ( ILanguage lang in Languages ) {
     if ( lang.MatchesContentType(contentType) ) {
       return lang;
     }
       }
       return defaultLang;
 }
예제 #30
0
        public MarkdownMenu(DTE2 dte, OleMenuCommandService mcs)
        {
            Mef.SatisfyImportsOnce(this);
            _contentType = ContentTypes.GetContentType("Markdown");
            _extensions = FileExtensionRegistry.GetFileExtensionSet(_contentType);

            _dte = dte;
            _mcs = mcs;
        }
예제 #31
0
        public XElement Serialize(IContentType contentType)
        {
            var info = new XElement("Info",
                                    new XElement("Name", contentType.Name),
                                    new XElement("Alias", contentType.Alias),
                                    new XElement("Key", contentType.Key),
                                    new XElement("Icon", contentType.Icon),
                                    new XElement("Thumbnail", contentType.Thumbnail),
                                    new XElement("Description", contentType.Description),
                                    new XElement("AllowAtRoot", contentType.AllowedAsRoot.ToString()),
                                    new XElement("IsListView", contentType.IsContainer.ToString()),
                                    new XElement("IsElement", contentType.IsElement.ToString()),
                                    new XElement("Variations", contentType.Variations.ToString()));

            var masterContentType = contentType.ContentTypeComposition.FirstOrDefault(x => x.Id == contentType.ParentId);

            if (masterContentType != null)
            {
                info.Add(new XElement("Master", masterContentType.Alias));
            }

            var compositionsElement = new XElement("Compositions");
            var compositions        = contentType.ContentTypeComposition;

            foreach (var composition in compositions)
            {
                compositionsElement.Add(new XElement("Composition", composition.Alias));
            }
            info.Add(compositionsElement);

            var allowedTemplates = new XElement("AllowedTemplates");

            foreach (var template in contentType.AllowedTemplates)
            {
                allowedTemplates.Add(new XElement("Template", template.Alias));
            }
            info.Add(allowedTemplates);

            if (contentType.DefaultTemplate != null && contentType.DefaultTemplate.Id != 0)
            {
                info.Add(new XElement("DefaultTemplate", contentType.DefaultTemplate.Alias));
            }
            else
            {
                info.Add(new XElement("DefaultTemplate", ""));
            }

            var structure = new XElement("Structure");

            foreach (var allowedType in contentType.AllowedContentTypes)
            {
                structure.Add(new XElement("DocumentType", allowedType.Alias));
            }

            var genericProperties = new XElement("GenericProperties", SerializePropertyTypes(contentType.PropertyTypes, contentType.PropertyGroups)); // actually, all of them

            var tabs = new XElement("Tabs", SerializePropertyGroups(contentType.PropertyGroups));                                                     // TODO Rename to PropertyGroups

            var xml = new XElement("DocumentType",
                                   info,
                                   structure,
                                   genericProperties,
                                   tabs);

            var folderNames = string.Empty;
            var folderKeys  = string.Empty;

            //don't add folders if this is a child doc type
            if (contentType.Level != 1 && masterContentType == null)
            {
                //get URL encoded folder names
                var folders = _contentTypeService.GetContainers(contentType)
                              .OrderBy(x => x.Level);

                folderNames = string.Join("/", folders.Select(x => WebUtility.UrlEncode(x.Name)).ToArray());
                folderKeys  = string.Join("/", folders.Select(x => x.Key).ToArray());
            }

            if (string.IsNullOrWhiteSpace(folderNames) == false)
            {
                xml.Add(new XAttribute("Folders", folderNames));
                xml.Add(new XAttribute("FolderKeys", folderKeys));
            }


            return(xml);
        }
예제 #32
0
 public CurrentContent(DocumentViewerContent content, IContentType contentType)
 {
     this.Content     = content;
     this.contentType = contentType;
 }
예제 #33
0
 ReplOptions(ITextViewOptionsGroup group, IContentType contentType, Guid guid, string languageName)
     : base(group, contentType)
 {
     Guid         = guid;
     LanguageName = languageName;
 }
예제 #34
0
 public static bool IsResJSON(this IContentType contentType)
 {
     return(contentType.IsOfType("ResJSON"));
 }
예제 #35
0
        public async static Task <CssSourceMap> Create(string targetFileContents, string mapFileContents, string directory, IContentType contentType)
        {
            CssSourceMap map = new CssSourceMap();

            map.MapNodes = Enumerable.Empty <CssSourceMapNode>();
            var settings = WESettings.Instance.ForContentType <ICssSourceMapSettings>(contentType);

            if (settings != null && settings.ProcessSourceMapsForEditorEnhancements)
            {
                await Task.Run(() => map.Initialize(targetFileContents, mapFileContents, directory, contentType));
            }

            return(map);
        }
예제 #36
0
 public static bool IsVisualBasic(this IContentType contentType)
 {
     return(contentType.IsOfType("Basic"));
 }
예제 #37
0
 public IWpfTextView CreateTextView(IContentType contentType, params string[] lines)
 {
     return(_vimEditorHost.CreateTextView(contentType, lines));
 }
예제 #38
0
 /// <summary>
 /// Does this IContentType represent C#
 /// </summary>
 public static bool IsCSharp(this IContentType contentType)
 {
     return(contentType.IsOfType(VsVimConstants.CSharpContentType));
 }
예제 #39
0
 /// <summary>
 /// Does this IContentType represent C++
 /// </summary>
 public static bool IsCPlusPlus(this IContentType contentType)
 {
     return(contentType.IsOfType(VsVimConstants.CPlusPlusContentType));
 }
예제 #40
0
 public static bool IsFSharp(this IContentType contentType)
 {
     return(contentType.IsOfType("F#"));
 }
예제 #41
0
 public ITextBuffer CreateTextBuffer(TextReader reader, IContentType contentType)
 {
     return(CreateTextBuffer(reader, contentType, -1, "legacy"));
 }
        public bool IsCompletionSupported(IContentType contentType) => CompletionAvailability.IsAvailable(contentType, roles: null);                                       // This will call HasCompletionProviders among doing other checks

        public bool IsCompletionSupported(IContentType contentType, ITextViewRoleSet textViewRoleSet) => CompletionAvailability.IsAvailable(contentType, textViewRoleSet); // This will call HasCompletionProviders among doing other checks
 public ITextBuffer Clone(SourceText sourceText, IContentType contentType) => throw new NotImplementedException();
        public ITextDocument CreateAndLoadTextDocument(string filePath, IContentType contentType, bool attemptUtf8Detection, out bool characterSubstitutionsOccurred)
        {
            if (filePath == null)
            {
                throw new ArgumentNullException(nameof(filePath));
            }

            if (contentType == null)
            {
                throw new ArgumentNullException(nameof(contentType));
            }

            characterSubstitutionsOccurred = false;

            Encoding    chosenEncoding = null;
            ITextBuffer buffer         = null;
            DateTime    lastModified;
            long        fileSize;

            // select matching detectors without instantiating any
            var detectors = ExtensionSelector.SelectMatchingExtensions(OrderedEncodingDetectors, contentType);

            using (Stream stream = OpenFile(filePath, out lastModified, out fileSize))
            {
                // First, look for a byte order marker and let the encoding detecters
                // suggest encodings.
                chosenEncoding = EncodedStreamReader.DetectEncoding(stream, detectors, GuardedOperations);

                // If that didn't produce a result, tentatively try to open as UTF 8.
                if (chosenEncoding == null && attemptUtf8Detection)
                {
                    try
                    {
                        var detectorEncoding = new ExtendedCharacterDetector();

                        using (StreamReader reader = new EncodedStreamReader.NonStreamClosingStreamReader(stream, detectorEncoding, false))
                        {
                            buffer = ((ITextBufferFactoryService2)BufferFactoryService).CreateTextBuffer(reader, contentType, fileSize, filePath);
                            characterSubstitutionsOccurred = false;
                        }

                        if (detectorEncoding.DecodedExtendedCharacters)
                        {
                            // Valid UTF-8 but has bytes that are not merely ASCII.
                            chosenEncoding = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);
                        }
                        else
                        {
                            // Valid UTF8 but no extended characters, so it's valid ASCII.
                            // We don't use ASCII here because of the following scenario:
                            // The user with a non-ENU system encoding opens a code file with ASCII-only contents
                            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                            {
                                chosenEncoding = DefaultEncoding;
                            }
                            else
                            {
                                // To get to this line, it means file doesn't have BOM
                                // On Windows DefaultEncoding is "ASCII" which doesn't have BOM
                                // On non-Windows systems DefaultEncoding is UTF8 which emits BOM on save
                                // which is something we don't want(on file that didn't have BOM to save BOM)
                                // So instead we use "new UTF8Encoding (encoderShouldEmitUTF8Identifier: false)", which means don't emit BOM when saving.
                                chosenEncoding = UTF8WithoutBOM;
                            }
                        }
                    }
                    catch (DecoderFallbackException)
                    {
                        // Not valid UTF-8.
                        // Proceed to the next if block to try the system's default codepage.
                        Debug.Assert(buffer == null);
                        buffer          = null;
                        stream.Position = 0;
                    }
                }

                Debug.Assert(buffer == null || chosenEncoding != null);

                // If all else didn't work, use system's default encoding.
                if (chosenEncoding == null)
                {
                    chosenEncoding = DefaultEncoding;
                }

                if (buffer == null)
                {
                    var fallbackDetector = new FallbackDetector(chosenEncoding.DecoderFallback);
                    var modifiedEncoding = (Encoding)chosenEncoding.Clone();
                    modifiedEncoding.DecoderFallback = fallbackDetector;

                    Debug.Assert(stream.Position == 0);

                    using (StreamReader reader = new EncodedStreamReader.NonStreamClosingStreamReader(stream, modifiedEncoding, detectEncodingFromByteOrderMarks: false))
                    {
                        Debug.Assert(chosenEncoding.CodePage == reader.CurrentEncoding.CodePage);
                        buffer = ((ITextBufferFactoryService2)BufferFactoryService).CreateTextBuffer(reader, contentType, fileSize, filePath);
                    }

                    characterSubstitutionsOccurred = fallbackDetector.FallbackOccurred;
                }
            }

            TextDocument textDocument = new TextDocument(buffer, filePath, lastModified, this, chosenEncoding, attemptUtf8Detection: attemptUtf8Detection);

            RaiseTextDocumentCreated(textDocument);

            return(textDocument);
        }
예제 #45
0
        void InitializeOptions(IWpfTextView textView, IContentType beforeContentType, IContentType afterContentType, bool force)
        {
            var oldColl = GetCollection(beforeContentType);
            var newColl = GetCollection(afterContentType);

            if (!force && oldColl == newColl)
            {
                return;
            }

            newColl.InitializeOptions(textView);
        }
예제 #46
0
        public void RaiseNewContentEvent(IDocumentViewer documentViewer, DocumentViewerContent content, IContentType contentType)
        {
            if (documentViewer == null)
            {
                throw new ArgumentNullException(nameof(documentViewer));
            }
            if (content == null)
            {
                throw new ArgumentNullException(nameof(content));
            }
            if (contentType == null)
            {
                throw new ArgumentNullException(nameof(contentType));
            }
            var e = new DocumentViewerGotNewContentEventArgs(documentViewer, content, contentType);

            NotifyListeners(e);
            GotNewContent?.Invoke(this, e);
        }
        public ITextDocument CreateAndLoadTextDocument(string filePath, IContentType contentType)
        {
            bool unused;

            return(CreateAndLoadTextDocument(filePath, contentType, attemptUtf8Detection: true, characterSubstitutionsOccurred: out unused));
        }
예제 #48
0
        public ActionResult RenewalFund([Bind(Prefix = "renewalViewModel")] RenewalFundViewModel model)
        {
            ResponseModel response = new ResponseModel();
            IMember       member   = Services.MemberService.GetById(Members.GetCurrentMemberId());

            //旧的交易记录
            IContent oldContent = Services.ContentService.GetById(model.CurrentPayId);
            //旧的产品
            IContent oldProduct = Services.ContentService.GetById(oldContent.GetValue <int>("buyproduct"));

            if (model.RenewalFundId == -1)
            {
                response.Success     = true;
                response.Msg         = "恭喜您已经成功解约,到期将余额返回到您账户余额";
                response.RedirectUrl = "/memberinfo";
                System.Threading.Tasks.Task.Factory.StartNew(() =>
                {
                    //member:ter:tplid
                    Dictionary <string, string> dic = new Dictionary <string, string>();
                    dic.Add("{{name}}", member.Name);
                    dic.Add("{{product}}", oldProduct.GetValue <string>("title"));
                    dic.Add("{{start}}", oldContent.GetValue <DateTime>("rechargeDateTime").ToString("yyyy-MM-dd HH:mm:ss"));
                    dic.Add("{{end}}", oldContent.GetValue <DateTime>("expirationtime").ToString("yyyy-MM-dd HH:mm:ss"));
                    Helpers.SendmailHelper.SendEmail(member.Username, "member:ter:tplid", dic);
                    dic.Add("{{option}}", "到期解约");
                    string manageremail = SystemSettingsHelper.GetSystemSettingsByKey("manager:email");
                    Helpers.SendmailHelper.SendEmail(manageremail, "manager:ter:tplid", dic);
                });
            }
            else
            {
                //续约的产品
                IContent product = Services.ContentService.GetById(model.RenewalFundId);
                //新的交易记录
                DateTime     start   = oldContent.GetValue <DateTime>("expirationtime").AddDays(1);
                DateTime     end     = start.AddMonths(product.GetValue <int>("cycle"));
                IContentType ct      = ApplicationContext.Services.ContentTypeService.GetContentType("PayRecords");
                IContent     content = ApplicationContext.Services.ContentService.CreateContent("无用户名", ct.Id, "PayRecords");

                content.SetValue("username", member.Name);
                content.Name = member.Email;
                content.SetValue("email", member.Email);
                content.SetValue("memberPicker", member.Id);
                content.SetValue("buyproduct", product.Id);
                content.SetValue("mobilePhone", member.GetValue <string>("tel"));
                content.SetValue("memberPicker", member.Id.ToString());
                content.SetValue("amountCny", oldContent.GetValue <string>("amountCny"));
                content.SetValue("rechargeDateTime", start.ToString("yyyy-MM-dd HH:mm:ss"));
                content.SetValue("expirationtime", end.ToString("yyyy-MM-dd HH:mm:ss"));
                content.SetValue("payBillno", "续约订单:" + oldContent.GetValue <string>("payBillno"));
                content.SetValue("isdeposit", true);
                content.SetValue("isexpired", false);
                Services.ContentService.Save(content);

                response.Success     = true;
                response.Msg         = "恭喜你已经完成自动续约!请查收邮件";
                response.IsRedirect  = true;
                response.RedirectUrl = "/memberinfo";
                //发送邮件
                System.Threading.Tasks.Task.Factory.StartNew(() =>
                {
                    //member:renewal:tplid
                    Dictionary <string, string> dic = new Dictionary <string, string>();
                    dic.Add("{{name}}", member.Name);
                    dic.Add("{{oldproduct}}", oldProduct.GetValue <string>("title"));
                    dic.Add("{{newproduct}}", product.GetValue <string>("title"));
                    dic.Add("{{start}}", start.ToString("yyyy-MM-dd HH:mm:ss"));
                    dic.Add("{{end}}", end.ToString("yyyy-MM-dd HH:mm:ss"));
                    Helpers.SendmailHelper.SendEmail(member.Username, "member:renewal:tplid", dic);
                    dic.Add("{{option}}", "自动续约");
                    string manageremail = SystemSettingsHelper.GetSystemSettingsByKey("manager:email");
                    Helpers.SendmailHelper.SendEmail(manageremail, "manager:renewal:tplid", dic);
                });
            }
            return(Json(response, JsonRequestBehavior.AllowGet));
        }
예제 #49
0
 public ITextBuffer CreateTextBuffer(IContentType contentType, params string[] lines)
 {
     return(_vimEditorHost.CreateTextBuffer(contentType, lines));
 }
예제 #50
0
 public static bool IsHTMLXProjection(this IContentType contentType)
 {
     return(contentType.IsOfType("HTMLXProjection"));
 }
예제 #51
0
        public XElement Serialize(IContentType contentType)
        {
            var info = new XElement("Info",
                                    new XElement("Name", contentType.Name),
                                    new XElement("Alias", contentType.Alias),
                                    new XElement("Icon", contentType.Icon),
                                    new XElement("Thumbnail", contentType.Thumbnail),
                                    new XElement("Description", contentType.Description),
                                    new XElement("AllowAtRoot", contentType.AllowedAsRoot.ToString()),
                                    new XElement("IsListView", contentType.IsContainer.ToString()),
                                    new XElement("IsElement", contentType.IsElement.ToString()),
                                    new XElement("Variations", contentType.Variations.ToString()));

            var masterContentType = contentType.ContentTypeComposition.FirstOrDefault(x => x.Id == contentType.ParentId);

            if (masterContentType != null)
            {
                info.Add(new XElement("Master", masterContentType.Alias));
            }

            var compositionsElement = new XElement("Compositions");
            var compositions        = contentType.ContentTypeComposition;

            foreach (var composition in compositions)
            {
                compositionsElement.Add(new XElement("Composition", composition.Alias));
            }
            info.Add(compositionsElement);

            var allowedTemplates = new XElement("AllowedTemplates");

            foreach (var template in contentType.AllowedTemplates)
            {
                allowedTemplates.Add(new XElement("Template", template.Alias));
            }
            info.Add(allowedTemplates);

            if (contentType.DefaultTemplate != null && contentType.DefaultTemplate.Id != 0)
            {
                info.Add(new XElement("DefaultTemplate", contentType.DefaultTemplate.Alias));
            }
            else
            {
                info.Add(new XElement("DefaultTemplate", ""));
            }

            var structure = new XElement("Structure");

            foreach (var allowedType in contentType.AllowedContentTypes)
            {
                structure.Add(new XElement("DocumentType", allowedType.Alias));
            }

            var genericProperties = new XElement("GenericProperties"); // actually, all of them

            foreach (var propertyType in contentType.PropertyTypes)
            {
                var definition = _dataTypeService.GetDataType(propertyType.DataTypeId);

                var propertyGroup = propertyType.PropertyGroupId == null // true generic property
                    ? null
                    : contentType.PropertyGroups.FirstOrDefault(x => x.Id == propertyType.PropertyGroupId.Value);

                var genericProperty = new XElement("GenericProperty",
                                                   new XElement("Name", propertyType.Name),
                                                   new XElement("Alias", propertyType.Alias),
                                                   new XElement("Type", propertyType.PropertyEditorAlias),
                                                   new XElement("Definition", definition.Key),
                                                   new XElement("Tab", propertyGroup == null ? "" : propertyGroup.Name),
                                                   new XElement("SortOrder", propertyType.SortOrder),
                                                   new XElement("Mandatory", propertyType.Mandatory.ToString()),
                                                   propertyType.MandatoryMessage != null ? new XElement("MandatoryMessage", propertyType.MandatoryMessage) : null,
                                                   propertyType.ValidationRegExp != null ? new XElement("Validation", propertyType.ValidationRegExp) : null,
                                                   propertyType.ValidationRegExpMessage != null ? new XElement("ValidationRegExpMessage", propertyType.ValidationRegExpMessage) : null,
                                                   propertyType.Description != null ? new XElement("Description", new XCData(propertyType.Description)) : null,
                                                   new XElement("Variations", propertyType.Variations.ToString()));

                genericProperties.Add(genericProperty);
            }

            var tabs = new XElement("Tabs");

            foreach (var propertyGroup in contentType.PropertyGroups)
            {
                var tab = new XElement("Tab",
                                       new XElement("Id", propertyGroup.Id.ToString(CultureInfo.InvariantCulture)),
                                       new XElement("Caption", propertyGroup.Name),
                                       new XElement("SortOrder", propertyGroup.SortOrder));
                tabs.Add(tab);
            }

            var xml = new XElement("DocumentType",
                                   info,
                                   structure,
                                   genericProperties,
                                   tabs);

            var folderNames = string.Empty;

            //don't add folders if this is a child doc type
            if (contentType.Level != 1 && masterContentType == null)
            {
                //get url encoded folder names
                var folders = _contentTypeService.GetContainers(contentType)
                              .OrderBy(x => x.Level)
                              .Select(x => HttpUtility.UrlEncode(x.Name));

                folderNames = string.Join("/", folders.ToArray());
            }

            if (string.IsNullOrWhiteSpace(folderNames) == false)
            {
                xml.Add(new XAttribute("Folders", folderNames));
            }

            return(xml);
        }
예제 #52
0
 internal static bool IsRoslynContentType(IContentType contentType)
 {
     return(contentType.IsCSharp() || contentType.IsVisualBasic());
 }
예제 #53
0
 private void Initialize(string targetFileContents, string mapFileContents, string directory, IContentType contentType)
 {
     _contentType = contentType;
     _parser      = CssParserLocator.FindComponent(_contentType).CreateParser();
     _directory   = directory;
     PopulateMap(targetFileContents, mapFileContents); // Begin two-steps initialization.
 }
예제 #54
0
 public IOutputTextPane Create(Guid guid, string name, IContentType contentType) =>
 Create(guid, name, (object)contentType);
예제 #55
0
 private InteractiveSmartIndenter(IContentType contentType, ITextView view, ISmartIndentProvider provider)
 {
     _contentType = contentType;
     _view        = view;
     _indenter    = provider.CreateSmartIndent(view);
 }
예제 #56
0
 public static bool IsJavaScript(this IContentType contentType)
 {
     return(contentType.IsOfType("JavaScript"));
 }
예제 #57
0
 public ITextBuffer CreateTextBuffer(string text, IContentType contentType)
 {
     return(CreateTextBuffer(text, contentType, false));
 }
 public bool IsCompletionSupported(IContentType contentType) => CompletionAvailability.IsAvailable(contentType, roles: null);                                       // This will call HasCompletionProviders among doing other checks
예제 #59
0
        public ActionResult Transferred([Bind(Prefix = "transferredViewModel")] TransferredViewModel model)
        {
            ResponseModel responseModel = new ResponseModel();

            if (!Members.IsLoggedIn())
            {
                responseModel.Success = false;
                responseModel.Msg     = "请先进行登录过在进行补充信息";
            }
            else if (!ModelState.IsValid)
            {
                foreach (var item in ModelState)
                {
                    if (item.Value.Errors.Count > 0)
                    {
                        responseModel.Success = false;
                        responseModel.Msg     = item.Value.Errors.FirstOrDefault().ErrorMessage;
                    }
                }
            }
            else
            {
                IMember member = Services.MemberService.GetById(Members.GetCurrentMemberId());

                if (member.GetValue <double>("okassets") < model.Amount)
                {
                    responseModel.Success = false;
                    responseModel.Msg     = "购买的金额超限,您账户余额是:" + member.GetValue <double>("okassets").ToString("N2") + "元";
                    return(Json(responseModel, JsonRequestBehavior.AllowGet));
                }


                //新增产品数据
                IContentType ct      = ApplicationContext.Services.ContentTypeService.GetContentType("PayRecords");
                IContent     content = ApplicationContext.Services.ContentService.CreateContent("无用户名", ct.Id, "PayRecords");

                IContent product = Services.ContentService.GetById(model.ProductId);
                DateTime start = DateTime.Now, end = start.AddMonths(product.GetValue <int>("cycle"));
                content.SetValue("username", member.Name);
                content.Name = member.Email;
                content.SetValue("email", member.Email);
                content.SetValue("memberPicker", member.Id);
                content.SetValue("buyproduct", product.Id);
                content.SetValue("mobilePhone", member.GetValue <string>("tel"));
                content.SetValue("memberPicker", member.Id.ToString());
                content.SetValue("amountCny", model.Amount.ToString());
                content.SetValue("rechargeDateTime", start.ToString("yyyy-MM-dd HH:mm:ss"));
                content.SetValue("expirationtime", end.ToString("yyyy-MM-dd HH:mm:ss"));
                content.SetValue("payBillno", "账户余额金额购买");
                content.SetValue("isdeposit", true);
                content.SetValue("isexpired", false);
                Services.ContentService.Save(content);
                EventHandlers.CustomRaiseEvent.RaiseContentCreated(content);
                decimal okassets = member.GetValue <decimal>("okassets"), fundAccount = member.GetValue <decimal>("fundAccount");
                //assets = assets - (decimal)model.Amount;

                //if (assets < okassets)
                //{
                //    //如果 可提现金额小于已经转出后的余额 也应扣款
                //    member.SetValue("okassets", assets.ToString());
                //}
                member.SetValue("okassets", (okassets - (decimal)model.Amount).ToString());
                member.SetValue("fundAccount", (fundAccount + (decimal)model.Amount).ToString());
                Services.MemberService.Save(member);

                responseModel.Success     = true;
                responseModel.Msg         = "恭喜你成功转入到定期宝!";
                responseModel.RedirectUrl = "/memberinfo";
            }
            return(Json(responseModel, JsonRequestBehavior.AllowGet));
        }
예제 #60
0
 // Returns true if the second content type is a base type of the first.
 private static bool IsBaseContentType(IContentType type, IContentType potentialBase)
 {
     return(type.BaseTypes.Any(b => b.IsOfType(potentialBase.TypeName) || IsBaseContentType(b, potentialBase)));
 }