/// <summary>
        ///     Gets the application configuration document data.
        /// </summary>
        /// <param name="serviceProvider">The service provider.</param>
        /// <param name="hierarchy">The hierarchy.</param>
        /// <param name="createIfNotExists">if set to <see langword="true" /> [create if not exists].</param>
        /// <returns>The application configuration document data.</returns>
        /// <exception cref="NotSupportedException">Incompatible buffer</exception>
        public static DocData GetAppConfigDocData(IServiceProvider serviceProvider, IVsHierarchy hierarchy,
                                                  bool createIfNotExists)
        {
            var     projSpecialFiles = hierarchy as IVsProjectSpecialFiles;
            DocData appConfigDocData = null;

            if (projSpecialFiles != null)
            {
                var flags = createIfNotExists
                    ? Convert.ToUInt32(__PSFFLAGS.PSFF_CreateIfNotExist | __PSFFLAGS.PSFF_FullPath)
                    : Convert.ToUInt32(__PSFFLAGS.PSFF_FullPath);
                projSpecialFiles.GetFile((int)__PSFFILEID.PSFFILEID_AppConfig, flags, out var appConfigItemId,
                                         out var appConfigFileName);

                if (appConfigItemId != (uint)VSConstants.VSITEMID.Nil)
                {
                    appConfigDocData = new DocData(serviceProvider, appConfigFileName);
                }
            }

            if (appConfigDocData == null || appConfigDocData.Buffer != null)
            {
                return(appConfigDocData);
            }

            // The native DocData needs to implement the IVsTextBuffer so DocDataTextReaders/Writers can be used.
            // If this is not possible, inform the user that things may be broken
            appConfigDocData.Dispose();
            throw new NotSupportedException("Incompatible buffer");
        }
예제 #2
0
        private bool AddFile(ProjectNode projectNode, string file, string content)
        {
            // add the file to the project
            HierarchyNode node = projectNode.AddItem(file);

            if (node == null)
            {
                return(false);
            }

            using (node)
            {
                // Hide the file already added
                IVsWindowFrame frame = projectNode.OpenItem(node);
                frame.Hide();
                using (DocData docData = new DocData(serviceProvider, node.Path))
                {
                    docData.CheckoutFile(serviceProvider);
                    using (DocDataTextWriter writer = new DocDataTextWriter(docData))
                    {
                        writer.Write(content);
                    }
                }
                frame.CloseFrame((uint)__FRAMECLOSE.FRAMECLOSE_SaveIfDirty);
                return(true);
            }
        }
예제 #3
0
        public void ExportTest()
        {
            var    writer    = new SautinsoftDocumentWriterService();
            string url       = @"d://Doc1.docx";
            string exporturl = @"d://TestExport";

            var data = new DocData
            {
                Name    = "@title",
                Value   = "سلام دنیا",
                DocType = DocType.Text
            };

            List <DocData> list = new List <DocData>
            {
                data
            };

            writer.Write(url, list, exporturl, ExportType.Pdf);
            writer.Write(url, list, exporturl, ExportType.Docx);


            var text = File.ReadAllText(url);

            Assert.True(text.IndexOf(data.Value) != -1);
        }
예제 #4
0
        private DocData AddDocData(int numVectorFields)
        {
            FieldData last = null;

            //for (IEnumerator<DocData> it = PendingDocs.Reverse(); it.MoveNext();)
            foreach (DocData doc in PendingDocs.Reverse())
            {
                if (!(doc.Fields.Count == 0))
                {
                    last = doc.Fields.Last.Value;
                    break;
                }
            }
            DocData newDoc;

            if (last == null)
            {
                newDoc = new DocData(this, numVectorFields, 0, 0, 0);
            }
            else
            {
                int posStart = last.PosStart + (last.HasPositions ? last.TotalPositions : 0);
                int offStart = last.OffStart + (last.HasOffsets ? last.TotalPositions : 0);
                int payStart = last.PayStart + (last.HasPayloads ? last.TotalPositions : 0);
                newDoc = new DocData(this, numVectorFields, posStart, offStart, payStart);
            }
            PendingDocs.AddLast(newDoc);
            return(newDoc);
        }
예제 #5
0
        /// <summary>
        /// This method will get the CodeDomDocDataAdapter corresponding to the active XAML file in
        /// the designer.
        /// </summary>
        /// <returns>The CodeDomDocDataAdapter for the .n file that corresponds to the active xaml file</returns>
        CodeDomDocDataAdapter GetDocDataAdapterForNemerleFile()
        {
            var codeDom = (IVSMDCodeDomProvider)(new ServiceProvider(_nFile.OleServiceProvider, true)).GetService(typeof(SVSMDCodeDomProvider));
            var data    = new DocData(((NemerleProjectNode)_project).ProjectMgr.Site, _nFile.Url);

            return(new CodeDomDocDataAdapter((_project as NemerleProjectNode).ProjectMgr.Site, data));
        }
