public DocumentCompletionEventArgs( DocumentInfo documentInfo, IList<DocumentPart> documentParts) { _documentInfo = documentInfo; _documentParts = new ReadOnlyCollection<DocumentPart>(documentParts); }
public static void Run() { // ExStart:SetFileInfo // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments(); // Open document Document pdfDocument = new Document(dataDir + "SetFileInfo.pdf"); // Specify document information DocumentInfo docInfo = new DocumentInfo(pdfDocument); docInfo.Author = "Aspose"; docInfo.CreationDate = DateTime.Now; docInfo.Keywords = "Aspose.Pdf, DOM, API"; docInfo.ModDate = DateTime.Now; docInfo.Subject = "PDF Information"; docInfo.Title = "Setting PDF Document Information"; dataDir = dataDir + "SetFileInfo_out.pdf"; // Save output document pdfDocument.Save(dataDir); // ExEnd:SetFileInfo Console.WriteLine("\nFile informations setup successfully.\nFile saved at " + dataDir); }
public DocumentInfo OpenDocument(DocumentInfo document) { if (String.IsNullOrEmpty(document?.ToString())) return null; return new DocumentInfo() { Content = new FileStream(document.ToString(), FileMode.Open), Identification = new DocumentIdentification(document.ToString()) }; }
public Task<Projection> CreateProjection (DocumentInfo info, IReadonlyTextDocument data, bool buildExpressions) { if (info == null) throw new ArgumentNullException ("info"); if (data == null) throw new ArgumentNullException ("data"); var document = new StringBuilder (); WriteUsings (info.Imports, document); var segBuilder = System.Collections.Immutable.ImmutableList<ProjectedSegment>.Empty.ToBuilder (); foreach (var node in info.XScriptBlocks) { var start = data.LocationToOffset (node.Region.Begin.Line, node.Region.Begin.Column) + 2; var end = data.LocationToOffset (node.Region.End.Line, node.Region.End.Column) - 2; segBuilder.Add (new ProjectedSegment (start, document.Length, end - start)); document.AppendLine (data.GetTextBetween (start, end)); } if (buildExpressions) { WriteClassDeclaration (info, document); document.AppendLine ("{"); document.AppendLine ("void Generated ()"); document.AppendLine ("{"); //Console.WriteLine ("start:" + location.BeginLine +"/" +location.BeginColumn); foreach (var node in info.XExpressions) { bool isBlock = node is WebFormsRenderBlock; var start = data.LocationToOffset (node.Region.Begin.Line, node.Region.Begin.Column) + 2; var end = data.LocationToOffset (node.Region.End.Line, node.Region.End.Column) - 2; if (!isBlock) { document.Append ("WriteLine ("); start += 1; } string expr = data.GetTextBetween (start, end); segBuilder.Add (new ProjectedSegment (start, document.Length, expr.Length)); document.Append (expr); if (!isBlock) document.Append (");"); } document.AppendLine ("}"); document.AppendLine ("}"); } return Task.FromResult(new Projection ( TextEditorFactory.CreateNewDocument (new StringTextSource (document.ToString ()), info.AspNetDocument.FileName + ".g.cs", "text/x-csharp"), segBuilder.ToImmutable () )); }
public OperationResult Post(DocumentInfo doc) { doc.Id = Database.Documents.Max(x => x.Id) + 1; doc.LastModifiedTimeUTC = DateTime.UtcNow; doc.DataHref = new DocumentData { Id = doc.Id }.CreateUri(); var createdUri = doc.CreateUri(); Database.Documents.Add(doc); return new OperationResult.Created { RedirectLocation = createdUri, ResponseResource = doc }; }
public OperationResult Post(DocumentInfo doc, IFile sentFile) { doc.Id = Database.Documents.Max(x => x.Id) + 1; doc.FileName = sentFile.FileName; using (var reader = new BinaryReader(sentFile.OpenStream())) doc.Data = reader.ReadBytes((int)sentFile.Length); doc.LastModifiedTimeUTC = DateTime.UtcNow; doc.DataHref = new DocumentData { Id = doc.Id }.CreateUri(); var createdUri = doc.CreateUri(); Database.Documents.Add(doc); return new OperationResult.Created { RedirectLocation = createdUri, ResponseResource = "Document created at " + createdUri }; }
protected void Page_Load(object sender, EventArgs e) { uniGrid.OnDataReload += uniGrid_OnDataReload; uniGrid.OnExternalDataBound += uniGrid_OnExternalDataBound; uniGrid.ShowActionsMenu = true; uniGrid.Columns = "NodeID, DocumentName, DocumentNamePath, DocumentCulture, DocumentModifiedWhen, ClassDisplayName, NodeChildNodesCount"; uniGrid.OnBeforeDataReload += uniGrid_OnBeforeDataReload; IDataClass nodeClass = DataClassFactory.NewDataClass("CMS.Tree"); DocumentInfo di = new DocumentInfo(); uniGrid.AllColumns = SqlHelperClass.MergeColumns(SqlHelperClass.MergeColumns(di.ColumnNames), SqlHelperClass.MergeColumns(nodeClass.ColumnNames)); nodeId = QueryHelper.GetInteger("nodeid", 0); serverId = QueryHelper.GetInteger("serverid", 0); if (nodeId > 0) { TreeNode node = TreeProvider.SelectSingleNode(nodeId); if (node != null) { if (node.NodeParentID > 0) { lnkUpperDoc.Attributes["onclick"] = "parent.frames['tasksTree'].RefreshNode(" + node.NodeParentID + "," + node.NodeParentID + ");window.location.href='" + ResolveUrl("~/CMSModules/Staging/Tools/Tasks/DocumentsList.aspx?serverid=") + serverId + "&nodeid=" + node.NodeParentID + "'; return false;"; imgUpperDoc.ImageUrl = GetImageUrl("Design/Controls/Tree/folderup.png"); } else { lnkUpperDoc.Attributes["onclick"] = "return false"; imgUpperDoc.ImageUrl = GetImageUrl("Design/Controls/Tree/folderupdisabled.png"); } string closeLink = "<a href=\"#\"><span class=\"ListingClose\" style=\"cursor: pointer;\" " + "onclick=\"parent.frames['tasksHeader'].selectDocuments = false; window.location.href='" + ResolveUrl("~/CMSModules/Staging/Tools/Tasks/Tasks.aspx?serverid=") + serverId + "&nodeid=" + nodeId + "';" + "var completeObj = parent.frames['tasksHeader'].document.getElementById('pnlComplete');" + "if (completeObj != null){ completeObj.style.display = 'block'; }" + "return false;\">" + GetString("general.close") + "</span></a>"; string docNamePath = "<span class=\"ListingPath\">" + node.DocumentNamePath + "</span>"; lblListingInfo.Text = String.Format(GetString("synchronization.listinginfo"), docNamePath, closeLink); } } }
public void ShouldNotThrowArgumentExceptionIfNoRevisionOnLoadedEntity() { string deletedId = null; string deletedRev = null; var bulkUpdateBatchMock = new Mock<IBulkUpdateBatch>(); bulkUpdateBatchMock .Setup(b => b.Delete(It.IsAny<string>(), It.IsAny<string>())) .Callback( (string id, string rev) => { deletedId = id; deletedRev = rev; }); var documentInfo = new DocumentInfo(EntityWithoutRevision.StandardDocId, "2-1a517022a0c2d4814d51abfedf9bfee7"); var result = documentInfo; var dbApiMock = new Mock<IDatabaseApi>(); dbApiMock .Setup(ca => ca.BulkUpdate(It.IsAny<Action<IBulkUpdateBatch>>())) .Returns<Action<IBulkUpdateBatch>>( updateAction => { updateAction(bulkUpdateBatchMock.Object); return new Dictionary<string, DocumentInfo> {{result.Id, result}} .ToTask<IDictionary<string, DocumentInfo>>(); }); dbApiMock .Setup(ca => ca.RequestDocument(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<AdditionalDocumentProperty>())) .Returns(EntityWithoutRevision.CreateDocumentWithRevision().ToTask()); dbApiMock .Setup(ca => ca.Synchronously).Returns(new SynchronousDatabaseApi(dbApiMock.Object)); var session = new CouchSession(Default.Settings, Mock.Of<ICouchApi>(c => c.Db("testdb") == dbApiMock.Object)); Assert.DoesNotThrow(() => { var entity = session.Synchronously.Load<EntityWithoutRevision>(EntityWithoutRevision.StandardEntityId); session.Delete(entity: entity); session.SaveChanges(); }); Assert.Equal(EntityWithoutRevision.StandardDocId, deletedId); Assert.Equal(EntityWithoutRevision.StandardRevision, deletedRev); }
public DocumentInfo PromptForSaveDocument(DocumentInfo document) { SaveFileDialog dlg = new SaveFileDialog(); dlg.Filter = "Workflow Definition File (*.wdef)|*.wdef|All files|*.*"; dlg.FilterIndex = 0; dlg.OverwritePrompt = true; dlg.AddExtension = true; dlg.CheckPathExists = true; dlg.DefaultExt = "wdef"; if (dlg.ShowDialog() != true) return null; // save the current workflow if (File.Exists(dlg.FileName)) File.Delete(dlg.FileName); return new DocumentInfo() { Content = new FileStream(dlg.FileName, FileMode.OpenOrCreate), Identification = new DocumentIdentification(dlg.FileName) }; }
public static void Run() { // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdf_WorkingDocuments(); //open document Document pdfDocument = new Document(dataDir + "SetFileInfo.pdf"); //specify document information DocumentInfo docInfo = new DocumentInfo(pdfDocument); docInfo.Author = "Aspose"; docInfo.CreationDate = DateTime.Now; docInfo.Keywords = "Aspose.Pdf, DOM, API"; docInfo.ModDate = DateTime.Now; docInfo.Subject = "PDF Information"; docInfo.Title = "Setting PDF Document Information"; //save output document pdfDocument.Save(dataDir + "SetFileInfo_out.pdf"); }
public TaskBuildElement(DocumentInfo Document, ProjectConfig Configuration) { m_Document = Document; m_Configuration = Configuration; }
protected void Page_Load(object sender, EventArgs e) { // Check the current user currentUser = CMSContext.CurrentUser; if (currentUser == null) { return; } // Check 'Read' permission if (currentUser.IsAuthorizedPerResource("cms.blog", "Read")) { readBlogs = true; } if (!RequestHelper.IsPostBack()) { this.drpBlogs.Items.Add(new ListItem(GetString("general.selectall"), "##ALL##")); this.drpBlogs.Items.Add(new ListItem(GetString("blog.selectmyblogs"), "##MYBLOGS##")); } // No cms.blog doc. type if (DataClassInfoProvider.GetDataClass("cms.blog") == null) { RedirectToInformation(GetString("blog.noblogdoctype")); } this.CurrentMaster.DisplaySiteSelectorPanel = true; gridBlogs.OnDataReload += gridBlogs_OnDataReload; gridBlogs.ZeroRowsText = GetString("general.nodatafound"); gridBlogs.ShowActionsMenu = true; gridBlogs.Columns = "BlogID, BlogName, NodeID, DocumentCulture"; // Get all possible columns to retrieve IDataClass nodeClass = DataClassFactory.NewDataClass("CMS.Tree"); DocumentInfo di = new DocumentInfo(); BlogInfo bi = new BlogInfo(); gridBlogs.AllColumns = SqlHelperClass.MergeColumns(SqlHelperClass.MergeColumns(SqlHelperClass.MergeColumns(bi.ColumnNames.ToArray()), SqlHelperClass.MergeColumns(di.ColumnNames.ToArray())), SqlHelperClass.MergeColumns(nodeClass.ColumnNames.ToArray())); DataClassInfo dci = DataClassInfoProvider.GetDataClass("cms.blogpost"); string classId = ""; StringBuilder script = new StringBuilder(); if (dci != null) { classId = dci.ClassID.ToString(); } // Get script to redirect to new blog post page script.Append("function NewPost(parentId, culture) {", " if (parentId != 0) {", " parent.parent.parent.location.href = \"", ResolveUrl("~/CMSDesk/default.aspx"), "?section=content&action=new&nodeid=\" + parentId + \"&classid=", classId, " &culture=\" + culture;", "}}"); // Generate javascript code ltlScript.Text = ScriptHelper.GetScript(script.ToString()); }
public DocumentInfo ResetDocument(DocumentInfo document) { if (String.IsNullOrEmpty(document?.ToString())) return null; if (File.Exists(document.ToString())) File.Delete(document.ToString()); return new DocumentInfo() { Content = new FileStream(document.ToString(), FileMode.OpenOrCreate), Identification = new DocumentIdentification(document.ToString()) }; }
public ICompletionDataList HandleCompletion(MonoDevelop.Ide.Gui.Document document, DocumentInfo info, LocalDocumentInfo localInfo, ProjectDom dom, char currentChar, ref int triggerWordLength) { CodeCompletionContext codeCompletionContext; using (var completion = CreateCompletion(document, info, localInfo, dom, out codeCompletionContext)) { return(completion.HandleCodeCompletion(codeCompletionContext, currentChar, ref triggerWordLength)); } }
static List <CodeAction> GetActions(CodeRefactoringProvider action, string input, out CSharpDiagnosticTestBase.TestWorkspace workspace, out Document doc, CSharpParseOptions parseOptions = null) { TextSpan selectedSpan; TextSpan markedSpan; string text = ParseText(input, out selectedSpan, out markedSpan); workspace = new CSharpDiagnosticTestBase.TestWorkspace(); var projectId = ProjectId.CreateNewId(); var documentId = DocumentId.CreateNewId(projectId); if (parseOptions == null) { parseOptions = new CSharpParseOptions( LanguageVersion.CSharp6, DocumentationMode.Diagnose | DocumentationMode.Parse, SourceCodeKind.Regular, ImmutableArray.Create("DEBUG", "TEST") ); } workspace.Options.WithChangedOption(CSharpFormattingOptions.NewLinesForBracesInControlBlocks, false); workspace.Open(ProjectInfo.Create( projectId, VersionStamp.Create(), "TestProject", "TestProject", LanguageNames.CSharp, null, null, new CSharpCompilationOptions( OutputKind.DynamicallyLinkedLibrary, "", "", "Script", null, OptimizationLevel.Debug, false, true ), parseOptions, new[] { DocumentInfo.Create( documentId, "a.cs", null, SourceCodeKind.Regular, TextLoader.From(TextAndVersion.Create(SourceText.From(text), VersionStamp.Create())) ) }, null, DiagnosticTestBase.DefaultMetadataReferences ) ); doc = workspace.CurrentSolution.GetProject(projectId).GetDocument(documentId); var actions = new List <CodeAction>(); var context = new CodeRefactoringContext(doc, selectedSpan, actions.Add, default(CancellationToken)); action.ComputeRefactoringsAsync(context).Wait(); if (markedSpan.Start > 0) { foreach (var nra in actions.OfType <NRefactoryCodeAction>()) { Assert.AreEqual(markedSpan, nra.TextSpan, "Activation span does not match."); } } return(actions); }
public void OnAdditionalDocumentAdded(DocumentInfo documentInfo) { }
public FormatRip(DocumentInfo info) : base(info, "rip", "RIPscrip", "rip") { }
private IDictionary<string, DocumentInfo> ProcessResponseData(Task<JsonArray> readDataTask) { var responseDescriptors = readDataTask.Result.AsDynamic(); foreach (var responseDescriptor in responseDescriptors) { string errorName = responseDescriptor.error; string documentId = responseDescriptor.id; if (errorName != null) CollectError(documentId, responseDescriptor.ToString()); else { var documentInfo = new DocumentInfo(documentId, (string)responseDescriptor.rev); result[documentInfo.Id] = documentInfo; } } switch (exceptions.Count) { case 0: return result; case 1: throw exceptions[0]; default: throw new AggregateException("Error executing CouchDB bulk update", exceptions); } }
public void UpdateDocumentUrl (DocumentInfo document, string oldUrl, int portalId, int moduleId) { if (document.Url != oldUrl) { var ctrlUrl = new UrlController (); // get tracking data for the old URL var url = ctrlUrl.GetUrlTracking (portalId, oldUrl, moduleId); // delete old URL tracking data DataProvider.Instance ().DeleteUrlTracking (portalId, oldUrl, moduleId); // create new URL tracking data ctrlUrl.UpdateUrl ( portalId, document.Url, url.UrlType, url.LogActivity, url.TrackClicks, moduleId, url.NewWindow); } }
private void UpdateProject(ProjectFileInfo projectFileInfo) { var project = _workspace.CurrentSolution.GetProject(projectFileInfo.WorkspaceId); var unusedDocuments = project.Documents.ToDictionary(d => d.FilePath, d => d.Id); foreach (var file in projectFileInfo.SourceFiles) { if (unusedDocuments.Remove(file)) { continue; } using (var stream = File.OpenRead(file)) { var sourceText = SourceText.From(stream, encoding: Encoding.UTF8); var id = DocumentId.CreateNewId(projectFileInfo.WorkspaceId); var version = VersionStamp.Create(); var loader = TextLoader.From(TextAndVersion.Create(sourceText, version)); _workspace.AddDocument(DocumentInfo.Create(id, file, filePath: file, loader: loader)); } } foreach (var unused in unusedDocuments) { _workspace.RemoveDocument(unused.Value); } var unusedProjectReferences = new HashSet <ProjectReference>(project.ProjectReferences); foreach (var projectReferencePath in projectFileInfo.ProjectReferences) { ProjectFileInfo projectReferenceInfo; if (_context.Projects.TryGetValue(projectReferencePath, out projectReferenceInfo)) { var reference = new ProjectReference(projectReferenceInfo.WorkspaceId); if (unusedProjectReferences.Remove(reference)) { // This reference already exists continue; } _workspace.AddProjectReference(project.Id, reference); } else { _logger.WriteWarning(string.Format("Unable to resolve project reference '{0}' for '{1}'.", projectReferencePath, projectFileInfo.ProjectFilePath)); } } foreach (var unused in unusedProjectReferences) { _workspace.RemoveProjectReference(project.Id, unused); } var unusedAnalyzers = new Dictionary <string, AnalyzerReference>(project.AnalyzerReferences.ToDictionary(a => a.FullPath)); foreach (var analyzerPath in projectFileInfo.Analyzers) { if (!File.Exists(analyzerPath)) { _logger.WriteWarning(string.Format("Unable to resolve assembly '{0}'", analyzerPath)); } else { if (unusedAnalyzers.Remove(analyzerPath)) { continue; } #if ASPNET50 var analyzerReference = new AnalyzerFileReference(analyzerPath); project.AddAnalyzerReference(analyzerReference); #endif } } foreach (var analyzerReference in unusedAnalyzers.Values) { project.RemoveAnalyzerReference(analyzerReference); } var unusedReferences = new HashSet <MetadataReference>(project.MetadataReferences); foreach (var referencePath in projectFileInfo.References) { if (!File.Exists(referencePath)) { _logger.WriteWarning(string.Format("Unable to resolve assembly '{0}'", referencePath)); } else { var metadataReference = _metadataReferenceCache.GetMetadataReference(referencePath); if (unusedReferences.Remove(metadataReference)) { continue; } _logger.WriteVerbose(string.Format("Adding reference '{0}' to '{1}'.", referencePath, projectFileInfo.ProjectFilePath)); _workspace.AddMetadataReference(project.Id, metadataReference); } } foreach (var reference in unusedReferences) { _workspace.RemoveMetadataReference(project.Id, reference); } }
public void Initalize(IConfiguration configuration) { _options = new DnxOptions(); ConfigurationBinder.Bind(configuration, _options); _dnxPaths = new DnxPaths(_env, _options, _loggerFactory); _packagesRestoreTool = new PackagesRestoreTool(_options, _emitter, _context, _dnxPaths);; _designTimeHostManager = new DesignTimeHostManager(_loggerFactory, _dnxPaths); var runtimePath = _dnxPaths.RuntimePath; _context.RuntimePath = runtimePath.Value; _context.Options = _options; if (!ScanForProjects()) { // No DNX projects found so do nothing _logger.LogInformation("No project.json based projects found"); return; } if (_context.RuntimePath == null) { // There is no default dnx found so do nothing _logger.LogInformation("No default runtime found"); _emitter.Emit(EventTypes.Error, runtimePath.Error); return; } var wh = new ManualResetEventSlim(); _designTimeHostManager.Start(_context.HostId, port => { var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.Connect(new IPEndPoint(IPAddress.Loopback, port)); var networkStream = new NetworkStream(socket); _logger.LogInformation("Connected"); _context.DesignTimeHostPort = port; _context.Connection = new ProcessingQueue(networkStream, _logger); _context.Connection.OnReceive += m => { var project = _context.Projects[m.ContextId]; if (m.MessageType == "ProjectInformation") { var val = m.Payload.ToObject <ProjectMessage>(); project.Name = val.Name; project.GlobalJsonPath = val.GlobalJsonPath; project.Configurations = val.Configurations; project.Commands = val.Commands; project.ProjectSearchPaths = val.ProjectSearchPaths; this._emitter.Emit(EventTypes.ProjectChanged, new ProjectInformationResponse() { { nameof(DnxProject), new DnxProject(project) } }); var unprocessed = project.ProjectsByFramework.Keys.ToList(); foreach (var frameworkData in val.Frameworks) { unprocessed.Remove(frameworkData.FrameworkName); var frameworkProject = project.ProjectsByFramework.GetOrAdd(frameworkData.FrameworkName, framework => { return(new FrameworkProject(project, frameworkData)); }); var id = frameworkProject.ProjectId; if (_workspace.CurrentSolution.ContainsProject(id)) { continue; } else { var projectInfo = ProjectInfo.Create( id, VersionStamp.Create(), val.Name + "+" + frameworkData.ShortName, val.Name, LanguageNames.CSharp, project.Path); _workspace.AddProject(projectInfo); _context.WorkspaceMapping[id] = frameworkProject; } lock (frameworkProject.PendingProjectReferences) { var reference = new Microsoft.CodeAnalysis.ProjectReference(id); foreach (var referenceId in frameworkProject.PendingProjectReferences) { _workspace.AddProjectReference(referenceId, reference); } frameworkProject.PendingProjectReferences.Clear(); } } // Remove old projects foreach (var frameworkName in unprocessed) { FrameworkProject frameworkProject; project.ProjectsByFramework.TryRemove(frameworkName, out frameworkProject); _workspace.RemoveProject(frameworkProject.ProjectId); } } // This is where we can handle messages and update the // language service else if (m.MessageType == "References") { // References as well as the dependency graph information var val = m.Payload.ToObject <ReferencesMessage>(); var frameworkProject = project.ProjectsByFramework[val.Framework.FrameworkName]; var projectId = frameworkProject.ProjectId; var metadataReferences = new List <MetadataReference>(); var projectReferences = new List <Microsoft.CodeAnalysis.ProjectReference>(); var removedFileReferences = frameworkProject.FileReferences.ToDictionary(p => p.Key, p => p.Value); var removedRawReferences = frameworkProject.RawReferences.ToDictionary(p => p.Key, p => p.Value); var removedProjectReferences = frameworkProject.ProjectReferences.ToDictionary(p => p.Key, p => p.Value); foreach (var file in val.FileReferences) { if (removedFileReferences.Remove(file)) { continue; } var metadataReference = _metadataFileReferenceCache.GetMetadataReference(file); frameworkProject.FileReferences[file] = metadataReference; metadataReferences.Add(metadataReference); } foreach (var rawReference in val.RawReferences) { if (removedRawReferences.Remove(rawReference.Key)) { continue; } var metadataReference = MetadataReference.CreateFromImage(rawReference.Value); frameworkProject.RawReferences[rawReference.Key] = metadataReference; metadataReferences.Add(metadataReference); } foreach (var projectReference in val.ProjectReferences) { if (removedProjectReferences.Remove(projectReference.Path)) { continue; } int projectReferenceContextId; if (!_context.ProjectContextMapping.TryGetValue(projectReference.Path, out projectReferenceContextId)) { projectReferenceContextId = AddProject(projectReference.Path); } var referencedProject = _context.Projects[projectReferenceContextId]; var referencedFrameworkProject = referencedProject.ProjectsByFramework.GetOrAdd(projectReference.Framework.FrameworkName, framework => { return(new FrameworkProject(referencedProject, projectReference.Framework)); }); var projectReferenceId = referencedFrameworkProject.ProjectId; if (_workspace.CurrentSolution.ContainsProject(projectReferenceId)) { projectReferences.Add(new Microsoft.CodeAnalysis.ProjectReference(projectReferenceId)); } else { lock (referencedFrameworkProject.PendingProjectReferences) { referencedFrameworkProject.PendingProjectReferences.Add(projectId); } } referencedFrameworkProject.ProjectDependeees[project.Path] = projectId; frameworkProject.ProjectReferences[projectReference.Path] = projectReferenceId; } foreach (var reference in metadataReferences) { _workspace.AddMetadataReference(projectId, reference); } foreach (var projectReference in projectReferences) { _workspace.AddProjectReference(projectId, projectReference); } foreach (var pair in removedProjectReferences) { _workspace.RemoveProjectReference(projectId, new Microsoft.CodeAnalysis.ProjectReference(pair.Value)); frameworkProject.ProjectReferences.Remove(pair.Key); // TODO: Update the dependee's list } foreach (var pair in removedFileReferences) { _workspace.RemoveMetadataReference(projectId, pair.Value); frameworkProject.FileReferences.Remove(pair.Key); } foreach (var pair in removedRawReferences) { _workspace.RemoveMetadataReference(projectId, pair.Value); frameworkProject.RawReferences.Remove(pair.Key); } } else if (m.MessageType == "Dependencies") { var val = m.Payload.ToObject <DependenciesMessage>(); var unresolvedDependencies = val.Dependencies.Values .Where(dep => dep.Type == "Unresolved"); if (unresolvedDependencies.Any()) { _logger.LogInformation("Project {0} has these unresolved references: {1}", project.Path, string.Join(", ", unresolvedDependencies.Select(d => d.Name))); _emitter.Emit(EventTypes.UnresolvedDependencies, new UnresolvedDependenciesMessage() { FileName = project.Path, UnresolvedDependencies = unresolvedDependencies.Select(d => new PackageDependency() { Name = d.Name, Version = d.Version }) }); _packagesRestoreTool.Run(project); } } else if (m.MessageType == "CompilerOptions") { // Configuration and compiler options var val = m.Payload.ToObject <CompilationOptionsMessage>(); var projectId = project.ProjectsByFramework[val.Framework.FrameworkName].ProjectId; var options = val.CompilationOptions.CompilationOptions; var specificDiagnosticOptions = options.SpecificDiagnosticOptions .ToDictionary(p => p.Key, p => (ReportDiagnostic)p.Value); var csharpOptions = new CSharpCompilationOptions( outputKind: (OutputKind)options.OutputKind, optimizationLevel: (OptimizationLevel)options.OptimizationLevel, platform: (Platform)options.Platform, generalDiagnosticOption: (ReportDiagnostic)options.GeneralDiagnosticOption, warningLevel: options.WarningLevel, allowUnsafe: options.AllowUnsafe, concurrentBuild: options.ConcurrentBuild, specificDiagnosticOptions: specificDiagnosticOptions ); var parseOptions = new CSharpParseOptions(val.CompilationOptions.LanguageVersion, preprocessorSymbols: val.CompilationOptions.Defines); _workspace.SetCompilationOptions(projectId, csharpOptions); _workspace.SetParseOptions(projectId, parseOptions); } else if (m.MessageType == "Sources") { // The sources to feed to the language service var val = m.Payload.ToObject <SourcesMessage>(); project.SourceFiles = val.Files .Where(fileName => Path.GetExtension(fileName) == ".cs") .ToList(); var frameworkProject = project.ProjectsByFramework[val.Framework.FrameworkName]; var projectId = frameworkProject.ProjectId; var unprocessed = new HashSet <string>(frameworkProject.Documents.Keys); foreach (var file in project.SourceFiles) { if (unprocessed.Remove(file)) { continue; } using (var stream = File.OpenRead(file)) { var sourceText = SourceText.From(stream, encoding: Encoding.UTF8); var id = DocumentId.CreateNewId(projectId); var version = VersionStamp.Create(); frameworkProject.Documents[file] = id; var loader = TextLoader.From(TextAndVersion.Create(sourceText, version)); _workspace.AddDocument(DocumentInfo.Create(id, file, filePath: file, loader: loader)); } } foreach (var file in unprocessed) { var docId = frameworkProject.Documents[file]; frameworkProject.Documents.Remove(file); _workspace.RemoveDocument(docId); } frameworkProject.Loaded = true; } else if (m.MessageType == "Error") { var val = m.Payload.ToObject <Microsoft.Framework.DesignTimeHost.Models.OutgoingMessages.ErrorMessage>(); _logger.LogError(val.Message); } if (project.ProjectsByFramework.Values.All(p => p.Loaded)) { wh.Set(); } }; // Start the message channel _context.Connection.Start(); // Initialize the DNX projects Initialize(); }); wh.Wait(); }
public void TestUpdatedDocumentHasTextVersion() { var pid = ProjectId.CreateNewId(); var text = SourceText.From("public class C { }"); var version = VersionStamp.Create(); var docInfo = DocumentInfo.Create(DocumentId.CreateNewId(pid), "c.cs", loader: TextLoader.From(TextAndVersion.Create(text, version))); var projInfo = ProjectInfo.Create( pid, version: VersionStamp.Default, name: "TestProject", assemblyName: "TestProject.dll", language: LanguageNames.CSharp, documents: new[] { docInfo }); using (var ws = new AdhocWorkspace()) { ws.AddProject(projInfo); SourceText currentText; VersionStamp currentVersion; var doc = ws.CurrentSolution.GetDocument(docInfo.Id); Assert.Equal(false, doc.TryGetText(out currentText)); Assert.Equal(false, doc.TryGetTextVersion(out currentVersion)); // cause text to load and show that TryGet now works for text and version currentText = doc.GetTextAsync().Result; Assert.Equal(true, doc.TryGetText(out currentText)); Assert.Equal(true, doc.TryGetTextVersion(out currentVersion)); Assert.Equal(version, currentVersion); // change document var root = doc.GetSyntaxRootAsync().Result; var newRoot = root.WithAdditionalAnnotations(new SyntaxAnnotation()); Assert.NotSame(root, newRoot); var newDoc = doc.WithSyntaxRoot(newRoot); Assert.NotSame(doc, newDoc); // text is now unavailable since it must be constructed from tree Assert.Equal(false, newDoc.TryGetText(out currentText)); // version is available because it is cached Assert.Equal(true, newDoc.TryGetTextVersion(out currentVersion)); // access it the hard way var actualVersion = newDoc.GetTextVersionAsync().Result; // version is the same Assert.Equal(currentVersion, actualVersion); // accessing text version did not cause text to be constructed. Assert.Equal(false, newDoc.TryGetText(out currentText)); // now access text directly (force it to be constructed) var actualText = newDoc.GetTextAsync().Result; actualVersion = newDoc.GetTextVersionAsync().Result; // prove constructing text did not introduce a new version Assert.Equal(currentVersion, actualVersion); } }
public RoslynCodeDocument(ICodeEditor codeEditor, DocumentInfo documentInfo, string nameNoExtension) { this.codeEditor = codeEditor; Info = documentInfo; NameNoExtension = nameNoExtension; }
/// <summary> /// Archivia il documento di un protocollo. /// </summary> /// <param name="sessionId">Identificativo della sessione di lavoro.</param> /// <param name="protocol">Protocollo di riferimento.</param> /// <returns></returns> private int archiveDocument(string sessionId, Protocol protocol) { if (!protocol.IdDocument.HasValue || protocol.IdDocument < 1) { throw new Exception("archiveDocument: IdDocument del protocollo mancante o non valido."); } // Recupero il documento da Biblos. DocumentInfo document = null; try { document = new BiblosDocumentInfo(protocol.Location.ProtBiblosDSDB, protocol.IdDocument.Value); } catch (Exception ex) { string message = "archiveDocument: errore in recupero documento da Biblos. {0} - {1}"; message = string.Format(message, ex.Source, ex.Message); throw new Exception(message, ex); } // Recupero il dizionario degli attributi. IDictionary <string, string> attributes = null; try { attributes = getDocumentAttributes(protocol); } catch (Exception ex) { string message = "archiveDocument: : errore in recupero dizionario degli attributi. {0} - {1}"; message = string.Format(message, ex.Source, ex.Message); throw new Exception(message, ex); } // Archivio il documento. int archived = -1; try { var pid = getProductId(document.Name); var fields = attributes.Keys.ToArray(); var values = attributes.Values.ToArray(); var message = string.Format("TopMedia Archive - sessionid: {0}, attachmenttype: {1}, fields: {2}, values: {3}, name: {4}, stream: {5}, pid: {6}", sessionId, DocSuiteContext.Current.ProtocolEnv.TopMediaParameters.AttachmentType, fields.Length, values.Length, document.Name, document.Stream.Length, pid); FileLogger.Info("FileLog", message); #if DEBUG archived = 123; #else archived = Services.TopMedia.Service.Archive(sessionId, DocSuiteContext.Current.ProtocolEnv.TopMediaParameters.DocumentType, fields, values, document.Name, document.Stream, pid); Services.TopMedia.Service.TryLogout(sessionId); #endif FileLogger.Info("FileLog", "archived: " + archived.ToString()); } catch (Exception ex) { string message = "archiveDocument: errore in archiviazione documento. {0} - {1}"; message = string.Format(message, ex.Source, ex.Message); throw new Exception(message, ex); } return(archived); }
private async Task <Solution> GetSolutionAsync(ISolutionSynchronizationService service, PinnedRemotableDataScope syncScope) { var workspace = new AdhocWorkspace(); var solutionObject = await service.GetValueAsync <SolutionStateChecksums>(syncScope.SolutionChecksum); var solutionInfo = await service.GetValueAsync <SolutionInfo.SolutionAttributes>(solutionObject.Info).ConfigureAwait(false); var projects = new List <ProjectInfo>(); foreach (var projectObject in solutionObject.Projects.ToProjectObjects(service)) { var projectInfo = await service.GetValueAsync <ProjectInfo.ProjectAttributes>(projectObject.Info).ConfigureAwait(false); if (!workspace.Services.IsSupported(projectInfo.Language)) { continue; } var documents = new List <DocumentInfo>(); foreach (var documentObject in projectObject.Documents.ToDocumentObjects(service)) { var documentInfo = await service.GetValueAsync <DocumentInfo.DocumentAttributes>(documentObject.Info).ConfigureAwait(false); var text = await service.GetValueAsync <SourceText>(documentObject.Text).ConfigureAwait(false); // TODO: do we need version? documents.Add( DocumentInfo.Create( documentInfo.Id, documentInfo.Name, documentInfo.Folders, documentInfo.SourceCodeKind, TextLoader.From(TextAndVersion.Create(text, VersionStamp.Create())), documentInfo.FilePath, documentInfo.IsGenerated)); } var p2p = new List <ProjectReference>(); foreach (var checksum in projectObject.ProjectReferences) { var reference = await service.GetValueAsync <ProjectReference>(checksum).ConfigureAwait(false); p2p.Add(reference); } var metadata = new List <MetadataReference>(); foreach (var checksum in projectObject.MetadataReferences) { var reference = await service.GetValueAsync <MetadataReference>(checksum).ConfigureAwait(false); metadata.Add(reference); } var analyzers = new List <AnalyzerReference>(); foreach (var checksum in projectObject.AnalyzerReferences) { var reference = await service.GetValueAsync <AnalyzerReference>(checksum).ConfigureAwait(false); analyzers.Add(reference); } var additionals = new List <DocumentInfo>(); foreach (var documentObject in projectObject.AdditionalDocuments.ToDocumentObjects(service)) { var documentInfo = await service.GetValueAsync <DocumentInfo.DocumentAttributes>(documentObject.Info).ConfigureAwait(false); var text = await service.GetValueAsync <SourceText>(documentObject.Text).ConfigureAwait(false); // TODO: do we need version? additionals.Add( DocumentInfo.Create( documentInfo.Id, documentInfo.Name, documentInfo.Folders, documentInfo.SourceCodeKind, TextLoader.From(TextAndVersion.Create(text, VersionStamp.Create())), documentInfo.FilePath, documentInfo.IsGenerated)); } var compilationOptions = await service.GetValueAsync <CompilationOptions>(projectObject.CompilationOptions).ConfigureAwait(false); var parseOptions = await service.GetValueAsync <ParseOptions>(projectObject.ParseOptions).ConfigureAwait(false); projects.Add( ProjectInfo.Create( projectInfo.Id, projectInfo.Version, projectInfo.Name, projectInfo.AssemblyName, projectInfo.Language, projectInfo.FilePath, projectInfo.OutputFilePath, compilationOptions, parseOptions, documents, p2p, metadata, analyzers, additionals, projectInfo.IsSubmission)); } return(workspace.AddSolution(SolutionInfo.Create(solutionInfo.Id, solutionInfo.Version, solutionInfo.FilePath, projects))); }
public void OnDocumentAdded(DocumentInfo documentInfo) { }
protected void Page_Load(object sender, EventArgs e) { gridLanguages.FilteredZeroRowsText = GetString("transman.nodocumentculture"); gridLanguages.OnDataReload += gridDocuments_OnDataReload; gridLanguages.OnExternalDataBound += gridLanguages_OnExternalDataBound; gridLanguages.ShowActionsMenu = true; gridLanguages.Columns = "DocumentName, Published"; IDataClass nodeClass = DataClassFactory.NewDataClass("CMS.Tree"); DocumentInfo di = new DocumentInfo(); gridLanguages.AllColumns = SqlHelperClass.MergeColumns(SqlHelperClass.MergeColumns(di.ColumnNames), SqlHelperClass.MergeColumns(nodeClass.ColumnNames)); pnlContainer.Enabled = !DocumentManager.ProcessingAction; }
public override bool HandleExport(ExportCharsetInfo Info, TextBox EditOutput, DocumentInfo DocInfo) { System.Windows.Forms.SaveFileDialog saveDlg = new System.Windows.Forms.SaveFileDialog(); saveDlg.FileName = Info.Charset.ExportFilename; saveDlg.Title = "Export Charset to"; saveDlg.Filter = "Charset|*.chr|All Files|*.*"; if (DocInfo.Project != null) { saveDlg.InitialDirectory = DocInfo.Project.Settings.BasePath; } if (saveDlg.ShowDialog() != System.Windows.Forms.DialogResult.OK) { return(false); } GR.Memory.ByteBuffer charSet = new GR.Memory.ByteBuffer(); List <int> exportIndices = Info.ExportIndices; foreach (int i in exportIndices) { charSet.Append(Info.Charset.Characters[i].Tile.Data); } if (checkPrefixLoadAddress.Checked) { ushort address = GR.Convert.ToU16(editPrefixLoadAddress.Text, 16); var addressData = new ByteBuffer(); addressData.AppendU16(address); charSet = addressData + charSet; } GR.IO.File.WriteAllBytes(saveDlg.FileName, charSet); return(true); }
/// <summary> /// Deletes the resource, accociated with the document (only files and URLs are supported). /// </summary> /// <param name="document">Document.</param> /// <param name="portalId">Portal identifier.</param> public int DeleteDocumentResource (DocumentInfo document, int portalId) { // count resource references var count = GetObjects<DocumentInfo> ("WHERE [ItemID] <> @0 AND [Url] = @1", document.ItemId, document.Url).Count (); // if no other document references it if (count == 0) { switch (Globals.GetURLType (document.Url)) { // delete file case TabType.File: var file = FileManager.Instance.GetFile (Utils.GetResourceId (document.Url)); if (file != null) { FileManager.Instance.DeleteFile (file); } break; // delete URL case TabType.Url: new UrlController ().DeleteUrl (portalId, document.Url); break; } } return count; }
public static async Task <CompilerInvocation> CreateFromJsonAsync(string jsonContents) { var invocationInfo = JsonConvert.DeserializeObject <CompilerInvocationInfo>(jsonContents); // We will use a Workspace to simplify the creation of the compilation, but will be careful not to return the Workspace instance from this class. // We will still provide the language services which are used by the generator itself, but we don't tie it to a Workspace object so we can // run this as an in-proc source generator if one day desired. var workspace = new AdhocWorkspace(); var languageName = GetLanguageName(invocationInfo); var languageServices = workspace.Services.GetLanguageServices(languageName); var mapPath = GetPathMapper(invocationInfo); var splitCommandLine = CommandLineParser.SplitCommandLineIntoArguments(invocationInfo.Arguments, removeHashComments: false).ToList(); // Unfortunately for us there are a few paths that get directly read by the command line parse which we need to remap, // such as /ruleset files. So let's go through and process them now. for (var i = 0; i < splitCommandLine.Count; i++) { const string RuleSetSwitch = "/ruleset:"; if (splitCommandLine[i].StartsWith(RuleSetSwitch, StringComparison.Ordinal)) { var rulesetPath = splitCommandLine[i].Substring(RuleSetSwitch.Length); var quoted = rulesetPath.Length > 2 && rulesetPath.StartsWith("\"", StringComparison.Ordinal) && rulesetPath.EndsWith("\"", StringComparison.Ordinal); if (quoted) { rulesetPath = rulesetPath.Substring(1, rulesetPath.Length - 2); } rulesetPath = mapPath(rulesetPath); if (quoted) { rulesetPath = "\"" + rulesetPath + "\""; } splitCommandLine[i] = RuleSetSwitch + rulesetPath; } } var commandLineParserService = languageServices.GetRequiredService <ICommandLineParserService>(); var parsedCommandLine = commandLineParserService.Parse(splitCommandLine, Path.GetDirectoryName(invocationInfo.ProjectFilePath), isInteractive: false, sdkDirectory: null); var projectId = ProjectId.CreateNewId(invocationInfo.ProjectFilePath); var projectInfo = ProjectInfo.Create( projectId, VersionStamp.Default, name: Path.GetFileNameWithoutExtension(invocationInfo.ProjectFilePath), assemblyName: parsedCommandLine.CompilationName !, language: languageName, filePath: invocationInfo.ProjectFilePath, outputFilePath: parsedCommandLine.OutputFileName, parsedCommandLine.CompilationOptions, parsedCommandLine.ParseOptions, parsedCommandLine.SourceFiles.Select(s => CreateDocumentInfo(unmappedPath: s.Path)), metadataReferences: parsedCommandLine.MetadataReferences.Select(r => MetadataReference.CreateFromFile(mapPath(r.Reference), r.Properties)), additionalDocuments: parsedCommandLine.AdditionalFiles.Select(f => CreateDocumentInfo(unmappedPath: f.Path))) .WithAnalyzerConfigDocuments(parsedCommandLine.AnalyzerConfigPaths.Select(CreateDocumentInfo)); workspace.AddProject(projectInfo); var compilation = await workspace.CurrentSolution.GetProject(projectId) !.GetRequiredCompilationAsync(CancellationToken.None); return(new CompilerInvocation(compilation, languageServices, invocationInfo.ProjectFilePath)); // Local methods: DocumentInfo CreateDocumentInfo(string unmappedPath) { var mappedPath = mapPath(unmappedPath); return(DocumentInfo.Create( DocumentId.CreateNewId(projectId, mappedPath), name: mappedPath, filePath: mappedPath, loader: new FileTextLoader(mappedPath, parsedCommandLine.Encoding))); } }
public Task SetErrorState(DocumentInfo document, string errorInfo, CancellationToken cancellationToken) { return(UpdateStateInternal(document, InProcessDocumentState.Error, errorInfo, cancellationToken)); }
async Task InitializeAsync(ITextBuffer buffer, string code, MetadataReference[] refs, string languageName, ISynchronousTagger <IClassificationTag> tagger, CompilationOptions compilationOptions, ParseOptions parseOptions) { using (var workspace = new AdhocWorkspace(RoslynMefHostServices.DefaultServices)) { var documents = new List <DocumentInfo>(); var projectId = ProjectId.CreateNewId(); documents.Add(DocumentInfo.Create(DocumentId.CreateNewId(projectId), "main.cs", null, SourceCodeKind.Regular, TextLoader.From(buffer.AsTextContainer(), VersionStamp.Create()))); var projectInfo = ProjectInfo.Create(projectId, VersionStamp.Create(), "compilecodeproj", Guid.NewGuid().ToString(), languageName, compilationOptions: compilationOptions .WithOptimizationLevel(OptimizationLevel.Release) .WithPlatform(Platform.AnyCpu) .WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default), parseOptions: parseOptions, documents: documents, metadataReferences: refs, isSubmission: false, hostObjectType: null); workspace.AddProject(projectInfo); foreach (var doc in documents) { workspace.OpenDocument(doc.Id); } buffer.Replace(new Span(0, buffer.CurrentSnapshot.Length), code); { // Initialize classification code paths var spans = new NormalizedSnapshotSpanCollection(new SnapshotSpan(buffer.CurrentSnapshot, 0, buffer.CurrentSnapshot.Length)); foreach (var tagSpan in tagger.GetTags(spans, CancellationToken.None)) { } } { // Initialize completion code paths var info = CompletionInfo.Create(buffer.CurrentSnapshot); Debug2.Assert(!(info is null)); if (!(info is null)) { var completionTrigger = CompletionTrigger.Invoke; var completionList = await info.Value.CompletionService.GetCompletionsAsync(info.Value.Document, 0, completionTrigger); } } { // Initialize signature help code paths var info = SignatureHelpInfo.Create(buffer.CurrentSnapshot); Debug2.Assert(!(info is null)); if (!(info is null)) { int sigHelpIndex = code.IndexOf("sighelp"); Debug.Assert(sigHelpIndex >= 0); var triggerInfo = new SignatureHelpTriggerInfo(SignatureHelpTriggerReason.InvokeSignatureHelpCommand); var items = await info.Value.SignatureHelpService.GetItemsAsync(info.Value.Document, sigHelpIndex, triggerInfo); } } { // Initialize quick info code paths var info = QuickInfoState.Create(buffer.CurrentSnapshot); Debug2.Assert(!(info is null)); if (!(info is null)) { int quickInfoIndex = code.IndexOf("Equals"); Debug.Assert(quickInfoIndex >= 0); var item = await info.Value.QuickInfoService.GetItemAsync(info.Value.Document, quickInfoIndex); } } } }
public ICompletionDataList HandlePopupCompletion(MonoDevelop.Ide.Gui.Document document, DocumentInfo info, LocalDocumentInfo localInfo, ProjectDom dom) { CodeCompletionContext codeCompletionContext; using (var completion = CreateCompletion(document, info, localInfo, dom, out codeCompletionContext)) { return(completion.CodeCompletionCommand(codeCompletionContext)); } }
private void UpdateProject(ProjectFileInfo projectFileInfo) { var project = _workspace.CurrentSolution.GetProject(projectFileInfo.WorkspaceId); var unusedDocuments = project.Documents.ToDictionary(d => d.FilePath, d => d.Id); foreach (var file in projectFileInfo.SourceFiles) { if (unusedDocuments.Remove(file)) { continue; } using (var stream = File.OpenRead(file)) { var sourceText = SourceText.From(stream, encoding: Encoding.UTF8); var id = DocumentId.CreateNewId(projectFileInfo.WorkspaceId); var version = VersionStamp.Create(); var loader = TextLoader.From(TextAndVersion.Create(sourceText, version)); _workspace.AddDocument(DocumentInfo.Create(id, file, filePath: file, loader: loader)); } } if (projectFileInfo.SpecifiedLanguageVersion.HasValue || projectFileInfo.DefineConstants != null) { var parseOptions = projectFileInfo.SpecifiedLanguageVersion.HasValue ? new CSharpParseOptions(projectFileInfo.SpecifiedLanguageVersion.Value) : new CSharpParseOptions(); if (projectFileInfo.DefineConstants != null && projectFileInfo.DefineConstants.Any()) { parseOptions = parseOptions.WithPreprocessorSymbols(projectFileInfo.DefineConstants); } _workspace.SetParseOptions(project.Id, parseOptions); } foreach (var unused in unusedDocuments) { _workspace.RemoveDocument(unused.Value); } var unusedProjectReferences = new HashSet <ProjectReference>(project.ProjectReferences); foreach (var projectReferencePath in projectFileInfo.ProjectReferences) { ProjectFileInfo projectReferenceInfo; if (_context.Projects.TryGetValue(projectReferencePath, out projectReferenceInfo)) { var reference = new ProjectReference(projectReferenceInfo.WorkspaceId); if (unusedProjectReferences.Remove(reference)) { // This reference already exists continue; } _workspace.AddProjectReference(project.Id, reference); } else { _logger.LogWarning($"Unable to resolve project reference '{projectReferencePath}' for '{projectFileInfo}'."); } } foreach (var unused in unusedProjectReferences) { _workspace.RemoveProjectReference(project.Id, unused); } var unusedAnalyzers = new Dictionary <string, AnalyzerReference>(project.AnalyzerReferences.ToDictionary(a => a.FullPath)); foreach (var analyzerPath in projectFileInfo.Analyzers) { if (!File.Exists(analyzerPath)) { _logger.LogWarning($"Unable to resolve assembly '{analyzerPath}'"); } else { if (unusedAnalyzers.Remove(analyzerPath)) { continue; } #if DNX451 var analyzerReference = new AnalyzerFileReference(analyzerPath); project.AddAnalyzerReference(analyzerReference); #endif } } foreach (var analyzerReference in unusedAnalyzers.Values) { project.RemoveAnalyzerReference(analyzerReference); } var unusedReferences = new HashSet <MetadataReference>(project.MetadataReferences); foreach (var referencePath in projectFileInfo.References) { if (!File.Exists(referencePath)) { _logger.LogWarning($"Unable to resolve assembly '{referencePath}'"); } else { var metadataReference = _metadataReferenceCache.GetMetadataReference(referencePath); if (unusedReferences.Remove(metadataReference)) { continue; } _logger.LogVerbose($"Adding reference '{referencePath}' to '{projectFileInfo.ProjectFilePath}'."); _workspace.AddMetadataReference(project.Id, metadataReference); } } foreach (var reference in unusedReferences) { _workspace.RemoveMetadataReference(project.Id, reference); } }
CSharpTextEditorCompletion CreateCompletion(MonoDevelop.Ide.Gui.Document document, DocumentInfo info, LocalDocumentInfo localInfo, ProjectDom dom, out CodeCompletionContext codeCompletionContext) { var doc = new Mono.TextEditor.Document() { Text = localInfo.LocalDocument, }; var documentLocation = doc.OffsetToLocation(localInfo.CaretPosition); codeCompletionContext = new CodeCompletionContext() { TriggerOffset = localInfo.CaretPosition, TriggerLine = documentLocation.Line + 1, TriggerLineOffset = documentLocation.Column + 1, }; var r = new System.IO.StringReader(localInfo.LocalDocument); using (var parser = ICSharpCode.NRefactory.ParserFactory.CreateParser(SupportedLanguage.CSharp, r)) { parser.Parse(); return(new CSharpTextEditorCompletion(document) { ParsedUnit = parser.CompilationUnit, Dom = dom, }); } }
private void comboBoxImputFormat_SelectionChanged(object sender, SelectionChangedEventArgs e) { DocumentInfo input = this.comboBoxImputFormat.SelectedItem as DocumentInfo; this.comboBoxOuputFormat.ItemsSource = DocumentFactory.Instance.BookFilters.Where(p => input.CanConvertTo.Contains(p.Type)); }
bool BuildElement(DocumentInfo Doc, string ConfigSetting, string AdditionalPredefines, bool OutputMessages, out Types.BuildInfo BuildInfo, out Types.ASM.FileInfo FileInfo) { BuildInfo = new C64Studio.Types.BuildInfo(); BuildInfo.TargetFile = ""; BuildInfo.TargetType = Types.CompileTargetType.NONE; FileInfo = null; Types.ASM.FileInfo combinedFileInfo = null; try { if (Doc.Element != null) { Doc.Element.CompileTarget = Types.CompileTargetType.NONE; Doc.Element.CompileTargetFile = null; // check dependencies foreach (var dependency in Doc.Element.ForcedDependency.DependentOnFile) { ProjectElement elementDependency = Doc.Project.GetElementByFilename(dependency.Filename); if (elementDependency == null) { Core.AddToOutput("Could not find dependency for " + dependency.Filename + System.Environment.NewLine); return(false); } Types.ASM.FileInfo dependencyFileInfo = null; // skip building if not required if (!Core.Compiling.NeedsRebuild(elementDependency.DocumentInfo, ConfigSetting)) { Core.AddToOutput("Dependency " + dependency.Filename + " is current for config " + ConfigSetting + System.Environment.NewLine); if ((Doc.Type == ProjectElement.ElementType.ASM_SOURCE) || (Doc.Type == ProjectElement.ElementType.BASIC_SOURCE)) { dependencyFileInfo = elementDependency.DocumentInfo.ASMFileInfo; //Debug.Log( "Doc " + Doc.Text + " receives " + dependencyFileInfo.Labels.Count + " dependency labels from dependency " + dependency.Filename ); } } else { Types.BuildInfo tempInfo = new C64Studio.Types.BuildInfo(); if (!BuildElement(elementDependency.DocumentInfo, ConfigSetting, null, false, out tempInfo, out dependencyFileInfo)) { return(false); } } // include symbols from dependency if (dependency.IncludeSymbols) { if (combinedFileInfo == null) { combinedFileInfo = new C64Studio.Types.ASM.FileInfo(); } // merge label info if (dependencyFileInfo != null) { foreach (var entry in dependencyFileInfo.Labels) { if (!combinedFileInfo.Labels.ContainsKey(entry.Key)) { combinedFileInfo.Labels.Add(entry.Key, entry.Value); } } //Debug.Log( "Doc " + Doc.Text + " receives " + dependencyFileInfo.Labels.Count + " dependency labels from dependency " + dependency.Filename ); } } } } if (!Doc.Compilable) { // not buildable // TODO - Autoexport? return(true); } ToolInfo tool = Core.DetermineTool(Doc, false); ProjectElement.PerConfigSettings configSetting = null; Parser.ParserBase parser = Core.DetermineParser(Doc); if (Doc.Element != null) { if (!Doc.Element.Settings.ContainsKey(ConfigSetting)) { Doc.Element.Settings.Add(ConfigSetting, new ProjectElement.PerConfigSettings()); } configSetting = Doc.Element.Settings[ConfigSetting]; if (!string.IsNullOrEmpty(configSetting.PreBuild)) { Core.AddToOutput("Running pre build step on " + Doc.Element.Name + System.Environment.NewLine); if (!Core.Executing.RunCommand(Doc, "pre build", configSetting.PreBuild)) { return(false); } } if (configSetting.PreBuildChain.Active) { if (!BuildChain(configSetting.PreBuildChain, "pre build chain", OutputMessages)) { return(false); } } Core.AddToOutput("Running build on " + Doc.Element.Name + " with configuration " + ConfigSetting + System.Environment.NewLine); } else { Core.AddToOutput("Running build on " + Doc.DocumentFilename + System.Environment.NewLine); } // include previous symbols string additionalPredefines = null; if (parser is Parser.ASMFileParser) { ((Parser.ASMFileParser)parser).InitialFileInfo = combinedFileInfo; if (combinedFileInfo != null) { //Debug.Log( "Doc " + Doc.Text + " receives " + combinedFileInfo.Labels.Count + " initial labels" ); } additionalPredefines = AdditionalPredefines; } else if (parser is Parser.BasicFileParser) { // BASIC may receive symbols from assembly ((Parser.BasicFileParser)parser).InitialFileInfo = combinedFileInfo; ((Parser.BasicFileParser)parser).SetBasicVersion(((Parser.BasicFileParser)parser).Settings.Version); ((Parser.BasicFileParser)parser).Settings.UpperCaseMode = !((SourceBasicEx)Doc.BaseDoc).m_LowerCaseMode; if (combinedFileInfo != null) { //Debug.Log( "Doc " + Doc.Text + " receives " + combinedFileInfo.Labels.Count + " initial labels" ); } Doc.ASMFileInfo = combinedFileInfo; } parser.AssembledOutput = null; if ((configSetting != null) && (!string.IsNullOrEmpty(configSetting.CustomBuild))) { Core.AddToOutput("Running custom build step on " + Doc.Element.Name + " with configuration " + ConfigSetting + System.Environment.NewLine); if (!Core.Executing.RunCommand(Doc, "custom build", configSetting.CustomBuild)) { return(false); } BuildInfo.TargetFile = Doc.Element.TargetFilename; BuildInfo.TargetType = Doc.Element.TargetType; } else { ProjectConfig config = null; if (Doc.Project != null) { config = Doc.Project.Settings.Configuration(ConfigSetting); } int startAddress = -1; if ((Doc.Type == ProjectElement.ElementType.BASIC_SOURCE) && (Doc.BaseDoc != null)) { // BASIC files bring a start address startAddress = ((SourceBasicEx)Doc.BaseDoc).StartAddress; ((Parser.BasicFileParser)parser).SetBasicVersion(((SourceBasicEx)Doc.BaseDoc).BASICVersion); } if ((!Core.MainForm.ParseFile(parser, Doc, config, additionalPredefines, OutputMessages, CreatePreProcessedFile)) || (!parser.Assemble(new C64Studio.Parser.CompileConfig() { TargetType = Core.DetermineTargetType(Doc, parser), OutputFile = Core.DetermineTargetFilename(Doc, parser), AutoTruncateLiteralValues = Core.Settings.ASMAutoTruncateLiteralValues, StartAddress = startAddress })) || (parser.Errors > 0)) { Core.MainForm.AddOutputMessages(parser); Core.AddToOutput("Build failed, " + parser.Warnings.ToString() + " warnings, " + parser.Errors.ToString() + " errors encountered" + System.Environment.NewLine); // always show messages if we fail! //if ( OutputMessages ) { Core.Navigating.UpdateFromMessages(parser.Messages, (parser is Parser.ASMFileParser) ? ((Parser.ASMFileParser)parser).ASMFileInfo : null, Doc.Project); Core.MainForm.m_CompileResult.UpdateFromMessages(parser, Doc.Project); } Core.ShowDocument(Core.MainForm.m_CompileResult); Core.MainForm.AppState = Types.StudioState.NORMAL; if (Core.Settings.PlaySoundOnBuildFailure) { System.Media.SystemSounds.Exclamation.Play(); } return(false); } Core.MainForm.AddOutputMessages(parser); var compileTarget = Core.DetermineTargetType(Doc, parser); string compileTargetFile = Core.DetermineTargetFilename(Doc, parser); if (Doc.Element != null) { Doc.Element.CompileTargetFile = compileTargetFile; } if (compileTargetFile == null) { if (parser is Parser.ASMFileParser) { parser.AddError(-1, Types.ErrorCode.E0001_NO_OUTPUT_FILENAME, "No output filename was given, missing element setting or !to <Filename>,<FileType> macro?"); } else { parser.AddError(-1, Types.ErrorCode.E0001_NO_OUTPUT_FILENAME, "No output filename was given, missing element setting"); } if (OutputMessages) { Core.Navigating.UpdateFromMessages(parser.Messages, (parser is Parser.ASMFileParser) ? ((Parser.ASMFileParser)parser).ASMFileInfo : null, Doc.Project); Core.MainForm.m_CompileResult.UpdateFromMessages(parser, Doc.Project); } Core.ShowDocument(Core.MainForm.m_CompileResult); Core.MainForm.AppState = Types.StudioState.NORMAL; if (Core.Settings.PlaySoundOnBuildFailure) { System.Media.SystemSounds.Exclamation.Play(); } return(false); } BuildInfo.TargetFile = compileTargetFile; BuildInfo.TargetType = compileTarget; if (parser.Warnings > 0) { if (OutputMessages) { Core.Navigating.UpdateFromMessages(parser.Messages, (parser is Parser.ASMFileParser) ? ((Parser.ASMFileParser)parser).ASMFileInfo : null, Doc.Project); Core.MainForm.m_CompileResult.UpdateFromMessages(parser, Doc.Project); } Core.ShowDocument(Core.MainForm.m_CompileResult); } } if (string.IsNullOrEmpty(BuildInfo.TargetFile)) { Core.AddToOutput("No target file name specified" + System.Environment.NewLine); Core.MainForm.AppState = Types.StudioState.NORMAL; if (Core.Settings.PlaySoundOnBuildFailure) { System.Media.SystemSounds.Exclamation.Play(); } return(false); } // write output if applicable if ((parser.AssembledOutput != null) && (parser.AssembledOutput.Assembly != null)) { try { System.IO.File.WriteAllBytes(BuildInfo.TargetFile, parser.AssembledOutput.Assembly.Data()); } catch (System.Exception ex) { Core.AddToOutput("Build failed, Could not create output file " + parser.CompileTargetFile + System.Environment.NewLine); Core.AddToOutput(ex.ToString() + System.Environment.NewLine); Core.MainForm.AppState = Types.StudioState.NORMAL; if (Core.Settings.PlaySoundOnBuildFailure) { System.Media.SystemSounds.Exclamation.Play(); } return(false); } Core.AddToOutput("Build successful, " + parser.Warnings.ToString() + " warnings, 0 errors encountered" + System.Environment.NewLine); Core.AddToOutput("Start address $" + parser.AssembledOutput.OriginalAssemblyStartAddress.ToString("X4") + " to $" + (parser.AssembledOutput.OriginalAssemblyStartAddress + parser.AssembledOutput.OriginalAssemblySize - 1).ToString("X4") + ", size " + parser.AssembledOutput.OriginalAssemblySize + " bytes" + System.Environment.NewLine); Core.AddToOutput("Compiled to file " + BuildInfo.TargetFile + ", " + parser.AssembledOutput.Assembly.Length + " bytes" + System.Environment.NewLine); //Debug.Log( "File " + Doc.DocumentFilename + " was rebuilt for config " + ConfigSetting + " this round" ); } if ((configSetting != null) && (configSetting.PostBuildChain.Active)) { if (!BuildChain(configSetting.PostBuildChain, "post build chain", OutputMessages)) { return(false); } } if ((configSetting != null) && (!string.IsNullOrEmpty(configSetting.PostBuild))) { Core.ShowDocument(Core.MainForm.m_Output); Core.AddToOutput("Running post build step on " + Doc.Element.Name + System.Environment.NewLine); if (!Core.Executing.RunCommand(Doc, "post build", configSetting.PostBuild)) { return(false); } } Doc.HasBeenSuccessfullyBuilt = true; if (parser is Parser.ASMFileParser) { FileInfo = ((Parser.ASMFileParser)parser).ASMFileInfo; // update symbols in main asm file Doc.SetASMFileInfo(FileInfo, parser.KnownTokens(), parser.KnownTokenInfo()); //Debug.Log( "Doc " + Doc.Text + " gets " + ( (SourceASM)Doc ).ASMFileInfo.Labels.Count + " labels" ); } if (FileInfo != null) { if (!string.IsNullOrEmpty(FileInfo.LabelDumpFile)) { Core.MainForm.DumpLabelFile(FileInfo); } } Core.Compiling.m_RebuiltFiles.Add(Doc.DocumentFilename); return(true); } catch (Exception ex) { Core.AddToOutput("An error occurred during building an element\r\n" + ex.ToString()); return(false); } }
private void FormatDocumentCreatedFromTemplate(IVsHierarchy hierarchy, uint itemid, string filePath, CancellationToken cancellationToken) { // A file has been created on disk which the user added from the "Add Item" dialog. We need // to include this in a workspace to figure out the right options it should be formatted with. // This requires us to place it in the correct project. var workspace = _componentModel.GetService <VisualStudioWorkspace>(); var solution = workspace.CurrentSolution; ProjectId projectIdToAddTo = null; foreach (var projectId in solution.ProjectIds) { if (workspace.GetHierarchy(projectId) == hierarchy) { projectIdToAddTo = projectId; break; } } if (projectIdToAddTo == null) { // We don't have a project for this, so we'll just make up a fake project altogether var temporaryProject = solution.AddProject( name: nameof(FormatDocumentCreatedFromTemplate), assemblyName: nameof(FormatDocumentCreatedFromTemplate), language: LanguageName); solution = temporaryProject.Solution; projectIdToAddTo = temporaryProject.Id; } var documentId = DocumentId.CreateNewId(projectIdToAddTo); var forkedSolution = solution.AddDocument(DocumentInfo.Create(documentId, filePath, loader: new FileTextLoader(filePath, defaultEncoding: null), filePath: filePath)); var addedDocument = forkedSolution.GetDocument(documentId); var rootToFormat = addedDocument.GetSyntaxRootSynchronously(cancellationToken); var documentOptions = ThreadHelper.JoinableTaskFactory.Run(() => addedDocument.GetOptionsAsync(cancellationToken)); var formattedTextChanges = Formatter.GetFormattedTextChanges(rootToFormat, workspace, documentOptions, cancellationToken); var formattedText = addedDocument.GetTextSynchronously(cancellationToken).WithChanges(formattedTextChanges); // Ensure the line endings are normalized. The formatter doesn't touch everything if it doesn't need to. var targetLineEnding = documentOptions.GetOption(FormattingOptions.NewLine); var originalText = formattedText; foreach (var originalLine in originalText.Lines) { var originalNewLine = originalText.ToString(CodeAnalysis.Text.TextSpan.FromBounds(originalLine.End, originalLine.EndIncludingLineBreak)); // Check if we have a line ending, so we don't go adding one to the end if we don't need to. if (originalNewLine.Length > 0 && originalNewLine != targetLineEnding) { var currentLine = formattedText.Lines[originalLine.LineNumber]; var currentSpan = CodeAnalysis.Text.TextSpan.FromBounds(currentLine.End, currentLine.EndIncludingLineBreak); formattedText = formattedText.WithChanges(new TextChange(currentSpan, targetLineEnding)); } } IOUtilities.PerformIO(() => { using (var textWriter = new StreamWriter(filePath, append: false, encoding: formattedText.Encoding)) { // We pass null here for cancellation, since cancelling in the middle of the file write would leave the file corrupted formattedText.Write(textWriter, cancellationToken: CancellationToken.None); } }); }
public bool? PromptForSaveWhenDocumentChanged(DocumentInfo document) { var result = MessageBox.Show("Das Dokument hat sich geändert. Soll es gespeichert werden?", "", MessageBoxButton.YesNoCancel, MessageBoxImage.Question); if (result == MessageBoxResult.Yes) { return true; } if (result == MessageBoxResult.No) { return false; } return null; }
public static Document AddDocument(this AdhocWorkspace workspace, Project project, string content, string fileName = "code.cs") => workspace.AddDocument(DocumentInfo.Create( DocumentId.CreateNewId(project.Id), "code.cs", loader: TextLoader.From(TextAndVersion.Create(SourceText.From(content), VersionStamp.Create()))));
static List <CodeAction> GetActions(CodeFixProvider action, string input, out DiagnosticTestBase.TestWorkspace workspace, out Document doc, CSharpParseOptions parseOptions = null) { TextSpan selectedSpan; string text = ParseText(input, out selectedSpan); workspace = new DiagnosticTestBase.TestWorkspace(); var projectId = ProjectId.CreateNewId(); var documentId = DocumentId.CreateNewId(projectId); if (parseOptions == null) { parseOptions = new CSharpParseOptions( LanguageVersion.CSharp6, DocumentationMode.Diagnose | DocumentationMode.Parse, SourceCodeKind.Regular, ImmutableArray.Create("DEBUG", "TEST") ); } workspace.Options.WithChangedOption(CSharpFormattingOptions.NewLinesForBracesInControlBlocks, false); workspace.Open(ProjectInfo.Create( projectId, VersionStamp.Create(), "TestProject", "TestProject", LanguageNames.CSharp, null, null, new CSharpCompilationOptions( OutputKind.DynamicallyLinkedLibrary, "", "", "Script", null, OptimizationLevel.Debug, false, true ), parseOptions, new[] { DocumentInfo.Create( documentId, "a.cs", null, SourceCodeKind.Regular, TextLoader.From(TextAndVersion.Create(SourceText.From(text), VersionStamp.Create())) ) }, null, CSharpDiagnosticTestBase.DefaultMetadataReferences ) ); doc = workspace.CurrentSolution.GetProject(projectId).GetDocument(documentId); var actions = new List <Tuple <CodeAction, ImmutableArray <Diagnostic> > >(); var model = doc.GetSemanticModelAsync().Result; var diagnostics = model.GetDiagnostics(); if (diagnostics.Length == 0) { return(new List <CodeAction>()); } foreach (var d in diagnostics) { if (action.FixableDiagnosticIds.Contains(d.Id)) { if (selectedSpan.Start > 0) { Assert.AreEqual(selectedSpan, d.Location.SourceSpan, "Activation span does not match."); } var context = new CodeFixContext(doc, d.Location.SourceSpan, diagnostics.Where(d2 => d2.Location.SourceSpan == d.Location.SourceSpan).ToImmutableArray(), (arg1, arg2) => actions.Add(Tuple.Create(arg1, arg2)), default(CancellationToken)); action.RegisterCodeFixesAsync(context); } } return(actions.Select(a => a.Item1).ToList()); }
private void CreateSimpleWorkspace(out OmnisharpWorkspace workspace, out ChangeBufferService controller, out DocumentInfo document, string filename, string contents) { workspace = new OmnisharpWorkspace( new HostServicesAggregator( Enumerable.Empty <IHostServicesProvider>())); controller = new ChangeBufferService(workspace); var projectInfo = ProjectInfo.Create(ProjectId.CreateNewId(), VersionStamp.Create(), "ProjectNameVal", "AssemblyNameVal", LanguageNames.CSharp); document = DocumentInfo.Create(DocumentId.CreateNewId(projectInfo.Id), filename, null, SourceCodeKind.Regular, TextLoader.From(TextAndVersion.Create(SourceText.From(contents), VersionStamp.Create())), filename); workspace.AddProject(projectInfo); workspace.AddDocument(document); }
protected void Page_Load(object sender, EventArgs e) { currentUser = CMSContext.CurrentUser; if (currentUser == null) { return; } // No cms.blog doc. type if (DataClassInfoProvider.GetDataClass("cms.blog") == null) { RedirectToInformation(GetString("blog.noblogdoctype")); } // Check if user is authorized to manage isAuthorized = currentUser.IsAuthorizedPerResource("CMS.Blog", "Manage") || (currentUser.IsAuthorizedPerClassName("cms.blog", "Manage", CMSContext.CurrentSiteName) && currentUser.IsAuthorizedPerClassName("cms.blogpost", "Manage", CMSContext.CurrentSiteName)); // Register grid events gridBlogs.OnExternalDataBound += gridBlogs_OnExternalDataBound; gridBlogs.OnDataReload += gridBlogs_OnDataReload; gridBlogs.ShowActionsMenu = true; gridBlogs.Columns = "BlogID, ClassName, BlogName, NodeID, DocumentCulture, NodeOwner, BlogModerators"; // Get all possible columns to retrieve IDataClass nodeClass = DataClassFactory.NewDataClass("CMS.Tree"); DocumentInfo di = new DocumentInfo(); BlogInfo bi = new BlogInfo(); gridBlogs.AllColumns = SqlHelperClass.MergeColumns(SqlHelperClass.MergeColumns(SqlHelperClass.MergeColumns(bi.ColumnNames), SqlHelperClass.MergeColumns(di.ColumnNames)), SqlHelperClass.MergeColumns(nodeClass.ColumnNames)); // Get ClassID of the 'cms.blogpost' class DataClassInfo dci = DataClassInfoProvider.GetDataClass("cms.blogpost"); string classId = ""; string script = ""; if (dci != null) { classId = dci.ClassID.ToString(); } // Get script to redirect to new blog post page script += "function NewPost(parentId, culture) { \n"; script += " if (parentId != 0) { \n"; script += " parent.parent.parent.location.href = \"" + ResolveUrl("~/CMSDesk/default.aspx") + "?section=content&action=new&nodeid=\" + parentId + \"&classid=" + classId + "&culture=\" + culture;"; script += "}} \n"; // Generate javascript code ltlScript.Text = ScriptHelper.GetScript(script); }
private void SetDocFlags() { DocInfo = DocumentInfo.IsParentTested | (_Document == null ? 0 : DocumentInfo.IsConnected | (_Document.NodeType == NodeType.DOCUMENT_NODE ? DocumentInfo.IsDocument : 0) | (_Document.IsIndexed ? DocumentInfo.IsIndexed : 0)); }
protected void Page_Load(object sender, EventArgs e) { UIContext.PropertyTab = PropertyTabEnum.LinkedDocs; nodeId = QueryHelper.GetInteger("nodeid", 0); currentSiteName = CMSContext.CurrentSiteName.ToLower(); tree = new TreeProvider(currentUser); node = tree.SelectSingleNode(nodeId, TreeProvider.ALL_CULTURES, tree.CombineWithDefaultCulture, false); // Set edited document EditedDocument = node; gridDocs.OnExternalDataBound += gridDocuments_OnExternalDataBound; gridDocs.OnAction += gridDocs_OnAction; gridDocs.OnDataReload += gridDocs_OnDataReload; gridDocs.ShowActionsMenu = true; gridDocs.Columns = "NodeAliasPath, SiteName, NodeParentID, DocumentName, DocumentNamePath, ClassDisplayName"; // Get all possible columns to retrieve IDataClass nodeClass = DataClassFactory.NewDataClass("CMS.Tree"); DocumentInfo di = new DocumentInfo(); gridDocs.AllColumns = SqlHelperClass.MergeColumns(SqlHelperClass.MergeColumns(di.ColumnNames.ToArray()), SqlHelperClass.MergeColumns(nodeClass.ColumnNames.ToArray())); }
protected void Page_Load(object sender, EventArgs e) { UIContext.PropertyTab = PropertyTabEnum.LinkedDocs; if (Node != null) { // Check modify permissions if (!CheckDocumentPermissions(Node, PermissionsEnum.Modify)) { pnlContainer.Enabled = false; } } currentSiteName = CMSContext.CurrentSiteName.ToLowerCSafe(); gridDocs.OnExternalDataBound += gridDocuments_OnExternalDataBound; gridDocs.OnAction += gridDocs_OnAction; gridDocs.OnDataReload += gridDocs_OnDataReload; gridDocs.ShowActionsMenu = true; gridDocs.Columns = "NodeAliasPath, SiteName, NodeParentID, DocumentName, DocumentNamePath, ClassDisplayName"; // Get all possible columns to retrieve IDataClass nodeClass = DataClassFactory.NewDataClass("CMS.Tree"); DocumentInfo di = new DocumentInfo(); gridDocs.AllColumns = SqlHelperClass.MergeColumns(SqlHelperClass.MergeColumns(di.ColumnNames), SqlHelperClass.MergeColumns(nodeClass.ColumnNames)); pnlContainer.Enabled = !DocumentManager.ProcessingAction; }
/// <summary> /// Page load. /// </summary> protected void Page_Load(object sender, EventArgs e) { ScriptHelper.RegisterScriptFile(this, @"~/CMSModules/Content/CMSDesk/View/Listing.js"); currentSiteName = CMSContext.CurrentSiteName; currentUserInfo = CMSContext.CurrentUser; // Current Node ID nodeId = QueryHelper.GetInteger("nodeid", 0); // Setup page title text and image CurrentMaster.Title.TitleText = GetString("Content.ListingTitle"); CurrentMaster.Title.TitleImage = GetImageUrl("CMSModules/CMS_Content/Menu/Listing.png"); CurrentMaster.Title.HelpName = "helpTopic"; CurrentMaster.Title.HelpTopicName = "list_tab"; string[,] actions = new string[1, 6]; actions[0, 0] = HeaderActions.TYPE_HYPERLINK; actions[0, 1] = GetString("Listing.ParentDirectory"); actions[0, 5] = GetImageUrl("CMSModules/CMS_Content/Listing/parent.png"); CurrentMaster.HeaderActions.Actions = actions; if (nodeId > 0) { tree = new TreeProvider(currentUserInfo); checkPermissions = tree.CheckDocumentUIPermissions(currentSiteName); node = tree.SelectSingleNode(nodeId, TreeProvider.ALL_CULTURES); // Set edited document EditedDocument = node; if (node != null) { if (currentUserInfo.IsAuthorizedPerDocument(node, NodePermissionsEnum.ExploreTree) != AuthorizationResultEnum.Allowed) { RedirectToCMSDeskAccessDenied("CMS.Content", "exploretree"); } aliasPath = node.NodeAliasPath; // Setup the link to the parent document if ((node.NodeClassName.ToLower() != "cms.root") && (currentUserInfo.UserStartingAliasPath.ToLower() != node.NodeAliasPath.ToLower())) { CurrentMaster.HeaderActions.Actions[0, 3] = "javascript:SelectItem(" + node.NodeParentID + ");"; } else { CurrentMaster.HeaderActions.Visible = false; CurrentMaster.PanelBody.FindControl("pnlActions").Visible = false; } } ScriptHelper.RegisterProgress(this); ScriptHelper.RegisterDialogScript(this); ScriptHelper.RegisterJQuery(this); InitDropdowLists(); cultureElem.DropDownCultures.Width = 222; // Prepare JavaScript for actions StringBuilder actionScript = new StringBuilder(); actionScript.Append( @"function PerformAction(selectionFunction, selectionField, dropId){ var label = document.getElementById('" + lblInfo.ClientID + @"'); var whatDrp = document.getElementById('" + drpWhat.ClientID + @"'); var action = document.getElementById(dropId).value; var selectionFieldElem = document.getElementById(selectionField); var allSelected = " + (int)What.SelectedDocuments + @"; if (action == '" + (int)Action.SelectAction + @"'){ label.innerHTML = '" + GetString("massaction.selectsomeaction") + @"'; return false; } if(whatDrp.value == '" + (int)What.AllDocuments + @"'){ allSelected = " + (int)What.AllDocuments + @"; } var items = selectionFieldElem.value; if(!eval(selectionFunction) || whatDrp.value == '" + (int)What.AllDocuments + @"'){ var argument = '|' + allSelected + '|' + items; switch(action){ case '" + (int)Action.Move + @"': argument = '" + Action.Move + "' + argument;" + ClientScript.GetCallbackEventReference(this, "argument", "OpenModal", string.Empty) + @"; break; case '" + (int)Action.Copy + @"': argument = '" + Action.Copy + "' + argument;" + ClientScript.GetCallbackEventReference(this, "argument", "OpenModal", string.Empty) + @"; break; case '" + (int)Action.Link + @"': argument = '" + Action.Link + "' + argument;" + ClientScript.GetCallbackEventReference(this, "argument", "OpenModal", string.Empty) + @"; break; case '" + (int)Action.Delete + @"': argument = '" + Action.Delete + "' + argument;" + ClientScript.GetCallbackEventReference(this, "argument", "Redirect", string.Empty) + @"; break; case '" + (int)Action.Publish + @"': argument = '" + Action.Publish + "' + argument;" + ClientScript.GetCallbackEventReference(this, "argument", "Redirect", string.Empty) + @"; break; case '" + (int)Action.Archive + @"': argument = '" + Action.Archive + "' + argument;" + ClientScript.GetCallbackEventReference(this, "argument", "Redirect", string.Empty) + @"; break; default: return false; } } else{ label.innerHTML = '" + GetString("documents.selectdocuments") + @"'; } return false; } function OpenModal(arg, context){ modalDialog(arg,'actionDialog','90%', '85%'); } function Redirect(arg, context){ document.location.replace(arg); }"); ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "actionScript", ScriptHelper.GetScript(actionScript.ToString())); // Add action to button btnOk.OnClientClick = "return PerformAction('" + gridDocuments.GetCheckSelectionScript() + "','" + gridDocuments.GetSelectionFieldClientID() + "','" + drpAction.ClientID + "');"; // Initialize dropdown lists if (!RequestHelper.IsPostBack()) { drpAction.Items.Add(new ListItem(GetString("general." + Action.SelectAction), Convert.ToInt32(Action.SelectAction).ToString())); drpAction.Items.Add(new ListItem(GetString("general." + Action.Move), Convert.ToInt32(Action.Move).ToString())); drpAction.Items.Add(new ListItem(GetString("general." + Action.Copy), Convert.ToInt32(Action.Copy).ToString())); drpAction.Items.Add(new ListItem(GetString("general." + Action.Link), Convert.ToInt32(Action.Link).ToString())); drpAction.Items.Add(new ListItem(GetString("general." + Action.Delete), Convert.ToInt32(Action.Delete).ToString())); if (currentUserInfo.IsGlobalAdministrator || currentUserInfo.IsAuthorizedPerResource("CMS.Content", "ManageWorkflow")) { drpAction.Items.Add(new ListItem(GetString("general." + Action.Publish), Convert.ToInt32(Action.Publish).ToString())); drpAction.Items.Add(new ListItem(GetString("general." + Action.Archive), Convert.ToInt32(Action.Archive).ToString())); } drpWhat.Items.Add(new ListItem(GetString("contentlisting." + What.SelectedDocuments), Convert.ToInt32(What.SelectedDocuments).ToString())); drpWhat.Items.Add(new ListItem(GetString("contentlisting." + What.AllDocuments), Convert.ToInt32(What.AllDocuments).ToString())); } // Setup the grid gridDocuments.OnExternalDataBound += gridDocuments_OnExternalDataBound; gridDocuments.OnBeforeDataReload += gridDocuments_OnBeforeDataReload; gridDocuments.OnDataReload += gridDocuments_OnDataReload; gridDocuments.ZeroRowsText = GetString("content.nochilddocumentsfound"); gridDocuments.ShowActionsMenu = true; if (node != null) { gridDocuments.WhereCondition = "NodeParentID = " + node.NodeID + " AND NodeLevel = " + (node.NodeLevel + 1); } // Initialize columns string columns = @"DocumentLastVersionName, DocumentName, NodeParentID, ClassDisplayName, DocumentModifiedWhen, Published, DocumentLastVersionNumber, DocumentMenuRedirectURL, DocumentLastVersionMenuRedirectUrl, DocumentIsArchived, DocumentCheckedOutByUserID, DocumentPublishedVersionHistoryID, DocumentWorkflowStepID, DocumentCheckedOutVersionHistoryID, DocumentNamePath, DocumentPublishFrom, DocumentType, DocumentLastVersionType, NodeAliasPath"; if (checkPermissions) { columns = SqlHelperClass.MergeColumns(columns, TreeProvider.SECURITYCHECK_REQUIRED_COLUMNS); } gridDocuments.Columns = columns; StringBuilder refreshScripts = new StringBuilder(); refreshScripts.Append( @"function RefreshTree() { if((parent != null) && (parent.parent != null) && (parent.parent.frames['contenttree'] != null) && (parent.parent.frames['contenttree'].RefreshNode != null)) { parent.parent.frames['contenttree'].RefreshNode(", nodeId, @",", nodeId, @"); } } function ClearSelection() { ", gridDocuments.GetClearSelectionScript(), @" } function RefreshGrid() { ClearSelection(); RefreshTree();", ClientScript.GetPostBackEventReference(btnShow, "null"), @" }"); // Register refresh scripts string refreshScript = ScriptHelper.GetScript(refreshScripts.ToString()); ScriptHelper.RegisterClientScriptBlock(Page, typeof(string), "refreshListing", refreshScript); // Get all possible columns to retrieve IDataClass nodeClass = DataClassFactory.NewDataClass("CMS.Tree"); DocumentInfo di = new DocumentInfo(); gridDocuments.AllColumns = SqlHelperClass.MergeColumns(SqlHelperClass.MergeColumns(di.ColumnNames.ToArray()), SqlHelperClass.MergeColumns(nodeClass.ColumnNames.ToArray())); } }
private void SaveAs(DocumentInfo info) { SaveFileDialog dialog = new SaveFileDialog(); dialog.Filter = "C# Files (*.cs)|*.cs|Text Files (*.txt)|*.txt|All Files (*.*)|*.*"; dialog.AddExtension = true; dialog.DefaultExt = ".cs"; dialog.FileName = info.Title; bool? result = dialog.ShowDialog(); // If the file name is not an empty string open it for saving. if (result == true && !string.IsNullOrWhiteSpace(dialog.FileName)) { TextEditor editor = info.Editor; editor.Save(dialog.FileName); if (info.FullPath != null) { _openFiles.Remove(info.FullPath); } _openFiles[dialog.FileName] = info.ID; info.FullPath = dialog.FileName; info.Title = dialog.SafeFileName; info.Tab.Title = dialog.SafeFileName; } }
static void WriteClassDeclaration (DocumentInfo info, StringBuilder builder) { builder.Append ("partial class "); builder.Append (info.ClassName); builder.Append (" : "); builder.AppendLine (info.BaseType); }
private void addToList(Control controlObject, DocumentInfo[] dis, bool mark) { if (dis != null && dis.Length > 0) { foreach (DocumentInfo di in dis) { LiteralControl c = new LiteralControl(); c.Text = makeDocumentInfopanel(di, mark); controlObject.Controls.Add(c); } } else { LiteralControl c = new LiteralControl(); c.Text = "<tr><td>" + i18n.GetMessage("m241") + "</td></tr>"; controlObject.Controls.Add(c); } }
public Ascii(DocumentInfo info) : base(info, "ascii", "Ascii", "txt", "asc", "nfo") { }
protected static void AnalyzeWithRule <T>(Func <string, SyntaxTree> parseTextFunc, Func <SyntaxTree[], Compilation> createCompilationFunc, string language, string input, string ruleId, string output = null, int issueToFix = -1, int actionToRun = 0, Action <int, Diagnostic> diagnosticCheck = null) where T : DiagnosticAnalyzer, new() { var text = new StringBuilder(); var expectedDiagnosics = new List <TextSpan>(); int start = -1; for (int i = 0; i < input.Length; i++) { char ch = input[i]; if (ch == '$') { if (start < 0) { start = text.Length; continue; } expectedDiagnosics.Add(TextSpan.FromBounds(start, text.Length)); start = -1; } else { text.Append(ch); } } var syntaxTree = parseTextFunc(text.ToString()); Compilation compilation = createCompilationFunc(new[] { syntaxTree }); var diagnostics = new List <Diagnostic>(); var compilationWithAnalyzers = compilation.WithAnalyzers(System.Collections.Immutable.ImmutableArray <DiagnosticAnalyzer> .Empty.Add(new T())); diagnostics.AddRange(compilationWithAnalyzers.GetAnalyzerDiagnosticsAsync().Result); if (expectedDiagnosics.Count != diagnostics.Count) { Console.WriteLine("Diagnostics: " + diagnostics.Count); foreach (var diag in diagnostics) { Console.WriteLine(diag.Id + "/" + diag.GetMessage()); } Assert.Fail("Diagnostic count mismatch expected: " + expectedDiagnosics.Count + " but was:" + diagnostics.Count); } for (int i = 0; i < expectedDiagnosics.Count; i++) { var d = diagnostics[i]; var wholeSpan = GetWholeSpan(d); if (wholeSpan != expectedDiagnosics[i]) { Assert.Fail("Diagnostic " + i + " span mismatch expected: " + expectedDiagnosics[i] + " but was " + wholeSpan); } if (diagnosticCheck != null) { diagnosticCheck(i, d); } } if (output == null) { return; } var workspace = new TestWorkspace(); var projectId = ProjectId.CreateNewId(); var documentId = DocumentId.CreateNewId(projectId); workspace.Open(ProjectInfo.Create( projectId, VersionStamp.Create(), "", "", language, null, null, null, null, new[] { DocumentInfo.Create( documentId, "a.cs", null, SourceCodeKind.Regular, TextLoader.From(TextAndVersion.Create(SourceText.From(text.ToString()), VersionStamp.Create()))) } )); if (issueToFix < 0) { diagnostics.Reverse(); foreach (var v in diagnostics) { RunFix(workspace, projectId, documentId, v); } } else { RunFix(workspace, projectId, documentId, diagnostics.ElementAt(issueToFix), actionToRun); } var txt = workspace.CurrentSolution.GetProject(projectId).GetDocument(documentId).GetTextAsync().Result.ToString(); txt = CodeFixTestBase.HomogenizeEol(txt); output = CodeFixTestBase.HomogenizeEol(output); if (output != txt) { Console.WriteLine("expected:"); Console.WriteLine(output); Console.WriteLine("got:"); Console.WriteLine(txt); Assert.Fail(); } }
/// <summary> /// Handles the Load event of the Page control. /// </summary> protected void Page_Load(object sender, EventArgs e) { gridDocuments.StopProcessing = StopProcessing; if (StopProcessing) { return; } if (NodeID > 0) { checkPermissions = Tree.CheckDocumentUIPermissions(currentSiteName); if (Node != null) { if (currentUserInfo.IsAuthorizedPerDocument(Node, NodePermissionsEnum.ExploreTree) != AuthorizationResultEnum.Allowed) { CMSPage.RedirectToCMSDeskAccessDenied("CMS.Content", "exploretree"); } aliasPath = Node.NodeAliasPath; } ScriptHelper.RegisterProgress(Page); ScriptHelper.RegisterDialogScript(Page); ScriptHelper.RegisterJQuery(Page); InitDropdownLists(); // Prepare JavaScript for actions StringBuilder actionScript = new StringBuilder(); actionScript.Append( @"function PerformAction(selectionFunction, selectionField, dropId){ var label = document.getElementById('", lblInfo.ClientID, @"'); var whatDrp = document.getElementById('", drpWhat.ClientID, @"'); var action = document.getElementById(dropId).value; var selectionFieldElem = document.getElementById(selectionField); var allSelected = ", (int)What.SelectedDocuments, @"; if (action == '", (int)Action.SelectAction, @"'){ label.innerHTML = '", GetString("massaction.selectsomeaction"), @"'; return false; } if(whatDrp.value == '", (int)What.AllDocuments, @"'){ allSelected = ", (int)What.AllDocuments, @"; } var items = selectionFieldElem.value; if(!eval(selectionFunction) || whatDrp.value == '", (int)What.AllDocuments, @"'){ var argument = '|' + allSelected + '|' + items; switch(action){ case '", (int)Action.Move, @"': argument = '", Action.Move, "' + argument;", ClientScript.GetCallbackEventReference(this, "argument", "OpenModal", string.Empty), @"; break; case '", (int)Action.Copy, @"': argument = '", Action.Copy, "' + argument;", ClientScript.GetCallbackEventReference(this, "argument", "OpenModal", string.Empty), @"; break; case '", (int)Action.Link, @"': argument = '", Action.Link, "' + argument;", ClientScript.GetCallbackEventReference(this, "argument", "OpenModal", string.Empty), @"; break; case '", (int)Action.Delete, @"': argument = '", Action.Delete, "' + argument;", ClientScript.GetCallbackEventReference(this, "argument", "Redirect", string.Empty), @"; break; case '", (int)Action.Publish, @"': argument = '", Action.Publish, "' + argument;", ClientScript.GetCallbackEventReference(this, "argument", "Redirect", string.Empty), @"; break; case '", (int)Action.Archive, @"': argument = '", Action.Archive, "' + argument;", ClientScript.GetCallbackEventReference(this, "argument", "Redirect", string.Empty), @"; break; case '", (int)Action.Translate, @"': argument = '", Action.Translate, "' + argument;", ClientScript.GetCallbackEventReference(this, "argument", "Redirect", string.Empty), @"; break; default: return false; } } else{ label.innerHTML = '", GetString("documents.selectdocuments"), @"'; } return false; } function OpenModal(arg, context){ modalDialog(arg,'actionDialog','90%', '85%'); } function Redirect(arg, context){ document.location.replace(arg); } function MoveNode(action, nodeId){ document.getElementById('", hdnMoveId.ClientID, @"').value = action + ';' + nodeId ; ", Page.ClientScript.GetPostBackEventReference(this, "move"), @" } "); ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "actionScript", ScriptHelper.GetScript(actionScript.ToString())); // Add action to button btnOk.OnClientClick = "return PerformAction('" + gridDocuments.GetCheckSelectionScript() + "','" + gridDocuments.GetSelectionFieldClientID() + "','" + drpAction.ClientID + "');"; // Setup the grid gridDocuments.OrderBy = OrderBy; gridDocuments.OnExternalDataBound += gridDocuments_OnExternalDataBound; gridDocuments.OnDataReload += gridDocuments_OnDataReload; gridDocuments.GridView.RowDataBound += new GridViewRowEventHandler(GridView_RowDataBound); gridDocuments.GridView.RowCreated += new GridViewRowEventHandler(GridView_RowCreated); gridDocuments.ShowActionsMenu = true; // Setup where condition string where = string.Empty; if (Node != null) { if (ShowAllLevels) { string path = aliasPath ?? string.Empty; path = path.TrimEnd('/'); where = string.Format("NodeAliasPath LIKE N'{0}/%'", SqlHelperClass.GetSafeQueryString(path)); } else { where = string.Format("NodeParentID = {0} AND NodeLevel = {1}", Node.NodeID, Node.NodeLevel + 1); // Extend the where condition to include the root document if (RequiresDialog && (Node != null) && (Node.NodeParentID == 0)) { where = SqlHelperClass.AddWhereCondition(where, "NodeParentID = 0", "OR"); OrderBy = "NodeParentID ASC" + ((OrderBy.Length > 0) ? "," : "") + OrderBy; } } } where = SqlHelperClass.AddWhereCondition(where, WhereCodition); if (!string.IsNullOrEmpty(where)) { gridDocuments.WhereCondition = where; } // Initialize columns string columns = @"DocumentLastVersionName, DocumentName, NodeParentID, ClassDisplayName, DocumentModifiedWhen, Published, DocumentLastVersionNumber, DocumentMenuRedirectURL, DocumentLastVersionMenuRedirectUrl, DocumentIsArchived, DocumentCheckedOutByUserID, DocumentPublishedVersionHistoryID, DocumentWorkflowStepID, DocumentCheckedOutVersionHistoryID, DocumentNamePath, DocumentPublishFrom, DocumentType, DocumentLastVersionType, NodeAliasPath"; if (checkPermissions) { columns = SqlHelperClass.MergeColumns(columns, TreeProvider.SECURITYCHECK_REQUIRED_COLUMNS); } gridDocuments.Columns = SqlHelperClass.MergeColumns(columns, AdditionalColumns); // Store the refresh node id. It will be used for refreshing the dialog after dialog actions are performed (move, delete...) refreshNodeId = NodeID; StringBuilder refreshScripts = new StringBuilder(); refreshScripts.Append(@" function RefreshTree() { if((parent != null) && (parent.RefreshTree != null)) { ", ControlsHelper.GetPostBackEventReference(this, "refresh", false, false), @" } } function ClearSelection() { ", gridDocuments.GetClearSelectionScript(), @" } function RefreshGrid() { ClearSelection(); RefreshTree(); ", gridDocuments.GetReloadScript(), @" }"); // Register refresh scripts string refreshScript = ScriptHelper.GetScript(refreshScripts.ToString()); ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "refreshListing", refreshScript); // Get all possible columns to retrieve IDataClass nodeClass = DataClassFactory.NewDataClass("CMS.Tree"); DocumentInfo di = new DocumentInfo(); gridDocuments.AllColumns = SqlHelperClass.MergeColumns(SqlHelperClass.MergeColumns(di.ColumnNames), SqlHelperClass.MergeColumns(nodeClass.ColumnNames)); } }
public DocumentInfo ToDocumentInfo() { return(DocumentInfo.Create(this.Id, this.Name, this.Folders, this.SourceCodeKind, loader: this.Loader, filePath: this.FilePath, isGenerated: this.IsGenerated)); }
protected void Page_Load(object sender, EventArgs e) { // Get ID of node nodeId = QueryHelper.GetInteger("nodeid", 0); gridLanguages.FilteredZeroRowsText = GetString("transman.nodocumentculture"); gridLanguages.OnDataReload += gridDocuments_OnDataReload; gridLanguages.OnExternalDataBound += gridLanguages_OnExternalDataBound; gridLanguages.ShowActionsMenu = true; gridLanguages.Columns = "DocumentModifiedWhen, DocumentLastPublished, DocumentName, VersionNumber, Published"; IDataClass nodeClass = DataClassFactory.NewDataClass("CMS.Tree"); DocumentInfo di = new DocumentInfo(); gridLanguages.AllColumns = SqlHelperClass.MergeColumns(SqlHelperClass.MergeColumns(di.ColumnNames.ToArray()), SqlHelperClass.MergeColumns(nodeClass.ColumnNames.ToArray())); }
protected void SetupControl() { // In design mode is processing of control stopped if (StopProcessing) { // Do nothing } else { if (CMSContext.CurrentUser.UserID == UserID) { gridElem.ZeroRowsText = GetString("blogsubscripitons.userhasnosubscriptions"); } else { gridElem.ZeroRowsText = GetString("blogsubscripitons.NoDataUser"); } gridElem.IsLiveSite = IsLiveSite; gridElem.OnAction += gridElem_OnAction; gridElem.OnExternalDataBound += gridElem_OnExternalDataBound; gridElem.OnDataReload += gridElem_OnDataReload; gridElem.ShowActionsMenu = true; gridElem.Columns = "SubscriptionID, SubscriptionEmail, DocumentName, NodeAliasPath, DocumentCulture, SubscriptionApproved"; // Get all possible columns to retrieve IDataClass nodeClass = DataClassFactory.NewDataClass("CMS.Tree"); DocumentInfo di = new DocumentInfo(); BlogPostSubscriptionInfo bpsi = new BlogPostSubscriptionInfo(); gridElem.AllColumns = SqlHelperClass.MergeColumns(SqlHelperClass.MergeColumns(SqlHelperClass.MergeColumns(bpsi.ColumnNames), SqlHelperClass.MergeColumns(di.ColumnNames)), SqlHelperClass.MergeColumns(nodeClass.ColumnNames)); mSiteName = SiteInfoProvider.GetSiteName(SiteID); } }
private void Save(DocumentInfo info) { if (string.IsNullOrWhiteSpace(info.FullPath)) { SaveAs(info); } else { info.Editor.Save(info.FullPath); } }
private async Task <Solution> CreateSolutionAsync(Checksum solutionChecksum, CancellationToken cancellationToken) { // synchronize whole solution first await _assetService.SynchronizeSolutionAssetsAsync(solutionChecksum, cancellationToken).ConfigureAwait(false); var solutionChecksumObject = await _assetService.GetAssetAsync <SolutionStateChecksums>(solutionChecksum, cancellationToken).ConfigureAwait(false); var workspace = new AdhocWorkspace(RoslynServices.HostServices, workspaceKind: WorkspaceKind_RemoteWorkspace); var solutionInfo = await _assetService.GetAssetAsync <SolutionInfo.SolutionAttributes>(solutionChecksumObject.Info, cancellationToken).ConfigureAwait(false); var projects = new List <ProjectInfo>(); foreach (var projectChecksum in solutionChecksumObject.Projects) { var projectSnapshot = await _assetService.GetAssetAsync <ProjectStateChecksums>(projectChecksum, cancellationToken).ConfigureAwait(false); var projectInfo = await _assetService.GetAssetAsync <ProjectInfo.ProjectAttributes>(projectSnapshot.Info, cancellationToken).ConfigureAwait(false); if (!workspace.Services.IsSupported(projectInfo.Language)) { // only add project our workspace supports. // workspace doesn't allow creating project with unknown languages continue; } var documents = new List <DocumentInfo>(); foreach (var documentChecksum in projectSnapshot.Documents) { var documentSnapshot = await _assetService.GetAssetAsync <DocumentStateChecksums>(documentChecksum, cancellationToken).ConfigureAwait(false); var documentInfo = await _assetService.GetAssetAsync <DocumentInfo.DocumentAttributes>(documentSnapshot.Info, cancellationToken).ConfigureAwait(false); var textLoader = TextLoader.From( TextAndVersion.Create( new ChecksumSourceText( documentSnapshot.Text, await _assetService.GetAssetAsync <SourceText>(documentSnapshot.Text, cancellationToken).ConfigureAwait(false)), VersionStamp.Create(), documentInfo.FilePath)); // TODO: do we need version? documents.Add( DocumentInfo.Create( documentInfo.Id, documentInfo.Name, documentInfo.Folders, documentInfo.SourceCodeKind, textLoader, documentInfo.FilePath, documentInfo.IsGenerated)); } var p2p = new List <ProjectReference>(); foreach (var checksum in projectSnapshot.ProjectReferences) { cancellationToken.ThrowIfCancellationRequested(); var reference = await _assetService.GetAssetAsync <ProjectReference>(checksum, cancellationToken).ConfigureAwait(false); p2p.Add(reference); } var metadata = new List <MetadataReference>(); foreach (var checksum in projectSnapshot.MetadataReferences) { cancellationToken.ThrowIfCancellationRequested(); var reference = await _assetService.GetAssetAsync <MetadataReference>(checksum, cancellationToken).ConfigureAwait(false); metadata.Add(reference); } var analyzers = new List <AnalyzerReference>(); foreach (var checksum in projectSnapshot.AnalyzerReferences) { cancellationToken.ThrowIfCancellationRequested(); var reference = await _assetService.GetAssetAsync <AnalyzerReference>(checksum, cancellationToken).ConfigureAwait(false); analyzers.Add(reference); } var additionals = new List <DocumentInfo>(); foreach (var documentChecksum in projectSnapshot.AdditionalDocuments) { cancellationToken.ThrowIfCancellationRequested(); var documentSnapshot = await _assetService.GetAssetAsync <DocumentStateChecksums>(documentChecksum, cancellationToken).ConfigureAwait(false); var documentInfo = await _assetService.GetAssetAsync <DocumentInfo.DocumentAttributes>(documentSnapshot.Info, cancellationToken).ConfigureAwait(false); var textLoader = TextLoader.From( TextAndVersion.Create( new ChecksumSourceText( documentSnapshot.Text, await _assetService.GetAssetAsync <SourceText>(documentSnapshot.Text, cancellationToken).ConfigureAwait(false)), VersionStamp.Create(), documentInfo.FilePath)); // TODO: do we need version? additionals.Add( DocumentInfo.Create( documentInfo.Id, documentInfo.Name, documentInfo.Folders, documentInfo.SourceCodeKind, textLoader, documentInfo.FilePath, documentInfo.IsGenerated)); } var compilationOptions = await _assetService.GetAssetAsync <CompilationOptions>(projectSnapshot.CompilationOptions, cancellationToken).ConfigureAwait(false); var parseOptions = await _assetService.GetAssetAsync <ParseOptions>(projectSnapshot.ParseOptions, cancellationToken).ConfigureAwait(false); projects.Add( ProjectInfo.Create( projectInfo.Id, projectInfo.Version, projectInfo.Name, projectInfo.AssemblyName, projectInfo.Language, projectInfo.FilePath, projectInfo.OutputFilePath, compilationOptions, parseOptions, documents, p2p, metadata, analyzers, additionals, projectInfo.IsSubmission)); } return(workspace.AddSolution(SolutionInfo.Create(solutionInfo.Id, solutionInfo.Version, solutionInfo.FilePath, projects))); }
private DocumentInfo CreateTab(string fullPath, string title) { TextEditor editor = new TextEditor(); editor.FontFamily = new FontFamily("Consolas"); editor.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#"); editor.ShowLineNumbers = true; if (!string.IsNullOrWhiteSpace(fullPath)) { editor.Load(fullPath); } LayoutDocument document = new LayoutDocument(); document.Title = title; document.Content = editor; document.Closing += document_Closing; _window.DocumentPane.InsertChildAt(_window.DocumentPane.ChildrenCount, document); document.IsSelected = true; DocumentInfo info = new DocumentInfo(fullPath, title, document, editor); _documents[info.ID] = info; document.ContentId = info.ID.ToString(); return info; }
public Task UpdateState(DocumentInfo document, InProcessDocumentState newState, CancellationToken cancellationToken) { return(UpdateStateInternal(document, newState, null, cancellationToken)); }