public ProjectModel GetProject(int userId, int projectId) { //Get files from database matching project ID: List<SimulatorFile> lSources = DB.GetProjectSource(userId, projectId, true); // Fabricate a ProjectModel from the list of files ProjectModel projectModel = new ProjectModel() { OwnerUserId = userId, ProjectId = projectId }; foreach (SimulatorFile cFile in lSources) { var fileModel = new ProjectFileModel() { ProjectId = projectId, Id = cFile.id, Name = cFile.name, Content = cFile.content }; projectModel.Children.Add(fileModel); } return projectModel; }
public static IEnumerable <string> GetProjectReferenceDependencyFilePathsRecursive(ProjectFileModel projectFileModel, string projectFilePath, HashSet <string> pathAccumulator) { var dependencyProjectFilePaths = projectFileModel.GetProjectReferenceDependencyFilePaths(projectFilePath); foreach (var dependencyProjectFilePath in dependencyProjectFilePaths) { if (!pathAccumulator.Contains(dependencyProjectFilePath)) { pathAccumulator.Add(dependencyProjectFilePath); yield return(dependencyProjectFilePath); } var dependencyProjectFile = ProjectFileModel.Load(dependencyProjectFilePath); var dependencyDependencyProjectFilePaths = dependencyProjectFile.GetProjectReferenceDependencyFilePathsRecursive(dependencyProjectFilePath); foreach (var dependencyDependencyProjectFilePath in dependencyDependencyProjectFilePaths) { if (!pathAccumulator.Contains(dependencyDependencyProjectFilePath)) { pathAccumulator.Add(dependencyDependencyProjectFilePath); yield return(dependencyDependencyProjectFilePath); } } } }
public ProjectModel GetProject(int userId, int projectId) { //Get files from database matching project ID: List <SimulatorFile> lSources = DB.GetProjectSource(userId, projectId, true); // Fabricate a ProjectModel from the list of files ProjectModel projectModel = new ProjectModel() { OwnerUserId = userId, ProjectId = projectId }; foreach (SimulatorFile cFile in lSources) { var fileModel = new ProjectFileModel() { ProjectId = projectId, Id = cFile.id, Name = cFile.name, Content = cFile.content }; projectModel.Children.Add(fileModel); } return(projectModel); }
public static IEnumerable <string> GetProjectReferenceDependencyFilePaths(string projectFilePath) { var projectFile = ProjectFileModel.Load(projectFilePath); var projectReferenceDependencyFilePaths = Utilities.GetProjectReferenceDependencyFilePaths(projectFile, projectFilePath); return(projectReferenceDependencyFilePaths); }
/// <summary> /// Adds the dependency project file as a project-reference dependency to the project file. /// </summary> public static void AddProjectReference(string projectFilePath, string dependencyProjectFilePath) { var projectFile = ProjectFileModel.Load(projectFilePath); projectFile.AddProjectReference(projectFilePath, dependencyProjectFilePath); projectFile.Save(projectFilePath); }
private static void CreateNewProjectOnly() { var projectFilePath = @"C:\Temp\temp.csproj"; var projectFile = ProjectFileModel.New(); ProjectFileSerialization.Serialize(projectFilePath, projectFile); }
private static void CreateNewNetStandardLibraryProjectFile() { var projectFilePath = @"C:\Temp\temp.csproj"; var projectFile = ProjectFileModel.NewNetStandardLibrary(); ProjectFileSerialization.Serialize(projectFilePath, projectFile); }
public static IEnumerable <string> GetProjectReferenceDependencyFilePathsRecursive(string projectFilePath, HashSet <string> pathAccumulator) { var projectFile = ProjectFileModel.Load(projectFilePath); var projectReferenceDependencyFilePaths = Utilities.GetProjectReferenceDependencyFilePathsRecursive(projectFile, projectFilePath, pathAccumulator); return(projectReferenceDependencyFilePaths); }
public static IEnumerable <string> GetProjectReferenceDependencyFilePaths(ProjectFileModel projectFile, string projectFilePath) { var projectDirectoryPath = PathUtilities.GetDirectoryPath(projectFilePath); var projectReferenceRelativeFilePaths = projectFile.GetProjectReferenceRelativePaths(); var projectReferenceDependencyFilePaths = Utilities.GetProjectReferenceDependencyFilePathsForProjectDirectory(projectDirectoryPath, projectReferenceRelativeFilePaths); return(projectReferenceDependencyFilePaths); }
private static void AddProjectAndPackageReferenceToProject() { var inputProjectFilePath = @"C:\Temp\temp.csproj"; var outputProjectFilePath = @"C:\Temp\temp-with references.csproj"; var projectFile = ProjectFileModel.FromFile(inputProjectFilePath) .AddPackageReference("YoYoYo", Version.Parse("1.2.3")) .AddProjectReference(@"..\..\Yo\Yo\Yo.csproj") ; projectFile.Save(outputProjectFilePath); }
private static void AddProjectAndPackageReferenceToProjectAgain() { var inputProjectFilePath = @"C:\Temp\temp-with references.csproj"; var outputProjectFilePath = @"C:\Temp\temp-with references, again.csproj"; var projectFile = ProjectFileModel.FromFile(inputProjectFilePath) .AddPackageReference("HeyHey", Version.Parse("2.3.4")) .AddProjectReference(@"..\..\Yup\Yup\Yup.csproj") ; projectFile.Save(outputProjectFilePath); }
public ActionResult ProjectFile(ProjectFileModel model) { SessionModelCollector sessionModel = this.GetFromSession <SessionModelCollector>("ProjectInfo"); if (sessionModel != null) { sessionModel.ProjectFile = model; sessionModel.IsFinished = true; } this.AddToSession("ProjectInfo", sessionModel); return(RedirectToAction("NewImages")); }
public static FileParseResult[] ParseFile(ProjectFileModel fileModel) { var parser = new CSharpParser(); SyntaxTree syntaxTree = parser.Parse(fileModel.Content, fileModel.Name); var results = parser.ErrorsAndWarnings .Select(x => new FileParseResult() { FileId = fileModel.Id, FileName = fileModel.Name, Line = x.Region.BeginLine, Column = x.Region.BeginColumn, Type = x.ErrorType, Message = x.Message }).ToArray(); return(results); }
public static void IntegrateFileModel(ProjectModel projectModel, ProjectFileModel fileModel) { // Parse C# code file => SyntaxTree // NOTE: The NRefactory Test project uses a somewhat "cleaner"/more "sanitized" version of the // file content for creating the AST. Why? I can't be certain, but I suspect that this is to // simplify testing by eliminating stuff that contribute to errors... but maybe there's something // more to it. Doing some more routine tests on our end should prove whether omitting this step // actually makes any difference. fileModel.Parser = new CSharpParser(); fileModel.SyntaxTree = fileModel.Parser.Parse(fileModel.Content, fileModel.Name); fileModel.SyntaxTree.Freeze(); // Convert syntax tree into parsed file that can be stored in the type system. fileModel.UnresolvedFile = fileModel.SyntaxTree.ToTypeSystem(); // Add specified file to the project content. // If a file with the same name already exists, this will update the existing file. projectModel.ProjectContent = projectModel.ProjectContent.AddOrUpdateFiles(fileModel.UnresolvedFile); }
public void SaveFileContent(int userId, int projectId, int fileId, string fileContent) { ProjectModel project = GetProject(userId, projectId); if (project == null) { throw new Exception(string.Format("Project {0} could not be found for user {1}. Saving a file for a new project is not yet supported", projectId, userId)); } ProjectFileModel fileModel = project.FindFile(fileId); if (fileModel == null) { throw new Exception(string.Format("File {0} could not be found within project {1} for user {2}. " + "Saving a new file in an existing project is not yet supported", fileId, projectId, userId)); } fileModel.Content = fileContent; }
//// todo: eliminate this method later //private static void AugmentProjectModelWithAlgorithmBase(ProjectModel model) //{ // model.Children.Add(QcAlgorithmFileModel.Value); //} public static ProjectAnalysisResult RunFullProjectAnalysis(ProjectAnalysisRequest projectAnalysisRequest) { Stopwatch sw = Stopwatch.StartNew(); ProjectAnalysisResult projectAnalysisResult = new ProjectAnalysisResult(); ProjectModel projectModel = projectAnalysisRequest.ProjectModel; // todo: Ask Jared why QCAlgorithm is a partial class and why it's not included in "common" #if false // ************************************************************************************ // NOTE: In order to get this project building cleanly, with minimal dependencies // before checking into Github, I've removed all hard QuantConnect dependencies, // including the QCAlgorithm.cs embedded resource and the assembly references to // QuantConnect.Algorithm.Interface // Augment the project model with the QCAgorithm base class // projectModel.Children.Add(QcAlgorithmFileModel.Value); // ************************************************************************************ #endif // Set up the project (if not already done) if (projectModel.ProjectContent == null) { projectModel.ProjectContent = new CSharpProjectContent(); projectModel.ProjectContent = projectModel.ProjectContent.AddAssemblyReferences(QCReferences.Value); } // For each new file, we need to integrate it into the project content var fileModelsInProject = projectModel.GetFileDescendants().ToArray(); foreach (var fileModelInProject in fileModelsInProject) { IntegrateFileModel(projectModel, fileModelInProject); } // We can return now if no code completion was requested if (projectAnalysisRequest.CodeCompletionParameters == null) { projectAnalysisResult.TimeElapsed = sw.Elapsed; return(projectAnalysisResult); } // Now it's time to give attention specifically to the matter of resolving the code completion // options. This, of course, requires a deeper analysis of the specified file... var codeCompletionParams = projectAnalysisRequest.CodeCompletionParameters; // Locate the file in the project ProjectFileModel fileModel = projectModel.FindFile(codeCompletionParams.FileId); if (fileModel == null) { throw new Exception("Specified file does not exist in this project"); } // Create a TypeSystem.ICompilation that allows resolving within the project. var compilation = projectModel.ProjectContent.CreateCompilation(); #region Resolve text cursor/caret location // The text cursor position is crucial to creating a properly-scoped type resolution context // so as to get relevant code completion suggestions. int textCursorOffset = 0; TextLocation textCursorLocation = new TextLocation(1, 1); ReadOnlyDocument doc = new ReadOnlyDocument(fileModel.Content); try { // if line and column aren't set, we'll assume that the cursor offset/index is set if (codeCompletionParams.Line == 0 && codeCompletionParams.Column == 0) { textCursorOffset = codeCompletionParams.Offset; if (textCursorOffset < 0) { textCursorOffset = 0; } textCursorLocation = doc.GetLocation(textCursorOffset); } // if either line or column are invalid (i.e. <= 0), then we'll use offset 0 instead else if (codeCompletionParams.Line <= 0 || codeCompletionParams.Column <= 0) { textCursorOffset = 0; } else { textCursorLocation = new TextLocation(codeCompletionParams.Line, codeCompletionParams.Column); textCursorOffset = doc.GetOffset(textCursorLocation); codeCompletionParams.Offset = textCursorOffset; } } catch (Exception) { textCursorOffset = 0; textCursorLocation = new TextLocation(1, 1); } finally { projectAnalysisResult.Line = textCursorLocation.Line; projectAnalysisResult.Column = textCursorLocation.Column; projectAnalysisResult.Offset = textCursorOffset; } #endregion #region Create and Refine the type resolution context as much as possible based upon the cursor position var typeResolveContext = new CSharpTypeResolveContext(compilation.MainAssembly); // Constrain the resolve context by using scope typeResolveContext = typeResolveContext .WithUsingScope(fileModel.UnresolvedFile.GetUsingScope(textCursorLocation) .Resolve(compilation)); var curDef = fileModel.UnresolvedFile.GetInnermostTypeDefinition(textCursorLocation); if (curDef != null) { var resolvedDef = curDef.Resolve(typeResolveContext).GetDefinition(); typeResolveContext = typeResolveContext.WithCurrentTypeDefinition(resolvedDef); var curMember = resolvedDef.Members.FirstOrDefault(m => m.Region.Begin <= textCursorLocation && textCursorLocation < m.BodyRegion.End); if (curMember != null) { typeResolveContext = typeResolveContext.WithCurrentMember(curMember); } } #endregion // The purpose of the rest of these steps is a little fuzzy in my mind... // I'm still trying to understand them fully and if/why they're all needed. // It seems there is some redundancy here... var completionContext = new DefaultCompletionContextProvider(doc, fileModel.UnresolvedFile); #region Add Preprocessor Symbols?? completionContext.AddSymbol("TEST"); foreach (var sym in fileModel.SyntaxTree.ConditionalSymbols) { completionContext.AddSymbol(sym); } #endregion var completionDataFactory = new CodeCompletionDataFactory(new CSharpResolver(typeResolveContext)); var completionEngine = new CSharpCompletionEngine(doc, completionContext, completionDataFactory, projectModel.ProjectContent, typeResolveContext); completionEngine.EolMarker = Environment.NewLine; completionEngine.FormattingPolicy = FormattingOptionsFactory.CreateMono(); projectModel.CompletionEngine = completionEngine; // Attach contextual info to analysis result GetDocumentContext(projectAnalysisResult, textCursorOffset, doc); // Finally, generate completion data! var completionOptions = completionEngine.GetCompletionData(textCursorOffset, projectAnalysisRequest.CodeCompletionParameters.CtrlSpace).ToArray(); projectAnalysisResult.CompletionOptions = completionOptions.OrderBy(x => x.CompletionText).ToArray(); projectAnalysisResult.AutoCompleteEmptyMatch = completionEngine.AutoCompleteEmptyMatch; projectAnalysisResult.AutoSelect = completionEngine.AutoSelect; projectAnalysisResult.DefaultCompletionString = completionEngine.DefaultCompletionString; int startPos, wordLength; if (completionEngine.TryGetCompletionWord(textCursorOffset, out startPos, out wordLength)) { //Debug.WriteLine("TryGetCompletionWord :: startpos:{0} wordlength:{1}", startPos, wordLength); string completionWord = projectAnalysisResult.CompletionWord = doc.GetText(startPos, wordLength); if (!string.IsNullOrWhiteSpace(completionWord)) { var bestMatch = projectAnalysisResult.CompletionOptions .FirstOrDefault(x => x.CompletionText.CompareTo(completionWord) >= 0); projectAnalysisResult.BestMatchToCompletionWord = bestMatch; //if (bestMatch != null) //projectAnalysisResult.BestMatchToCompletionWord = bestMatch.CompletionText; } } projectAnalysisResult.TimeElapsed = sw.Elapsed; return(projectAnalysisResult); }
public static ProjectAnalysisResult RunFullProjectAnalysis(ProjectAnalysisRequest projectAnalysisRequest) // ProjectModel projectModel, int fileId, int line, int column) { Stopwatch sw = Stopwatch.StartNew(); ProjectAnalysisResult projectAnalysisResult = new ProjectAnalysisResult(); ProjectModel projectModel = projectAnalysisRequest.ProjectModel; // Set up the project (if not already done) if (projectModel.ProjectContent == null) { projectModel.ProjectContent = new CSharpProjectContent(); projectModel.ProjectContent = projectModel.ProjectContent.AddAssemblyReferences(QCReferences.Value); } // For each new file, we need to integrate it into the project content var fileModelsInProject = projectModel.GetFileDescendants().ToArray(); foreach (var fileModelInProject in fileModelsInProject) { IntegrateFileModel(projectModel, fileModelInProject); } // We can return now if no code completion was requested if (projectAnalysisRequest.CodeCompletionParameters == null) { projectAnalysisResult.TimeElapsed = sw.Elapsed; return(projectAnalysisResult); } // Now it's time to give attention specifically to the matter of resolving the code completion // options. This, of course, requires a deeper analysis of the specified file... var codeCompletionParams = projectAnalysisRequest.CodeCompletionParameters; // Locate the file in the project ProjectFileModel fileModel = projectModel.FindFile(codeCompletionParams.FileId); if (fileModel == null) { throw new Exception("Specified file does not exist in this project"); } // Create a TypeSystem.ICompilation that allows resolving within the project. var compilation = projectModel.ProjectContent.CreateCompilation(); #region Resolve text cursor/caret location // The text cursor position is crucial to creating a properly-scoped type resolution context // so as to get relevant code completion suggestions. int textCursorOffset; TextLocation textCursorLocation; ReadOnlyDocument doc = new ReadOnlyDocument(fileModel.Content); if (codeCompletionParams.Line == 0 && codeCompletionParams.Column == 0) { textCursorOffset = codeCompletionParams.Offset; textCursorLocation = doc.GetLocation(textCursorOffset); codeCompletionParams.Line = textCursorLocation.Line; codeCompletionParams.Column = textCursorLocation.Column; } else { textCursorLocation = new TextLocation(codeCompletionParams.Line, codeCompletionParams.Column); textCursorOffset = doc.GetOffset(textCursorLocation); codeCompletionParams.Offset = textCursorOffset; } #endregion #region Create and Refine the type resolution context as much as possible based upon the cursor position var typeResolveContext = new CSharpTypeResolveContext(compilation.MainAssembly); // Constrain the resolve context by using scope typeResolveContext = typeResolveContext .WithUsingScope(fileModel.UnresolvedFile.GetUsingScope(textCursorLocation) .Resolve(compilation)); var curDef = fileModel.UnresolvedFile.GetInnermostTypeDefinition(textCursorLocation); if (curDef != null) { var resolvedDef = curDef.Resolve(typeResolveContext).GetDefinition(); typeResolveContext = typeResolveContext.WithCurrentTypeDefinition(resolvedDef); var curMember = resolvedDef.Members.FirstOrDefault(m => m.Region.Begin <= textCursorLocation && textCursorLocation < m.BodyRegion.End); if (curMember != null) { typeResolveContext = typeResolveContext.WithCurrentMember(curMember); } } #endregion // The purpose of the rest of these steps is a little fuzzy in my mind... // I'm still trying to understand them fully and if/why they're all needed. // It seems there is some redundancy here... var completionContext = new DefaultCompletionContextProvider(doc, fileModel.UnresolvedFile); #region Add Preprocessor Symbols?? completionContext.AddSymbol("TEST"); foreach (var sym in fileModel.SyntaxTree.ConditionalSymbols) { completionContext.AddSymbol(sym); } #endregion var completionDataFactory = new TestCompletionDataFactory(new CSharpResolver(typeResolveContext)); var completionEngine = new CSharpCompletionEngine(doc, completionContext, completionDataFactory, projectModel.ProjectContent, typeResolveContext); completionEngine.EolMarker = Environment.NewLine; completionEngine.FormattingPolicy = FormattingOptionsFactory.CreateMono(); projectModel.CompletionEngine = completionEngine; #region Debugging Aid // Resolve content around text cursor int numberOfCharactersAroundCursorToResolve = 20; int firstCharOffset = textCursorOffset - numberOfCharactersAroundCursorToResolve / 2; if (firstCharOffset < 0) { firstCharOffset = 0; } if (doc.TextLength < firstCharOffset + numberOfCharactersAroundCursorToResolve) { numberOfCharactersAroundCursorToResolve = doc.TextLength - firstCharOffset; } string surroundingText = doc.GetText(firstCharOffset, numberOfCharactersAroundCursorToResolve); Debug.WriteLine("Text around cursor: [{0}]", surroundingText); #endregion // Finally, generate completion data! var completionOptions = completionEngine.GetCompletionData(textCursorOffset, projectAnalysisRequest.CodeCompletionParameters.CtrlSpace).ToArray(); projectAnalysisResult.CompletionOptions = completionEngine.GetCompletionData(textCursorOffset, projectAnalysisRequest.CodeCompletionParameters.CtrlSpace).ToArray(); projectAnalysisResult.AutoCompleteEmptyMatch = completionEngine.AutoCompleteEmptyMatch; projectAnalysisResult.AutoSelect = completionEngine.AutoSelect; projectAnalysisResult.DefaultCompletionString = completionEngine.DefaultCompletionString; int startPos, wordLength; if (completionEngine.TryGetCompletionWord(textCursorOffset, out startPos, out wordLength)) { Debug.WriteLine("TryGetCompletionWord :: startpos:{0} wordlength:{1}", startPos, wordLength); projectAnalysisResult.CompletionWord = doc.GetText(startPos, wordLength); } projectAnalysisResult.TimeElapsed = sw.Elapsed; return(projectAnalysisResult); }
private static FileOperationResponse Server_HandleStatefulFileOperationRequest(FileOperationRequest request) { FileOperationResponse response = new FileOperationResponse(); ProjectModel projectModel = null; ProjectFileModel fileModel = null; try { projectModel = ServerProjectRepository.GetProject(request.UserId, request.ProjectId); if (projectModel == null) { response.SetError("Specified project could not be located."); return(response); } fileModel = ServerProjectRepository.GetFile(request.UserId, request.ProjectId, request.FileId); if (fileModel == null) { response.SetError("Specified file could not be located within the project."); return(response); } } catch (Exception ex) { response.SyncContent.SetError(ex); } // Set contextual identifiers on response response.UserId = request.UserId; response.ProjectId = request.ProjectId; response.FileId = request.FileId; // Now, handle each requested operation... if (request.SyncContent != null) { response.SyncContent = new FileSyncContentResponse(); fileModel.Content = request.SyncContent.Content; response.SyncContent.Status = ResponseStatus.OK; } if (request.Parse != null) { response.Parse = new FileParseResponse(); try { response.Parse.Errors = NRefactoryUtils.ParseFile(fileModel); response.Parse.Status = ResponseStatus.OK; } catch (Exception ex) { response.Parse.SetError(ex); } } if (request.CompleteCode != null) { response.CompleteCode = new FileCodeCompletionResponse(); try { var analysisRequest = new ProjectAnalysisRequest() { ProjectModel = projectModel, CodeCompletionParameters = new ProjectAnalysisCodeCompletionParameters() { FileId = request.FileId, Line = request.CompleteCode.LineNumber, Column = request.CompleteCode.ColumnNumber } }; var analysisResult = NRefactoryUtils.RunFullProjectAnalysis(analysisRequest); response.CompleteCode.CompletionOptions = analysisResult.CompletionOptions.Select(x => new FileCodeCompletionResult() { CompletionText = x.CompletionText, DisplayText = x.DisplayText }).ToArray(); response.CompleteCode.Status = ResponseStatus.OK; } catch (Exception ex) { response.CompleteCode.SetError(ex); } } response.Status = ResponseStatus.OK; return(response); }
public ActionResult ProjectFile() { ProjectFileModel model = new ProjectFileModel() { PathToFile = "ERROR" }; try { SessionModelCollector sessionModel = this.GetFromSession <SessionModelCollector>("ProjectInfo"); if (sessionModel.Figures.Count <= 0) { return(RedirectToAction("Figure", "FigureList")); } var filepath = sessionModel.SessionDirectoryPath + @"\document.augp"; using (FileStream fileStream = new FileStream(filepath, FileMode.Create)) //create the .augp file in the user's temp folder { XmlWriterSettings settings = new XmlWriterSettings() { Indent = true }; using (XmlWriter writer = XmlWriter.Create(fileStream, settings)) { writer.WriteStartDocument(false); //start file writer.WriteStartElement("AugmentedPaper"); //METADATA writer.WriteStartElement("MetaData"); writer.WriteAttributeString("ArticleName", sessionModel.MetaData.ProjectName); writer.WriteAttributeString("DOI", sessionModel.MetaData.DOI); writer.WriteStartElement("Authors"); if (sessionModel.Authors != null) { foreach (var item in sessionModel.Authors) { writer.WriteStartElement("Author"); writer.WriteAttributeString("Name", item.FullName); writer.WriteAttributeString("Affiliation", item.Affiliation); writer.WriteEndElement(); //</Figure> } } else { writer.WriteComment("No authors found."); } writer.WriteEndElement(); //</Authors> writer.WriteEndElement(); //</MetaData> //METADATA ENDS //FIGURES writer.WriteStartElement("Figures"); //Figures if (sessionModel.Figures != null && sessionModel.Figures.Count > 0) { for (int i = 0; i < sessionModel.Figures.Count; i++) { writer.WriteStartElement("Figure"); writer.WriteAttributeString("Id", i.ToString()); writer.WriteAttributeString("Title", sessionModel.Figures[i].Name); writer.WriteAttributeString("ObjFile", sessionModel.Figures[i].ObjPath); writer.WriteAttributeString("MtlFile", sessionModel.Figures[i].MtlPath); writer.WriteEndElement(); //</Figure> } } else { writer.WriteComment("No models found."); } writer.WriteEndElement(); //</Figures> //FIGURES END writer.WriteEndElement(); //</AugmentedPaper> //end file writer.Flush(); } fileStream.Flush(); } model.PathToFile = filepath; sessionModel.ProjectFile = model; this.AddToSession("ProjectInfo", sessionModel); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.StackTrace); } return(this.CheckViewFirst(model)); }