예제 #6
0
        internal void OnCloseFrame(FrameWrapper closingFrame)
        {
            if (_mapFrameToUri.ContainsKey(closingFrame))
            {
                _mapFrameToUri.Remove(closingFrame);

                if (null != closingFrame.Uri)
                {
                    var rdt = new RunningDocumentTable(_package);
                    var doc = rdt.FindDocument(closingFrame.Uri.LocalPath);
                    if (doc != null)
                    {
                        var isModified = false;
                        using (var docData = new DocData(doc))
                        {
                            isModified = docData.Modified;
                        }
                        if (isModified)
                        {
                            // document was modified but was closed without saving changes;
                            // we need to refresh all sets that refer to the document
                            // so that they revert to the document that is persisted in the file system

                            // TODO: add this functinality
                            //ModelManager.RefreshModelForLocation(closingFrame.Uri);
                        }
                    }
                }
            }
        }
예제 #7
0
        private DocData AddDocData(int numVectorFields)
        {
            FieldData last = null;
            // LUCENENET specific - quicker just to use the linked list properties
            // to walk backward, since we are only looking for the last element with
            // fields.
            var doc = pendingDocs.Last;

            while (doc != null)
            {
                if (!(doc.Value.fields.Count == 0))
                {
                    last = doc.Value.fields.Last.Value;
                    break;
                }
                doc = doc.Previous;
            }
            DocData newDoc;

            if (last == null)
            {
                newDoc = new DocData(this, numVectorFields, 0, 0, 0);
            }
            else
            {
                int posStart = last.posStart + (last.hasPositions ? last.totalPositions : 0);
                int offStart = last.offStart + (last.hasOffsets ? last.totalPositions : 0);
                int payStart = last.payStart + (last.hasPayloads ? last.totalPositions : 0);
                newDoc = new DocData(this, numVectorFields, posStart, offStart, payStart);
            }
            pendingDocs.AddLast(newDoc);
            return(newDoc);
        }
        /// <summary>
        /// This method will get the CodeDomDocDataAdapter corresponding to the active XAML file in
        /// the designer.
        /// </summary>
        /// <returns>The CodeDomDocDataAdapter for the .py file that corresponds to the active xaml file</returns>
        public CodeDomDocDataAdapter GetDocDataAdapterForPyFile()
        {
            IVSMDCodeDomProvider codeDom = (new ServiceProvider(pyFile.OleServiceProvider, true)).GetService(typeof(SVSMDCodeDomProvider)) as IVSMDCodeDomProvider;
            DocData data = new DocData((project as PythonProjectNode).ProjectMgr.Site, pyFile.Url);
            CodeDomDocDataAdapter cdDocDataAdapter = new CodeDomDocDataAdapter((project as PythonProjectNode).ProjectMgr.Site, data);

            return(cdDocDataAdapter);
        }
예제 #9
0
        public App()
        {
            ////var newInt = (b << 16) | a;

            AppSetting.Load();
            YinData.InitData();
            DocData.InitData();
        }
예제 #10
0
        public override CodeCompileUnit Parse(TextReader codeStream)
        {
            CodeCompileUnit compileUnit = null;
            //
            string mainFilePath = GetFilePath();

            // Are we are from the Designer ?
            if (codeStream is DocDataTextReader)
            {
                this.FileName = mainFilePath;
                // Do the parse
                // If the TextReader is a DocDataTextReader, we should be running from VisualStudio, called by the designer
                // So, we will guess the FileName to check if we have a .Designer.Prg file at the same place.
                // If so, we will have to handle both .prg to produce two CodeCompileUnit, then we will merge the result into one, with markers in it
                // so we can split again when the Designer is willing to save. ( See GenerateCodeFromCompileUnit )
                if (codeStream is DocDataTextReader)
                {
                    // Anyway, we have that source, just parse it.
                    compileUnit = base.Parse(codeStream);
                    // Now, we should check if we have a partial Class inside, if so, that's a Candidate for .Designer.prg
                    CodeNamespace       nameSpace;
                    CodeTypeDeclaration className;
                    if (XSharpCodeDomHelper.HasPartialClass(compileUnit, out nameSpace, out className))
                    {
                        // Ok, so get the Filename, to get the .Designer.prg
                        DocDataTextReader ddtr        = codeStream as DocDataTextReader;
                        DocData           dd          = ((IServiceProvider)ddtr).GetService(typeof(DocData)) as DocData;
                        String            prgFileName = dd.Name;
                        // Build the Designer FileName
                        String designerPrgFile = XSharpCodeDomHelper.BuildDesignerFileName(prgFileName);
                        if (!String.IsNullOrEmpty(designerPrgFile) && File.Exists(designerPrgFile))
                        {
                            // Ok, we have a candidate !!!
                            DocData           docdata = new DocData((IServiceProvider)ddtr, designerPrgFile);
                            DocDataTextReader reader  = new DocDataTextReader(docdata);
                            // so parse
                            CodeCompileUnit designerCompileUnit = base.Parse(reader);
                            CodeCompileUnit mergedCompileUnit   = null;
                            // Now we have Two CodeCompileUnit, we must merge them
                            mergedCompileUnit = XSharpCodeDomHelper.MergeCodeCompileUnit(compileUnit, designerCompileUnit);
                            mergedCompileUnit.UserData[XSharpCodeConstants.USERDATA_HASDESIGNER] = true;
                            mergedCompileUnit.UserData[XSharpCodeConstants.USERDATA_FILENAME]    = prgFileName;
                            // Save CCU for GenerateCode operation, it will be faster and easier than to recreate it
                            mergedCompileUnit.UserData[XSharpCodeConstants.USERDATA_CCU_FORM]     = compileUnit;
                            mergedCompileUnit.UserData[XSharpCodeConstants.USERDATA_CCU_DESIGNER] = designerCompileUnit;
                            return(mergedCompileUnit);
                        }
                    }
                }
                else
                {
                    compileUnit = base.Parse(codeStream);
                }
            }
            //
            return(compileUnit);
        }
