/// <summary> /// Migrates logic class files over to the blazor server project. /// </summary> /// <param name="webFormProjectData">List of pre cached models for from the web form project.</param> /// <param name="webFormProject">The web forms project that we are migrating data from.</param> /// <param name="blazorServerProject">The blazor server project this is being migrated to.</param> public async Task MigrateLogic(IReadOnlyList <VsModel> webFormProjectData, VsProject webFormProject, VsProject blazorServerProject) { try { //Informing the dialog the migration step has started. await _statusTracking.UpdateStepStatusAsync(MigrationStepEnum.AppLogic, MigrationStatusEnum.Running); var childFiles = webFormProjectData.GetSourceCodeDocumentsAsync(true); //we don't want any known aspx/ascx files hitching a ride. just plain vanilla *.cs files should qualify. var logicFiles = childFiles.Where(p => (!p.Name.ToLower().Contains("aspx.") && !p.Name.ToLower().Contains("ascx.") && !p.Name.ToLower().Contains("asax."))).ToList(); //put logic files (using the file system into the target under the project root) foreach (VsCSharpSource sourceDocument in logicFiles) { //look for specific files that are native to a WebForm app and skip them. ** TODO: move this to a config setting maybe? if (sourceDocument.Name.ToLower().Contains("bundleconfig")) { continue; } if (sourceDocument.Name.ToLower().Contains("assemblyinfo")) { continue; } if (sourceDocument.Name.ToLower().Contains("startup")) { continue; } if (sourceDocument.Name.ToLower().Contains(".master")) { continue; } var logicDocument = await sourceDocument.LoadDocumentModelAsync(); var parentFolders = await logicDocument.GetParentFolders(); var source = sourceDocument.SourceCode; var docText = await logicDocument.GetDocumentContentAsStringAsync(); if (parentFolders.Count >= 1) { parentFolders.Reverse(); //The folders are returned in leaf-to-trunk so need to reverse the order for the next step. VsProjectFolder createdFolder = null; //deal with source folder hierarchy for (int i = 0; i < parentFolders.Count; i++) { if (i > 0) { createdFolder = await createdFolder.CheckAddFolder(parentFolders[i].Name); } else { createdFolder = await blazorServerProject.CheckAddFolder(parentFolders[i].Name); } } //copy the file. We only really care about the most leaf/edge subfolder so its safe to use the creatdFolder variable here. docText = docText.Replace(source.Classes.First().Namespace, $"{blazorServerProject.Name}.{createdFolder.Name}"); var targetFolderFiles = await createdFolder.GetChildrenAsync(false); if (!targetFolderFiles.Any(c => c.Name.ToLower().Equals(logicDocument.Name.ToLower()))) { await createdFolder.AddDocumentAsync(logicDocument.Name, docText); //Updating the dialog with a status await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.AppLogic, MessageTypeEnum.Information, $"Copied logic file: {logicDocument.Name} to project {blazorServerProject.Name} location: {Path.Combine(createdFolder.Path, logicDocument.Name)}"); } else { await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.AppLogic, MessageTypeEnum.Warning, $"Logic file: {logicDocument.Name} already exists in target folder location: {Path.Combine(createdFolder.Path, logicDocument.Name)} and was skipped."); } } else { var projFiles = await blazorServerProject.GetChildrenAsync(false); if (!projFiles.Any(c => c.Name.ToLower().Equals(logicDocument.Name.ToLower()))) { docText = docText.Replace(source.Classes.First().Namespace, $"{blazorServerProject.Name}"); var thing = await blazorServerProject.AddDocumentAsync(logicDocument.Name, docText); //Updating the dialog with a status await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.AppLogic, MessageTypeEnum.Information, $"Copied static file: {logicDocument.Name} to project {blazorServerProject.Name} location: {Path.Combine(blazorServerProject.Path, logicDocument.Name)}"); } else { //Updating the dialog with a status await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.AppLogic, MessageTypeEnum.Warning, $"Static file: {logicDocument.Name} already exists in project {blazorServerProject.Name} location: {Path.Combine(blazorServerProject.Path, logicDocument.Name)} and was skipped."); } } } //Completed the migration step informing the dialog. await _statusTracking.UpdateStepStatusAsync(MigrationStepEnum.AppLogic, MigrationStatusEnum.Passed); } catch (Exception unhandledError) { //Dumping the exception that occured directly into the status so the user can see what happened. await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.AppLogic, MessageTypeEnum.Error, $"The following unhandled error occured. '{unhandledError.Message}'"); //Updating the status that the step failed await _statusTracking.UpdateStepStatusAsync(MigrationStepEnum.AppLogic, MigrationStatusEnum.Failed); } }
/// <summary> /// Migrates the definition of existing Http Modules that were used in the web forms project into the blazor project. /// </summary> /// <param name="webFormProjectData">Pre cached project data about the web forms project.</param> /// <param name="webFormProject">The web forms project that we are migrating data from.</param> /// <param name="blazorServerProject">The blazor server project this is being migrated to.</param> public async Task MigrateHttpModulesAsync(IReadOnlyList <VsModel> webFormProjectData, VsProject webFormProject, VsProject blazorServerProject) { try { //Letting the dialog know the http modules migration has started. await _statusTracking.UpdateStepStatusAsync(MigrationStepEnum.HttpModules, MigrationStatusEnum.Running); //find class(es) that inherit HttpApplication var handlerClasses = webFormProjectData.GetClassesThatImplementInterface("IHttpHandler"); var moduleClasses = webFormProjectData.GetClassesThatImplementInterface("IHttpModule"); if (!handlerClasses.Any() && !moduleClasses.Any()) { //No handler classes or modules were found updating the status and exiting this step. await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.Startup, MessageTypeEnum.Error, $"No classes were found in {webFormProject.Name} that inherit from either 'IHttpHandler' or 'IHttpModule'"); //Setting the status to passed wasn't a failure and the solution will not require these to be added. await _statusTracking.UpdateStepStatusAsync(MigrationStepEnum.HttpModules, MigrationStatusEnum.Passed); return; } //Making sure a modules folder exists, if it does not create it in the blazor server project. var modulesFolder = await blazorServerProject.CheckAddFolder("Modules"); //Creating a dictionary that holds the target namespace for modules. var conversionData = new Dictionary <string, string> { { "Namespace", $"{blazorServerProject.DefaultNamespace}.Modules" } }; CsModelStore store = null; //Create a class file in the Modules folder from a T4 Template for each handler class foreach (CsSource source in handlerClasses) { //Setting up the model data to pass off to a T4 Factory store = new CsModelStore(); store.SetModel(source); //Calling the T4 factory and getting back the formatted file content. var fileContent = ModuleFactory.GenerateSource(store, conversionData); //Calling CodeFactory project system API to add a new document to the project folder, also injecting the new file content into the file. await modulesFolder.AddDocumentAsync($"{Path.GetFileNameWithoutExtension(source.SourceDocument)}Handler.cs", fileContent); //Clearing model store for the next call store = null; } //Create a class file in the Modules folder from a T4 Template for each model class foreach (CsSource source in moduleClasses) { store = new CsModelStore(); store.SetModel(source); await _visualStudioActions.ProjectFolderActions.AddDocumentAsync(modulesFolder, $"{Path.GetFileNameWithoutExtension(source.SourceDocument)}Handler.cs", ModuleFactory.GenerateSource(store, conversionData)); store = null; } //Completed process the modules informing the dialog it has passed. await _statusTracking.UpdateStepStatusAsync(MigrationStepEnum.HttpModules, MigrationStatusEnum.Passed); } catch (Exception unhandledError) { //Dumping the exception that occured directly into the status so the user can see what happened. await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.HttpModules, MessageTypeEnum.Error, $"The following unhandled error occured. '{unhandledError.Message}'"); //Updating the status that the step failed await _statusTracking.UpdateStepStatusAsync(MigrationStepEnum.HttpModules, MigrationStatusEnum.Failed); } }
/// <summary> /// Migrates the site.master layout files from the source WebForms project into the \Shared folder /// in the Blazor target application project. /// </summary> /// <param name="webFormSiteMasterFiles">The flattened list of WebForms project objects/files</param> /// <param name="blazorServerProject">The target Blazor project object</param> /// <returns></returns> /// private async Task ConvertAspxPage(VsDocument sourcePage, VsProject targetProject, VsProjectFolder targetPagesFolder, VsCSharpSource sourceCodeBehind = null) private async Task <string> ConvertLayoutFiles(IEnumerable <VsModel> webFormSiteMasterFiles, VsProject blazorServerProject) { string headerData = null; //put the files in the target project var targetFolder = await blazorServerProject.CheckAddFolder("Shared"); try { foreach (var layoutFile in webFormSiteMasterFiles) { //We don't want to touch/migrate any of the *.designer files if (layoutFile.Name.ToLower().Contains("designer")) { continue; } String targetFileName = layoutFile.Name.Replace(".", ""); //Get any existing children in the targetFolder that match. var existingBlazorMatches = await targetFolder.GetChildrenAsync(true, false); var docMatches = existingBlazorMatches.Where(p => p.Name.ToLower().Contains(targetFileName.ToLower())).Cast <VsDocument>(); foreach (VsDocument matchFile in docMatches) { //delete each matched file in the target folder. await matchFile.DeleteAsync(); } //work on just the Site.Master file which is basically a specialized *.aspx file. if (!layoutFile.Name.ToLower().Contains(".cs")) { var docObj = layoutFile as VsDocument; var textFromResult = await docObj.GetDocumentContentAsStringAsync(); //grab the <%Page element from the source and pull it from the text. Its meta data anyway and just screws up the conversion down the line. var pageHeaderData = System.Text.RegularExpressions.Regex.Match(textFromResult, @"<%@\s*[^%>]*(.*?)\s*%>").Value; if (pageHeaderData.Length > 0) { textFromResult = Regex.Replace(textFromResult, @"<%@\s*[^%>]*(.*?)\s*%>", string.Empty); } //Swap ASP.NET string tokens for Razor syntax (<%, <%@, <%:, <%#:, etc var targetText = RemoveASPNETSyntax(textFromResult); //Convert Site.Master file into razor syntax, specifically the asp:controls that might be used there. var conversionData = await ReplaceAspControls(targetText); //Drop the pageHeaderData into the Dictionary for later processing by any downstream T4 factories conversionData.Add("HeaderData", pageHeaderData); //Setup Page directives, using statements etc var targetWithMeta = await SetRazorPageDirectives(targetFileName, conversionData); VsDocument success = await _visualStudioActions.ProjectFolderActions.AddDocumentAsync(targetFolder, $"{targetFileName}.razor", targetWithMeta); //Updating the dialog await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.AspxPages, MessageTypeEnum.Information, $"The file {targetFileName}.razor was copied to {targetFolder.Name}."); } //Get sibling/named code-behind file //1. Get the children of this *.aspx file //2. Grab the doc that has the same name with a ".cs" extension on the end of it if (layoutFile.Name.Contains(".cs")) { targetFileName = layoutFile.Name.Replace(".cs", ""); targetFileName = targetFileName.Replace(".", ""); var sourceObj = layoutFile as VsCSharpSource; var codeSource = sourceObj.SourceCode; var metaDataDictionary = new Dictionary <string, string>(); metaDataDictionary.Add("Namespace", $"{blazorServerProject.Name}.Pages"); //Setup Page directives, using statements etc //var targetWithMeta = await SetRazorPageDirectives(targetFileName, conversionData); CsModelStore modelStore = new CsModelStore(); modelStore.SetModel(codeSource.Classes.FirstOrDefault()); var codebehind = await _visualStudioActions.ProjectFolderActions.AddDocumentAsync(targetFolder, $"{targetFileName}.razor.cs", Templates.PageCodeBehind.GenerateSource(modelStore, metaDataDictionary)); // Updating the dialog await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.AspxPages, MessageTypeEnum.Information, $"The file {targetFileName}.razor.cs was copied to {targetFolder.Name}."); } } } catch (Exception unhandledError) { await _statusTracking.UpdateCurrentStatusAsync(MigrationStepEnum.AspxPages, MessageTypeEnum.Error, $"The following unhandled error occured while trying to migrate the layout files. '{unhandledError.Message}'"); } return(headerData); }