예제 #11
0
        public override DocData GetNextDocData(DocData docData)
        {
            int id = NewDocID();

            AddBytes(DOC_TEXT.Length);
            docData.Clear();
            docData.Name = "doc" + id;
            docData.Body = DOC_TEXT;
            return(docData);
        }
예제 #12
0
 /// <summary>
 /// 初始化所有字段
 /// </summary>
 public override void Clear()
 {
     base.Clear();
     _docData      = null; // 源工程数据对象
     _ctaDocData   = null; //	对比工程数据对象
     _docDataId    = null;
     _ctaDocDataId = null;
     _ctaStatus    = (int)_ctaStatusEnum.csConsis;
     _errorCount   = 0;
 }
예제 #13
0
        /// <summary>
        /// This method will get the CodeDomDocDataAdapter corresponding to the active XAML file in
        /// the designer.
        /// </summary>
        /// <returns>The CodeDomDocDataAdapter for the .prg file that corresponds to the active xaml file</returns>
        CodeDomDocDataAdapter GetDocDataAdapterForXSharpFile()
        {
            if (_cdda == null)
            {
                var codeDom = (IVSMDCodeDomProvider)(new ServiceProvider(_xsFile.OleServiceProvider, true)).GetService(typeof(SVSMDCodeDomProvider));
                var data    = new DocData(((XSharpProjectNode)_project).ProjectMgr.Site, _xsFile.Url);

                _cdda = new CodeDomDocDataAdapter((_project as XSharpProjectNode).ProjectMgr.Site, data);
            }
            return(_cdda);
        }
예제 #14
0
        /// <summary>
        /// Called when window is closed. Overridden here to remove our objects from the selection context so that
        /// the property browser doesn't call back on our objects after the window is closed.
        /// </summary>
        protected override void OnClose()
        {
            bool dirty = DocData.IsDirty(out int isDirty) == 0 && isDirty == 1;

            if (!DocData.DocViews.Except(new[] { this }).Any() && dirty && DocData.QuerySaveFile().CanSaveFile)
            {
                DocData.Save(string.Empty, 1, 0);
            }

            base.OnClose();
        }
예제 #15
0
 public override void FinishDocument()
 {
     // append the payload bytes of the doc after its terms
     TermSuffixes.WriteBytes(PayloadBytes.Bytes, PayloadBytes.Length);
     PayloadBytes.Length = 0;
     ++NumDocs;
     if (TriggerFlush())
     {
         Flush();
     }
     CurDoc = null;
 }
예제 #16
0
        private void Flush()
        {
            int chunkDocs = pendingDocs.Count;

            if (Debugging.AssertsEnabled)
            {
                Debugging.Assert(chunkDocs > 0, "{0}", chunkDocs);
            }

            // write the index file
            indexWriter.WriteIndex(chunkDocs, vectorsStream.Position); // LUCENENET specific: Renamed from getFilePointer() to match FileStream

            int docBase = numDocs - chunkDocs;

            vectorsStream.WriteVInt32(docBase);
            vectorsStream.WriteVInt32(chunkDocs);

            // total number of fields of the chunk
            int totalFields = FlushNumFields(chunkDocs);

            if (totalFields > 0)
            {
                // unique field numbers (sorted)
                int[] fieldNums = FlushFieldNums();
                // offsets in the array of unique field numbers
                FlushFields(totalFields, fieldNums);
                // flags (does the field have positions, offsets, payloads?)
                FlushFlags(totalFields, fieldNums);
                // number of terms of each field
                FlushNumTerms(totalFields);
                // prefix and suffix lengths for each field
                FlushTermLengths();
                // term freqs - 1 (because termFreq is always >=1) for each term
                FlushTermFreqs();
                // positions for all terms, when enabled
                FlushPositions();
                // offsets for all terms, when enabled
                FlushOffsets(fieldNums);
                // payload lengths for all terms, when enabled
                FlushPayloadLengths();

                // compress terms and payloads and write them to the output
                compressor.Compress(termSuffixes.Bytes, 0, termSuffixes.Length, vectorsStream);
            }

            // reset
            pendingDocs.Clear();
            curDoc              = null;
            curField            = null;
            termSuffixes.Length = 0;
        }
예제 #17
0
		///-------------------------------------------------------------------------------------------------------------
		/// <summary>
		///	 
		/// </summary>
		///-------------------------------------------------------------------------------------------------------------
		void IVsCodeBehindCodeGenerator.Generate()
		{
			DocData ddDesigner = null;
			DocDataTextWriter designerWriter = null;

			try
			{
				if (_itemCode != null && _codeDomProvider != null)
				{

					// Generate the code
					StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture);
					_codeDomProvider.GenerateCodeFromCompileUnit(_ccu, stringWriter, _codeGeneratorOptions);
					string generatedCode = stringWriter.ToString();

					// Create designer file if requested
					if (_itemDesigner == null && _create)
					{
						_itemDesigner = GetDesignerItem(_itemCode, true);
					}

					// See if generated code changed
					string designerContents = _itemDesigner.GetDocumentText();
					if (!BufferEquals(designerContents, generatedCode))  // Would be nice to just compare lengths but the buffer gets formatted after insertion
					{
						ddDesigner = new LockedDocData(_serviceProvider, _itemDesigner.FullPath());

						// Try to check out designer file (this throws)
						ddDesigner.CheckoutFile(_serviceProvider);

						// Write out the new code
						designerWriter = new DocDataTextWriter(ddDesigner);
						designerWriter.Write(generatedCode);
						designerWriter.Flush();
						designerWriter.Close();
					}
				}
			}
			finally
			{
				if (designerWriter != null)
				{
					designerWriter.Dispose();
				}
				if (ddDesigner != null)
				{
					ddDesigner.Dispose();
				}
			}
		}
예제 #18
0
        private static ModelChangeMonitor CreateModelChangeMonitor()
        {
            IMonitorSelectionService monitorSelectionService = RuntimeHelper.ServiceProvider.GetService(typeof(IMonitorSelectionService)) as IMonitorSelectionService;

            if (monitorSelectionService != null) // may be null on tests
            {
                DocData docData = monitorSelectionService.CurrentDocument as DocData;
                if (docData != null)
                {
                    return(new ModelChangeMonitor(docData));
                }
            }
            return(null);
        }
예제 #19
0
 public ModelChangeMonitor(DocData docData)
 {
     bool initialized = false;
     try
     {
         this.uniqueId = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture);
         docData.DocumentClosed += OnDocumentClosed;
         initialized = true;
     }
     finally
     {
         base.InitializationComplete();
         if (!initialized) base.Dispose();
     }
 }
예제 #20
0
        /// <summary>
        /// Replaces the source file with the destination file
        /// </summary>
        /// <param name="source">full path to the source file</param>
        /// <param name="dest">full path to the destination file</param>
        /// <param name="project">project where the file is located</param>
        private void ReplaceFile(string source, string dest, Project project)
        {
            bool documentOpened = false;

            OutputString(VSConstants.OutputWindowPaneGuid.BuildOutputPane_guid,
                         "Replacing " + dest + " with " + source + Environment.NewLine);

            // Get source text. Make sure the project item is opened, otherwise the Document property
            //  will be null
            var projectItem = project.DTE.Solution.FindProjectItem(source);

            if (!projectItem.IsOpen)
            {
                projectItem.Open();
                documentOpened = true;
            }

            // Try to open the document as Text
            var textDocument = (TextDocument)projectItem.Document.Object("TextDocument");

            // Not a text document
            if (textDocument == null)
            {
                // If we can replace it as text, just copy the file manually
                File.Copy(source, dest, true);
            }
            // Replace the text document
            else
            {
                EditPoint editPoint = textDocument.StartPoint.CreateEditPoint();
                var       content   = editPoint.GetText(textDocument.EndPoint);

                // Copy the text to the destination file
                var docData = new DocData(this, dest);
                var editorAdaptersFactoryService = (this.GetService(typeof(SComponentModel)) as IComponentModel).GetService <IVsEditorAdaptersFactoryService>();
                var textBuffer = editorAdaptersFactoryService.GetDataBuffer(docData.Buffer);
                textBuffer.Replace(new Span(0, textBuffer.CurrentSnapshot.Length), content);

                // Save the file after modifying it
                project.DTE.Solution.FindProjectItem(dest).Save();
            }

            // Close the document if we opened it
            if (documentOpened)
            {
                projectItem.Document.Close();
            }
        }
예제 #21
0
        private void Flush()
        {
            int chunkDocs = PendingDocs.Count;

            Debug.Assert(chunkDocs > 0, chunkDocs.ToString());

            // write the index file
            IndexWriter.WriteIndex(chunkDocs, VectorsStream.FilePointer);

            int docBase = NumDocs - chunkDocs;

            VectorsStream.WriteVInt(docBase);
            VectorsStream.WriteVInt(chunkDocs);

            // total number of fields of the chunk
            int totalFields = FlushNumFields(chunkDocs);

            if (totalFields > 0)
            {
                // unique field numbers (sorted)
                int[] fieldNums = FlushFieldNums();
                // offsets in the array of unique field numbers
                FlushFields(totalFields, fieldNums);
                // flags (does the field have positions, offsets, payloads?)
                FlushFlags(totalFields, fieldNums);
                // number of terms of each field
                FlushNumTerms(totalFields);
                // prefix and suffix lengths for each field
                FlushTermLengths();
                // term freqs - 1 (because termFreq is always >=1) for each term
                FlushTermFreqs();
                // positions for all terms, when enabled
                FlushPositions();
                // offsets for all terms, when enabled
                FlushOffsets(fieldNums);
                // payload lengths for all terms, when enabled
                FlushPayloadLengths();

                // compress terms and payloads and write them to the output
                Compressor.Compress(TermSuffixes.Bytes, 0, TermSuffixes.Length, VectorsStream);
            }

            // reset
            PendingDocs.Clear();
            CurDoc              = null;
            CurField            = null;
            TermSuffixes.Length = 0;
        }
예제 #22
0
        /// <summary>
        /// Save the given document that is subordinate to this document.
        /// </summary>
        /// <param name="subordinateDocument">The subordinate document.</param>
        /// <param name="fileName">The fileName to save.</param>
        protected override void SaveSubordinateFile(DocData subordinateDocument, string fileName)
        {
            Guard.NotNull(() => subordinateDocument, subordinateDocument);

            SerializationResult serializationResult = new SerializationResult();

            var diagrams = this.GetDiagrams(fileName);

            foreach (var diagram in diagrams)
            {
                try
                {
                    this.SuspendFileChangeNotification(diagram.Key);

                    PatternModelSerializationHelper.Instance.SaveDiagram(serializationResult, diagram.Value, diagram.Key, this.Encoding, false);
                }
                finally
                {
                    this.ResumeFileChangeNotification(fileName);
                }
            }

            this.SuspendErrorListRefresh();

            try
            {
                foreach (var serializationMessage in serializationResult)
                {
                    this.AddErrorListItem(new SerializationErrorListItem(this.ServiceProvider, serializationMessage));
                }
            }
            finally
            {
                this.ResumeErrorListRefresh();
            }

            if (!serializationResult.Failed)
            {
                this.NotifySubordinateDocumentSaved(subordinateDocument.FileName, fileName);
            }
            else
            {
                throw new InvalidOperationException(PatternModelDomainModel.SingletonResourceManager.GetString("CannotSaveDocument"));
            }
        }
예제 #23
0
        private DocData GetContrastDoc(DocData doc, int idx, CjzData ctaCjzData)
        {
            DocData ret = null;

            if (idx < ctaCjzData.docList.Count)
            {
                DocData ddoc = ctaCjzData.docList[idx] as DocData;
                if ((doc.docName == ddoc.docName) && (doc.docLevel == ddoc.docLevel))
                {
                    ret = ddoc;
                }
                else
                {
                    ddoc = ctaCjzData.docList.Cast <DocData>().FirstOrDefault(a => a.docName == doc.docName);
                }
            }

            return(ret);
        }
예제 #24
0
        public ModelChangeMonitor(DocData docData)
        {
            bool initialized = false;

            try
            {
                this.uniqueId           = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture);
                docData.DocumentClosed += OnDocumentClosed;
                initialized             = true;
            }
            finally
            {
                base.InitializationComplete();
                if (!initialized)
                {
                    base.Dispose();
                }
            }
        }
예제 #25
0
        private static void SelectShape(ShapeElement shapeElement, DocData docData)
        {
            // Validation

            if (shapeElement == null)
            {
                throw new ArgumentNullException("shapeElement");
            }

            if (docData == null)
            {
                throw new ArgumentNullException("docData");
            }

            ModelingDocView docView = docData.DocViews[0];

            if (docView != null)
            {
                docView.SelectObjects(1, new object[] { shapeElement }, 0);
            }
        }
예제 #26
0
        public override CodeCompileUnit Parse(TextReader codeStream)
        {
            //
            string mainFilePath = GetFilePath();
            // Are we are from the Designer ?
            var ddtr = codeStream as DocDataTextReader;

            if (ddtr != null)
            {
                this.FileName = mainFilePath;
                // Do the parse
                // If the TextReader is a DocDataTextReader, we should be running from VisualStudio, called by the designer
                // So, we will guess the FileName to check if we have a .Designer.boo file at the same place.
                // If so, we will have to build both .boo files to produce the CodeCompileUnit
                // Now, we should check if we have a partial Class inside, if so, that's a Candidate for .Designer.boo
                // Ok, so get the Filename, to get the companion file
                var    dd         = ((IServiceProvider)ddtr).GetService(typeof(DocData)) as DocData;
                String ddFileName = dd.Name;
                // Build the Designer FileName
                var    baseIsDesignForm = ddFileName.EndsWith(".Designer.boo");
                String companionFile    = baseIsDesignForm
                    ? BooCodeDomHelper.BuildNonDesignerFileName(ddFileName)
                    : BooCodeDomHelper.BuildDesignerFileName(ddFileName);
                if (File.Exists(companionFile))
                {
                    // Ok, we have a candidate !!!
                    DocData           docdata = new DocData(ddtr, companionFile);
                    DocDataTextReader reader  = new DocDataTextReader(docdata);
                    // so parse
                    var result = base.Parse(new TextReader[] { codeStream, reader }, new[] { ddFileName, companionFile });
                    BooCodeDomHelper.AnnotateCompileUnit(result);
                    result.UserData[BooCodeDomHelper.USERDATA_HASDESIGNER] = true;
                    result.UserData[BooCodeDomHelper.USERDATA_FILENAME]    = ddFileName;
                    return(result);
                }
            }
            return(base.Parse(codeStream));
        }
        public override CodeCompileUnit Parse(TextReader codeStream)
        {
            CodeCompileUnit compileUnit = null;
            //
            string mainFilePath = GetFilePath();
            // Are we are from the Designer ?
            if (codeStream is DocDataTextReader)
            {
                this.FileName = mainFilePath;
                // Do the parse
#if DESIGNERSUPPORT
                // If the TextReader is a DocDataTextReader, we should be running from VisualStudio, called by the designer
                // So, we will guess the FileName to check if we have a .Designer.Prg file at the same place.
                // If so, we will have to handle both .prg to produce two CodeCompileUnit, then we will merge the result into one, with markers in it
                // so we can split again when the Designer is willing to save. ( See GenerateCodeFromCompileUnit )
                if (codeStream is DocDataTextReader)
                {
                    // Anyway, we have that source, just parse it.
                    compileUnit = base.Parse(codeStream);
                    // Now, we should check if we have a partial Class inside, if so, that's a Candidate for .Designer.prg
                    CodeNamespace nameSpace;
                    CodeTypeDeclaration className;
                    if (XSharpCodeDomHelper.HasPartialClass(compileUnit, out nameSpace, out className))
                    {
                        // Ok, so get the Filename, to get the .Designer.prg
                        DocDataTextReader ddtr = codeStream as DocDataTextReader;
                        DocData dd = ((IServiceProvider)ddtr).GetService(typeof(DocData)) as DocData;
                        String prgFileName = dd.Name;
                        // Build the Designer FileName
                        String designerPrgFile = XSharpCodeDomHelper.BuildDesignerFileName(prgFileName);
                        if (File.Exists(designerPrgFile))
                        {
                            // Ok, we have a candidate !!!
                            DocData docdata = new DocData((IServiceProvider)ddtr, designerPrgFile);
                            DocDataTextReader reader = new DocDataTextReader(docdata);
                            // so parse
                            CodeCompileUnit designerCompileUnit = base.Parse(reader);
                            CodeCompileUnit mergedCompileUnit = null;
                            // Now we have Two CodeCompileUnit, we must merge them
                            mergedCompileUnit = XSharpCodeDomHelper.MergeCodeCompileUnit(compileUnit, designerCompileUnit);
                            mergedCompileUnit.UserData[XSharpCodeConstants.USERDATA_HASDESIGNER] = true;
                            mergedCompileUnit.UserData[XSharpCodeConstants.USERDATA_FILENAME] = prgFileName;
                            // Save CCU for GenerateCode operation, it will be faster and easier than to recreate it
                            mergedCompileUnit.UserData[XSharpCodeConstants.USERDATA_CCU_FORM] = compileUnit;
                            mergedCompileUnit.UserData[XSharpCodeConstants.USERDATA_CCU_DESIGNER] = designerCompileUnit;
                            return mergedCompileUnit;
                        }
                    }
                }
                else
#endif
                {
                    compileUnit = base.Parse(codeStream);
                }

            }
            //
            return compileUnit;
        }
예제 #28
0
 // <summary>
 //     This toolwindow is only usable when one of our documents is shown
 // </summary>
 protected override bool IsDocumentSupported(DocData docData)
 {
     return(docData is IEntityDesignDocData);
 }
예제 #29
0
 public override DocData GetNextDocData(DocData docData)
 {
     return(docData);
 }
        protected override bool LoadView()
        {
            var ret = false;

            var isDocDataDirty = 0;

            // Save IsDocDataDirty flag here to be set back later.
            // This is because loading-view can cause the flag to be set since a new diagram could potentially created.
            DocData.IsDocDataDirty(out isDocDataDirty);
            IsLoading = true;
            try
            {
                var uri = Utils.FileName2Uri(DocData.FileName);
                _context = PackageManager.Package.DocumentFrameMgr.EditingContextManager.GetNewOrExistingContext(uri);
                Debug.Assert(_context != null, "_context should not be null");

                // Set DSL Diagram instance and values.
                // Note: the code should be executed before we suspend rule notification. The diagram shapes will not created correctly if we don't.

                // When document is reloaded, a new diagram will be created; so we always need to check for the new view diagram every time LoadView is called.
                var currentDiagram = GetNewOrExistingViewDiagram();
                if (Diagram != currentDiagram)
                {
                    Diagram = currentDiagram;
                }

                // Ensure that cache _xRef is cleared.
                _xRef = null;

                // The only case where diagram is null at this point is that VS tries to open diagram that doesn't exist in our model.
                // One of the possibilities: the user creates multiple diagrams, open the diagrams in VS, then close the project without saving the document.
                // When the project is reopened in the same VS, VS remembers any opened windows and will try to reopen it.
                // In this case, we should close the frame.
                if (Diagram == null)
                {
                    // Return false will force the window frame to be closed.
                    return(false);
                }

                if (Diagram is EntityDesignerDiagram entityDiagram && entityDiagram.ModelElement.EditingContext is null)
                {
                    // The editing context is null. This will cause downstream calls to throw exceptions.
                    // It is unknown why this happens sometimes, but seems to have something to do with designers being open on project load.
                    // Solution: Close the frame.
                    return(false);
                }

                ApplyLayoutInformationFromModelDiagram();

                Debug.Assert(DocData.Store.RuleManager.IsRuleSuspended == false, "The rule notification should not be suspended.");
                DocData.Store.RuleManager.SuspendRuleNotification();

                // We don't call base.LoadView() because the code assumes there is only 1 diagram (will assert otherwise),
                // and will always choose the first diagram.
                if (BaseLoadView())
                {
                    // Normally our toolbox items get populated only when the window is activated, but
                    // in certain circumstances we may switch the mode of our designer (normal/safe-mode/etc)
                    // when the window is already active. This is an expensive operation so we only need it when
                    // we reload the active document.
                    var escherDocData = DocData as MicrosoftDataEntityDesignDocData;
                    if (escherDocData != null &&
                        escherDocData.IsHandlingDocumentReloaded)
                    {
                        ToolboxService.Refresh();
                    }
                    ret = true;
                }

                // Listen to Diagram Title change event so we can update our window caption with the information.
                var entityDesignerDiagram = Diagram as EntityDesignerDiagram;
                Debug.Assert(entityDesignerDiagram != null, "The diagram is not the type of EntityDesignerDiagram");
                if (entityDesignerDiagram != null)
                {
                    entityDesignerDiagram.OnDiagramTitleChanged += OnDiagramTitleChanged;
                }
                UpdateWindowFrameCaption();
            }
            finally
            {
                // After Diagram is set, DSL code enabled DSL Undo Manager, so the code below is to disable it.
                if (DocData.Store.UndoManager.UndoState == DslModeling.UndoState.Enabled)
                {
                    DocData.Store.UndoManager.UndoState = DslModeling.UndoState.Disabled;
                }

                if (DocData.Store.RuleManager.IsRuleSuspended)
                {
                    DocData.Store.RuleManager.ResumeRuleNotification();
                }
                DocData.SetDocDataDirty(isDocDataDirty);
                IsLoading = false;
            }
            return(ret);
        }
        internal void OnCloseFrame(FrameWrapper closingFrame)
        {
            if (_mapFrameToUri.ContainsKey(closingFrame))
            {
                _mapFrameToUri.Remove(closingFrame);

                if (null != closingFrame.Uri)
                {
                    var rdt = new RunningDocumentTable(_package);
                    var doc = rdt.FindDocument(closingFrame.Uri.LocalPath);
                    if (doc != null)
                    {
                        var isModified = false;
                        using (var docData = new DocData(doc))
                        {
                            isModified = docData.Modified;
                        }
                        if (isModified)
                        {
                            // document was modified but was closed without saving changes;
                            // we need to refresh all sets that refer to the document
                            // so that they revert to the document that is persisted in the file system

                            // TODO: add this functinality
                            //ModelManager.RefreshModelForLocation(closingFrame.Uri);
                        }
                    }
                }
            }
        }
예제 #32
0
        /// <summary>
        /// Save the given document that is subordinate to this document.
        /// </summary>
        /// <param name="subordinateDocument">The subordinate document.</param>
        /// <param name="fileName">The fileName to save.</param>
        protected override void SaveSubordinateFile(DocData subordinateDocument, string fileName)
        {
            Guard.NotNull(() => subordinateDocument, subordinateDocument);

            SerializationResult serializationResult = new SerializationResult();

            var diagrams = this.GetDiagrams(fileName);

            foreach (var diagram in diagrams)
            {
                try
                {
                    this.SuspendFileChangeNotification(diagram.Key);

                    PatternModelSerializationHelper.Instance.SaveDiagram(serializationResult, diagram.Value, diagram.Key, this.Encoding, false);
                }
                finally
                {
                    this.ResumeFileChangeNotification(fileName);
                }
            }

            this.SuspendErrorListRefresh();

            try
            {
                foreach (var serializationMessage in serializationResult)
                {
                    this.AddErrorListItem(new SerializationErrorListItem(this.ServiceProvider, serializationMessage));
                }
            }
            finally
            {
                this.ResumeErrorListRefresh();
            }

            if (!serializationResult.Failed)
            {
                this.NotifySubordinateDocumentSaved(subordinateDocument.FileName, fileName);
            }
            else
            {
                throw new InvalidOperationException(PatternModelDomainModel.SingletonResourceManager.GetString("CannotSaveDocument"));
            }
        }
 public override void FinishDocument()
 {
     // append the payload bytes of the doc after its terms
     TermSuffixes.WriteBytes(PayloadBytes.Bytes, PayloadBytes.Length);
     PayloadBytes.Length = 0;
     ++NumDocs;
     if (TriggerFlush())
     {
         Flush();
     }
     CurDoc = null;
 }
 // <summary>
 //     This toolwindow is only usable when one of our documents is shown
 // </summary>
 protected override bool IsDocumentSupported(DocData docData)
 {
     return docData is IEntityDesignDocData;
 }
 /// <summary>
 ///     Allows derived classes to specify supported Document type(s)
 /// </summary>
 protected abstract bool IsDocumentSupported(DocData document);
        private void Flush()
        {
            int chunkDocs = PendingDocs.Count;
            Debug.Assert(chunkDocs > 0, chunkDocs.ToString());

            // write the index file
            IndexWriter.WriteIndex(chunkDocs, VectorsStream.FilePointer);

            int docBase = NumDocs - chunkDocs;
            VectorsStream.WriteVInt(docBase);
            VectorsStream.WriteVInt(chunkDocs);

            // total number of fields of the chunk
            int totalFields = FlushNumFields(chunkDocs);

            if (totalFields > 0)
            {
                // unique field numbers (sorted)
                int[] fieldNums = FlushFieldNums();
                // offsets in the array of unique field numbers
                FlushFields(totalFields, fieldNums);
                // flags (does the field have positions, offsets, payloads?)
                FlushFlags(totalFields, fieldNums);
                // number of terms of each field
                FlushNumTerms(totalFields);
                // prefix and suffix lengths for each field
                FlushTermLengths();
                // term freqs - 1 (because termFreq is always >=1) for each term
                FlushTermFreqs();
                // positions for all terms, when enabled
                FlushPositions();
                // offsets for all terms, when enabled
                FlushOffsets(fieldNums);
                // payload lengths for all terms, when enabled
                FlushPayloadLengths();

                // compress terms and payloads and write them to the output
                Compressor.Compress(TermSuffixes.Bytes, 0, TermSuffixes.Length, VectorsStream);
            }

            // reset
            PendingDocs.Clear();
            CurDoc = null;
            CurField = null;
            TermSuffixes.Length = 0;
        }
예제 #37
0
 public override void StartDocument(int numVectorFields)
 {
     CurDoc = AddDocData(numVectorFields);
 }
 public DocController(ApplicationDbContext context)
 {
     _repository = new DocData(context);
 }
예제 #39
0
        /// <summary>
        /// This method will get the CodeDomDocDataAdapter corresponding to the active XAML file in
        /// the designer.
        /// </summary>
        /// <returns>The CodeDomDocDataAdapter for the .n file that corresponds to the active xaml file</returns>
        CodeDomDocDataAdapter GetDocDataAdapterForNemerleFile()
        {
            var codeDom = (IVSMDCodeDomProvider)(new ServiceProvider(_nFile.OleServiceProvider, true)).GetService(typeof(SVSMDCodeDomProvider));
            var data = new DocData(((NemerleProjectNode)_project).ProjectMgr.Site, _nFile.Url);

            return new CodeDomDocDataAdapter((_project as NemerleProjectNode).ProjectMgr.Site, data);
        }
 public override void StartDocument(int numVectorFields)
 {
     CurDoc = AddDocData(numVectorFields);
 }
 /// <summary>
 /// This method will get the CodeDomDocDataAdapter corresponding to the active XAML file in
 /// the designer.
 /// </summary>
 /// <returns>The CodeDomDocDataAdapter for the .py file that corresponds to the active xaml file</returns>
 public CodeDomDocDataAdapter GetDocDataAdapterForPyFile()
 {
     IVSMDCodeDomProvider codeDom = (new ServiceProvider(pyFile.OleServiceProvider, true)).GetService(typeof(SVSMDCodeDomProvider)) as IVSMDCodeDomProvider;
     DocData data = new DocData((project as PythonProjectNode).ProjectMgr.Site, pyFile.Url);
     CodeDomDocDataAdapter cdDocDataAdapter = new CodeDomDocDataAdapter((project as PythonProjectNode).ProjectMgr.Site, data);
     return cdDocDataAdapter;
 }
 private DocData AddDocData(int numVectorFields)
 {
     FieldData last = null;
     //for (IEnumerator<DocData> it = PendingDocs.Reverse(); it.MoveNext();)
     foreach (DocData doc in PendingDocs.Reverse())
     {
         if (!(doc.Fields.Count == 0))
         {
             last = doc.Fields.Last.Value;
             break;
         }
     }
     DocData newDoc;
     if (last == null)
     {
         newDoc = new DocData(this, numVectorFields, 0, 0, 0);
     }
     else
     {
         int posStart = last.PosStart + (last.HasPositions ? last.TotalPositions : 0);
         int offStart = last.OffStart + (last.HasOffsets ? last.TotalPositions : 0);
         int payStart = last.PayStart + (last.HasPayloads ? last.TotalPositions : 0);
         newDoc = new DocData(this, numVectorFields, posStart, offStart, payStart);
     }
     PendingDocs.AddLast(newDoc);
     return newDoc;
 }