Microsoft.Extensions.Logging.ILogger.LogInformation(string, params object[])

Here are the examples of the csharp api Microsoft.Extensions.Logging.ILogger.LogInformation(string, params object[]) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

2119 Examples 7

19 View Source File : MinimumAgeAuthorizationHandler.cs
License : Apache License 2.0
Project Creator : aspnet

protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, MinimumAgeRequirement requirement)
        {
            // Log as a warning so that it's very clear in sample output which authorization policies 
            // (and requirements/handlers) are in use
            _logger.LogWarning("Evaluating authorization requirement for age >= {age}", requirement.Age);

            // Check the user's age
            var dateOfBirthClaim = context.User.FindFirst(c => c.Type == ClaimTypes.DateOfBirth);
            if (dateOfBirthClaim != null)
            {
                // If the user has a date of birth claim, check their age
                var dateOfBirth = Convert.ToDateTime(dateOfBirthClaim.Value);
                var age = DateTime.Now.Year - dateOfBirth.Year;
                if (dateOfBirth > DateTime.Now.AddYears(-age))
                {
                    // Adjust age if the user hasn't had a birthday yet this year
                    age--;
                }

                // If the user meets the age criterion, mark the authorization requirement succeeded
                if (age >= requirement.Age)
                {
                    _logger.LogInformation("Minimum age authorization requirement {age} satisfied", requirement.Age);
                    context.Succeed(requirement);
                }
                else
                {
                    _logger.LogInformation("Current user's DateOfBirth claim ({dateOfBirth}) does not satisfy the minimum age authorization requirement {age}",
                        dateOfBirthClaim.Value,
                        requirement.Age);
                }
            }
            else
            {
                _logger.LogInformation("No DateOfBirth claim present");
            }

            return Task.CompletedTask;
        }

19 View Source File : Register.cshtml.cs
License : Apache License 2.0
Project Creator : aspnet

public async Task<IActionResult> OnPostAsync(string returnUrl = null)
        {
            ReturnUrl = returnUrl;
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser { UserName = Input.Email, Email = Input.Email };
                var result = await _userManager.CreateAsync(user, Input.Preplacedword);
                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with preplacedword.");

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                    var callbackUrl = Url.EmailConfirmationLink(user.Id, code, Request.Scheme);
                    await _emailSender.SendEmailConfirmationAsync(Input.Email, callbackUrl);

                    await _signInManager.SignInAsync(user, isPersistent: false);
                    return LocalRedirect(Url.GetLocalUrl(returnUrl));
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return Page();
        }

19 View Source File : AccountController.cs
License : Apache License 2.0
Project Creator : aspnet

[HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Logout()
        {
            await _signInManager.SignOutAsync();
            _logger.LogInformation("User logged out.");
            return RedirectToPage("/Index");
        }

19 View Source File : ChangePassword.cshtml.cs
License : Apache License 2.0
Project Creator : aspnet

public async Task<IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return Page();
            }

            var user = await _userManager.GetUserAsync(User);
            if (user == null)
            {
                throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
            }

            var changePreplacedwordResult = await _userManager.ChangePreplacedwordAsync(user, Input.OldPreplacedword, Input.NewPreplacedword);
            if (!changePreplacedwordResult.Succeeded)
            {
                foreach (var error in changePreplacedwordResult.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
                return Page();
            }

            await _signInManager.SignInAsync(user, isPersistent: false);
            _logger.LogInformation("User changed their preplacedword successfully.");
            StatusMessage = "Your preplacedword has been changed.";

            return RedirectToPage();
        }

19 View Source File : Disable2fa.cshtml.cs
License : Apache License 2.0
Project Creator : aspnet

public async Task<IActionResult> OnPostAsync()
        {
            var user = await _userManager.GetUserAsync(User);
            if (user == null)
            {
                throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
            }

            var disable2faResult = await _userManager.SetTwoFactorEnabledAsync(user, false);
            if (!disable2faResult.Succeeded)
            {
                throw new ApplicationException($"Unexpected error occurred disabling 2FA for user with ID '{_userManager.GetUserId(User)}'.");
            }

            _logger.LogInformation("User with ID '{UserId}' has disabled 2fa.", _userManager.GetUserId(User));

            return RedirectToPage("./TwoFactorAuthentication");
        }

19 View Source File : GenerateRecoveryCodes.cshtml.cs
License : Apache License 2.0
Project Creator : aspnet

public async Task<IActionResult> OnGetAsync()
        {
            var user = await _userManager.GetUserAsync(User);
            if (user == null)
            {
                throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
            }

            if (!user.TwoFactorEnabled)
            {
                throw new ApplicationException($"Cannot generate recovery codes for user with ID '{user.Id}' as they do not have 2FA enabled.");
            }

            var recoveryCodes = await _userManager.GenerateNewTwoFactorRecoveryCodesAsync(user, 10);
            RecoveryCodes = recoveryCodes.ToArray();

            _logger.LogInformation("User with ID '{UserId}' has generated new 2FA recovery codes.", user.Id);

            return Page();
        }

19 View Source File : ResetAuthenticator.cshtml.cs
License : Apache License 2.0
Project Creator : aspnet

public async Task<IActionResult> OnPostAsync()
        {
            var user = await _userManager.GetUserAsync(User);
            if (user == null)
            {
                throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
            }

            await _userManager.SetTwoFactorEnabledAsync(user, false);
            await _userManager.ResetAuthenticatorKeyAsync(user);
            _logger.LogInformation("User with ID '{UserId}' has reset their authentication app key.", user.Id);

            return RedirectToPage("./EnableAuthenticator");
        }

19 View Source File : ExternalLogin.cshtml.cs
License : Apache License 2.0
Project Creator : aspnet

public async Task<IActionResult> OnPostConfirmationAsync(string returnUrl = null)
        {
            if (ModelState.IsValid)
            {
                // Get the information about the user from the external login provider
                var info = await _signInManager.GetExternalLoginInfoAsync();
                if (info == null)
                {
                    throw new ApplicationException("Error loading external login information during confirmation.");
                }
                var user = new ApplicationUser { UserName = Input.Email, Email = Input.Email };
                var result = await _userManager.CreateAsync(user);
                if (result.Succeeded)
                {
                    result = await _userManager.AddLoginAsync(user, info);
                    if (result.Succeeded)
                    {
                        // Copy over the gender claim as well
                        await _userManager.AddClaimAsync(user, info.Principal.FindFirst(ClaimTypes.Gender));

                        // Include the access token in the properties
                        var props = new AuthenticationProperties();
                        props.StoreTokens(info.AuthenticationTokens);

                        await _signInManager.SignInAsync(user, props, authenticationMethod: info.LoginProvider);
                        _logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider);
                        return LocalRedirect(Url.GetLocalUrl(returnUrl));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            ReturnUrl = returnUrl;
            return Page();
        }

19 View Source File : Login.cshtml.cs
License : Apache License 2.0
Project Creator : aspnet

public async Task<IActionResult> OnPostAsync(string returnUrl = null)
        {
            ReturnUrl = returnUrl;

            if (ModelState.IsValid)
            {
                // This doesn't count login failures towards account lockout
                // To enable preplacedword failures to trigger account lockout, set lockoutOnFailure: true
                var result = await _signInManager.PreplacedwordSignInAsync(Input.Email, Input.Preplacedword, Input.RememberMe, lockoutOnFailure: true);
                if (result.Succeeded)
                {
                    _logger.LogInformation("User logged in.");
                    return LocalRedirect(Url.GetLocalUrl(returnUrl));
                }
                if (result.RequiresTwoFactor)
                {
                    return RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe });
                }
                if (result.IsLockedOut)
                {
                    _logger.LogWarning("User account locked out.");
                    return RedirectToPage("./Lockout");
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                    return Page();
                }
            }

            // If we got this far, something failed, redisplay form
            return Page();
        }

19 View Source File : EnableAuthenticator.cshtml.cs
License : Apache License 2.0
Project Creator : aspnet

public async Task<IActionResult> OnPostAsync()
        {
            var user = await _userManager.GetUserAsync(User);
            if (user == null)
            {
                throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
            }

            if (!ModelState.IsValid)
            {
                await LoadSharedKeyAndQrCodeUriAsync(user);
                return Page();
            }

            // Strip spaces and hypens
            var verificationCode = Input.Code.Replace(" ", string.Empty).Replace("-", string.Empty);

            var is2faTokenValid = await _userManager.VerifyTwoFactorTokenAsync(
                user, _userManager.Options.Tokens.AuthenticatorTokenProvider, verificationCode);

            if (!is2faTokenValid)
            {
                ModelState.AddModelError("Input.Code", "Verification code is invalid.");
                await LoadSharedKeyAndQrCodeUriAsync(user);
                return Page();
            }

            await _userManager.SetTwoFactorEnabledAsync(user, true);
            _logger.LogInformation("User with ID '{UserId}' has enabled 2FA with an authenticator app.", user.Id);
            return RedirectToPage("./GenerateRecoveryCodes");
        }

19 View Source File : LoginWith2fa.cshtml.cs
License : Apache License 2.0
Project Creator : aspnet

public async Task<IActionResult> OnPostAsync(bool rememberMe, string returnUrl = null)
        {
            if (!ModelState.IsValid)
            {
                return Page();
            }

            var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
            if (user == null)
            {
                throw new ApplicationException($"Unable to load two-factor authentication user.");
            }

            var authenticatorCode = Input.TwoFactorCode.Replace(" ", string.Empty).Replace("-", string.Empty);

            var result = await _signInManager.TwoFactorAuthenticatorSignInAsync(authenticatorCode, rememberMe, Input.RememberMachine);

            if (result.Succeeded)
            {
                _logger.LogInformation("User with ID '{UserId}' logged in with 2fa.", user.Id);
                return LocalRedirect(Url.GetLocalUrl(returnUrl));
            }
            else if (result.IsLockedOut)
            {
                _logger.LogWarning("User with ID '{UserId}' account locked out.", user.Id);
                return RedirectToPage("./Lockout");
            }
            else
            {
                _logger.LogWarning("Invalid authenticator code entered for user with ID '{UserId}'.", user.Id);
                ModelState.AddModelError(string.Empty, "Invalid authenticator code.");
                return Page();
            }
        }

19 View Source File : LoginWithRecoveryCode.cshtml.cs
License : Apache License 2.0
Project Creator : aspnet

public async Task<IActionResult> OnPostAsync(string returnUrl = null)
        {
            if (!ModelState.IsValid)
            {
                return Page();
            }

            var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();
            if (user == null)
            {
                throw new ApplicationException($"Unable to load two-factor authentication user.");
            }

            var recoveryCode = Input.RecoveryCode.Replace(" ", string.Empty);

            var result = await _signInManager.TwoFactorRecoveryCodeSignInAsync(recoveryCode);
                
            if (result.Succeeded)
            {
                _logger.LogInformation("User with ID '{UserId}' logged in with a recovery code.", user.Id);
                return LocalRedirect(Url.GetLocalUrl(returnUrl));
            }
            if (result.IsLockedOut)
            {
                _logger.LogWarning("User with ID '{UserId}' account locked out.", user.Id);
                return RedirectToPage("./Lockout");
            }
            else
            {
                _logger.LogWarning("Invalid recovery code entered for user with ID '{UserId}' ", user.Id);
                ModelState.AddModelError(string.Empty, "Invalid recovery code entered.");
                return Page();
            }
        }

19 View Source File : MinimumAgeAuthorizationHandler.cs
License : Apache License 2.0
Project Creator : aspnet

protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, MinimumAgeRequirement requirement)
        {
            // Log as a warning so that it's very clear in sample output which authorization policies 
            // (and requirements/handlers) are in use
            _logger.LogWarning("Evaluating authorization requirement for age >= {age}", requirement.Age);

            // Check the user's age
            var dateOfBirthClaim = context.User.FindFirst(c => c.Type == ClaimTypes.DateOfBirth);
            if (dateOfBirthClaim != null)
            {
                // If the user has a date of birth claim, check their age
                var dateOfBirth = Convert.ToDateTime(dateOfBirthClaim.Value);
                var age = DateTime.Now.Year - dateOfBirth.Year;
                if (dateOfBirth > DateTime.Now.AddYears(-age))
                {
                    // Adjust age if the user hasn't had a birthday yet this year
                    age--;
                }

                // If the user meets the age criterion, mark the authorization requirement succeeded
                if (age >= requirement.Age)
                {
                    _logger.LogInformation("Minimum age authorization requirement {age} satisfied", requirement.Age);
                    context.Succeed(requirement);
                }
                else
                {
                    _logger.LogInformation("Current user's DateOfBirth claim ({dateOfBirth}) does not satisfy the minimum age authorization requirement {age}",
                        dateOfBirthClaim.Value,
                        requirement.Age);
                }
            }
            else
            {
                _logger.LogInformation("No DateOfBirth claim present");
            }

            return Task.CompletedTask;
        }

19 View Source File : ExternalLogin.cshtml.cs
License : Apache License 2.0
Project Creator : aspnet

public async Task<IActionResult> OnGetCallbackAsync(string returnUrl = null, string remoteError = null)
        {
            if (remoteError != null)
            {
                ErrorMessage = $"Error from external provider: {remoteError}";
                return RedirectToPage("./Login");
            }
            var info = await _signInManager.GetExternalLoginInfoAsync();
            if (info == null)
            {
                return RedirectToPage("./Login");
            }

            // Sign in the user with this external login provider if the user already has a login.
            var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false, bypreplacedTwoFactor : true);
            if (result.Succeeded)
            {
                // Store the access token and resign in so the token is included in the cookie
                var user = await _userManager.FindByLoginAsync(info.LoginProvider, info.ProviderKey);
                var props = new AuthenticationProperties();
                props.StoreTokens(info.AuthenticationTokens);
                await _signInManager.SignInAsync(user, props, info.LoginProvider);

                _logger.LogInformation("{Name} logged in with {LoginProvider} provider.", info.Principal.Idenreplacedy.Name, info.LoginProvider);
                return LocalRedirect(Url.GetLocalUrl(returnUrl));
            }
            if (result.IsLockedOut)
            {
                return RedirectToPage("./Lockout");
            }
            else
            {
                // If the user does not have an account, then ask the user to create an account.
                ReturnUrl = returnUrl;
                LoginProvider = info.LoginProvider;
                if (info.Principal.HasClaim(c => c.Type == ClaimTypes.Email))
                {
                    Input = new InputModel
                    {
                        Email = info.Principal.FindFirstValue(ClaimTypes.Email)
                    };
                }
                return Page();
            }
        }

19 View Source File : DefaultRazorProjectService.cs
License : Apache License 2.0
Project Creator : aspnet

public override void AddDoreplacedent(string filePath)
        {
            _foregroundDispatcher.replacedertForegroundThread();

            var textDoreplacedentPath = _filePathNormalizer.Normalize(filePath);
            if (_doreplacedentResolver.TryResolveDoreplacedent(textDoreplacedentPath, out var _))
            {
                // Doreplacedent already added. This usually occurs when VSCode has already pre-initialized
                // open doreplacedents and then we try to manually add all known razor doreplacedents.
                return;
            }

            if (!_projectResolver.TryResolvePotentialProject(textDoreplacedentPath, out var projectSnapshot))
            {
                projectSnapshot = _projectResolver.GetMiscellaneousProject();
            }

            var targetFilePath = textDoreplacedentPath;
            var projectDirectory = _filePathNormalizer.GetDirectory(projectSnapshot.FilePath);
            if (targetFilePath.StartsWith(projectDirectory, FilePathComparison.Instance))
            {
                // Make relative
                targetFilePath = textDoreplacedentPath.Substring(projectDirectory.Length);
            }

            // Representing all of our host doreplacedents with a re-normalized target path to workaround GetRelatedDoreplacedent limitations.
            var normalizedTargetFilePath = targetFilePath.Replace('/', '\\').TrimStart('\\');

            var hostDoreplacedent = _hostDoreplacedentFactory.Create(textDoreplacedentPath, normalizedTargetFilePath);
            var defaultProject = (DefaultProjectSnapshot)projectSnapshot;
            var textLoader = _remoteTextLoaderFactory.Create(textDoreplacedentPath);

            _logger.LogInformation($"Adding doreplacedent '{filePath}' to project '{projectSnapshot.FilePath}'.");
            _projectSnapshotManagerAccessor.Instance.DoreplacedentAdded(defaultProject.HostProject, hostDoreplacedent, textLoader);
        }

19 View Source File : DefaultRazorProjectService.cs
License : Apache License 2.0
Project Creator : aspnet

public override void OpenDoreplacedent(string filePath, SourceText sourceText, long version)
        {
            _foregroundDispatcher.replacedertForegroundThread();

            var textDoreplacedentPath = _filePathNormalizer.Normalize(filePath);
            if (!_doreplacedentResolver.TryResolveDoreplacedent(textDoreplacedentPath, out var _))
            {
                // Doreplacedent hasn't been added. This usually occurs when VSCode trumps all other initialization 
                // processes and pre-initializes already open doreplacedents.
                AddDoreplacedent(filePath);
            }

            if (!_projectResolver.TryResolvePotentialProject(textDoreplacedentPath, out var projectSnapshot))
            {
                projectSnapshot = _projectResolver.GetMiscellaneousProject();
            }

            var defaultProject = (DefaultProjectSnapshot)projectSnapshot;

            _logger.LogInformation($"Opening doreplacedent '{textDoreplacedentPath}' in project '{projectSnapshot.FilePath}'.");
            _projectSnapshotManagerAccessor.Instance.DoreplacedentOpened(defaultProject.HostProject.FilePath, textDoreplacedentPath, sourceText);
            TrackDoreplacedentVersion(textDoreplacedentPath, version);

        }

19 View Source File : DefaultRazorProjectService.cs
License : Apache License 2.0
Project Creator : aspnet

public override void CloseDoreplacedent(string filePath)
        {
            _foregroundDispatcher.replacedertForegroundThread();

            var textDoreplacedentPath = _filePathNormalizer.Normalize(filePath);
            if (!_projectResolver.TryResolvePotentialProject(textDoreplacedentPath, out var projectSnapshot))
            {
                projectSnapshot = _projectResolver.GetMiscellaneousProject();
            }

            var textLoader = _remoteTextLoaderFactory.Create(filePath);
            var defaultProject = (DefaultProjectSnapshot)projectSnapshot;
            _logger.LogInformation($"Closing doreplacedent '{textDoreplacedentPath}' in project '{projectSnapshot.FilePath}'.");
            _projectSnapshotManagerAccessor.Instance.DoreplacedentClosed(defaultProject.HostProject.FilePath, textDoreplacedentPath, textLoader);
        }

19 View Source File : DefaultRazorProjectService.cs
License : Apache License 2.0
Project Creator : aspnet

public override void RemoveDoreplacedent(string filePath)
        {
            _foregroundDispatcher.replacedertForegroundThread();

            var textDoreplacedentPath = _filePathNormalizer.Normalize(filePath);
            if (!_projectResolver.TryResolvePotentialProject(textDoreplacedentPath, out var projectSnapshot))
            {
                projectSnapshot = _projectResolver.GetMiscellaneousProject();
            }

            if (!projectSnapshot.DoreplacedentFilePaths.Contains(textDoreplacedentPath, FilePathComparer.Instance))
            {
                _logger.LogInformation($"Containing project is not tracking doreplacedent '{filePath}");
                return;
            }

            var doreplacedent = (DefaultDoreplacedentSnapshot)projectSnapshot.GetDoreplacedent(textDoreplacedentPath);
            var defaultProject = (DefaultProjectSnapshot)projectSnapshot;
            _logger.LogInformation($"Removing doreplacedent '{textDoreplacedentPath}' from project '{projectSnapshot.FilePath}'.");
            _projectSnapshotManagerAccessor.Instance.DoreplacedentRemoved(defaultProject.HostProject, doreplacedent.State.HostDoreplacedent);
        }

19 View Source File : DefaultRazorProjectService.cs
License : Apache License 2.0
Project Creator : aspnet

public override void AddProject(string filePath)
        {
            _foregroundDispatcher.replacedertForegroundThread();

            var normalizedPath = _filePathNormalizer.Normalize(filePath);
            var hostProject = new HostProject(normalizedPath, RazorDefaults.Configuration, RazorDefaults.RootNamespace);
            _projectSnapshotManagerAccessor.Instance.ProjectAdded(hostProject);
            _logger.LogInformation($"Added project '{filePath}' to project system.");

            TryMigrateMiscellaneousDoreplacedentsToProject();
        }

19 View Source File : DefaultRazorProjectService.cs
License : Apache License 2.0
Project Creator : aspnet

public override void RemoveProject(string filePath)
        {
            _foregroundDispatcher.replacedertForegroundThread();

            var normalizedPath = _filePathNormalizer.Normalize(filePath);
            var project = (DefaultProjectSnapshot)_projectSnapshotManagerAccessor.Instance.GetLoadedProject(normalizedPath);

            if (project == null)
            {
                // Never tracked the project to begin with, noop.
                return;
            }

            _logger.LogInformation($"Removing project '{filePath}' from project system.");
            _projectSnapshotManagerAccessor.Instance.ProjectRemoved(project.HostProject);

            TryMigrateDoreplacedentsFromRemovedProject(project);
        }

19 View Source File : DefaultRazorProjectService.cs
License : Apache License 2.0
Project Creator : aspnet

public override void UpdateProject(
            string filePath,
            RazorConfiguration configuration,
            string rootNamespace,
            ProjectWorkspaceState projectWorkspaceState,
            IReadOnlyList<DoreplacedentSnapshotHandle> doreplacedents)
        {
            _foregroundDispatcher.replacedertForegroundThread();

            var normalizedPath = _filePathNormalizer.Normalize(filePath);
            var project = (DefaultProjectSnapshot)_projectSnapshotManagerAccessor.Instance.GetLoadedProject(normalizedPath);

            if (project == null)
            {
                // Never tracked the project to begin with, noop.
                _logger.LogInformation($"Failed to update untracked project '{filePath}'.");
                return;
            }

            UpdateProjectDoreplacedents(doreplacedents, project);

            if (!projectWorkspaceState.Equals(ProjectWorkspaceState.Default))
            {
                _logger.LogInformation($"Updating project '{filePath}' TagHelpers ({projectWorkspaceState.TagHelpers.Count}) and C# Language Version ({projectWorkspaceState.CSharpLanguageVersion}).");
            }

            _projectSnapshotManagerAccessor.Instance.ProjectWorkspaceStateChanged(project.FilePath, projectWorkspaceState);

            var currentHostProject = project.HostProject;
            var currentConfiguration = currentHostProject.Configuration;
            if (currentConfiguration.ConfigurationName == configuration?.ConfigurationName &&
                currentHostProject.RootNamespace == rootNamespace)
            {
                _logger.LogTrace($"Updating project '{filePath}'. The project is already using configuration '{configuration.ConfigurationName}' and root namespace '{rootNamespace}'.");
                return;
            }

            if (configuration == null)
            {
                configuration = RazorDefaults.Configuration;
                _logger.LogInformation($"Updating project '{filePath}' to use Razor's default configuration ('{configuration.ConfigurationName}')'.");
            }
            else if (currentConfiguration.ConfigurationName != configuration.ConfigurationName)
            {
                _logger.LogInformation($"Updating project '{filePath}' to Razor configuration '{configuration.ConfigurationName}' with language version '{configuration.LanguageVersion}'.");
            }

            if (currentHostProject.RootNamespace != rootNamespace)
            {
                _logger.LogInformation($"Updating project '{filePath}''s root namespace to '{rootNamespace}'.");
            }

            var hostProject = new HostProject(project.FilePath, configuration, rootNamespace);
            _projectSnapshotManagerAccessor.Instance.ProjectConfigurationChanged(hostProject);
        }

19 View Source File : DefaultRazorProjectService.cs
License : Apache License 2.0
Project Creator : aspnet

internal void TryMigrateDoreplacedentsFromRemovedProject(ProjectSnapshot project)
        {
            _foregroundDispatcher.replacedertForegroundThread();

            var miscellaneousProject = _projectResolver.GetMiscellaneousProject();

            foreach (var doreplacedentFilePath in project.DoreplacedentFilePaths)
            {
                var doreplacedentSnapshot = (DefaultDoreplacedentSnapshot)project.GetDoreplacedent(doreplacedentFilePath);

                if (!_projectResolver.TryResolvePotentialProject(doreplacedentFilePath, out var toProject))
                {
                    // This is the common case. It'd be rare for a project to be nested but we need to protect against it anyhow.
                    toProject = miscellaneousProject;
                }

                var textLoader = new DoreplacedentSnapshotTextLoader(doreplacedentSnapshot);
                var defaultToProject = (DefaultProjectSnapshot)toProject;
                var newHostDoreplacedent = _hostDoreplacedentFactory.Create(doreplacedentSnapshot.FilePath, doreplacedentSnapshot.TargetPath);

                _logger.LogInformation($"Migrating '{doreplacedentFilePath}' from the '{project.FilePath}' project to '{toProject.FilePath}' project.");
                _projectSnapshotManagerAccessor.Instance.DoreplacedentAdded(defaultToProject.HostProject, newHostDoreplacedent, textLoader);
            }
        }

19 View Source File : DefaultRazorProjectService.cs
License : Apache License 2.0
Project Creator : aspnet

internal void TryMigrateMiscellaneousDoreplacedentsToProject()
        {
            _foregroundDispatcher.replacedertForegroundThread();

            var miscellaneousProject = _projectResolver.GetMiscellaneousProject();

            foreach (var doreplacedentFilePath in miscellaneousProject.DoreplacedentFilePaths)
            {
                if (!_projectResolver.TryResolvePotentialProject(doreplacedentFilePath, out var projectSnapshot))
                {
                    continue;
                }

                var doreplacedentSnapshot = (DefaultDoreplacedentSnapshot)miscellaneousProject.GetDoreplacedent(doreplacedentFilePath);

                // Remove from miscellaneous project
                var defaultMiscProject = (DefaultProjectSnapshot)miscellaneousProject;
                _projectSnapshotManagerAccessor.Instance.DoreplacedentRemoved(defaultMiscProject.HostProject, doreplacedentSnapshot.State.HostDoreplacedent);

                // Add to new project

                var textLoader = new DoreplacedentSnapshotTextLoader(doreplacedentSnapshot);
                var defaultProject = (DefaultProjectSnapshot)projectSnapshot;
                var newHostDoreplacedent = _hostDoreplacedentFactory.Create(doreplacedentSnapshot.FilePath, doreplacedentSnapshot.TargetPath);
                _logger.LogInformation($"Migrating '{doreplacedentFilePath}' from the '{miscellaneousProject.FilePath}' project to '{projectSnapshot.FilePath}' project.");
                _projectSnapshotManagerAccessor.Instance.DoreplacedentAdded(defaultProject.HostProject, newHostDoreplacedent, textLoader);
            }
        }

19 View Source File : Program.cs
License : Apache License 2.0
Project Creator : aspnet

public static async Task MainAsync(string[] args)
        {
            var logLevel = LogLevel.Information;
            for (var i = 0; i < args.Length; i++)
            {
                if (args[i].IndexOf("debug", StringComparison.OrdinalIgnoreCase) >= 0)
                {
                    while (!Debugger.IsAttached)
                    {
                        Thread.Sleep(1000);
                    }

                    Debugger.Break();
                    continue;
                }

                if (args[i] == "--logLevel" && i + 1 < args.Length)
                {
                    var logLevelString = args[++i];
                    if (!Enum.TryParse(logLevelString, out logLevel))
                    {
                        logLevel = LogLevel.Information;
                        Console.WriteLine($"Invalid log level '{logLevelString}'. Defaulting to {logLevel.ToString()}.");
                    }
                }
            }

            Serializer.Instance.JsonSerializer.Converters.RegisterRazorConverters();

            var factory = new LoggerFactory();
            ILanguageServer server = null;
            server = await OmniSharp.Extensions.LanguageServer.Server.LanguageServer.From(options =>
                options
                    .WithInput(Console.OpenStandardInput())
                    .WithOutput(Console.OpenStandardOutput())
                    .WithLoggerFactory(factory)
                    .AddDefaultLoggingProvider()
                    .WithMinimumLogLevel(logLevel)
                    .WithHandler<RazorDoreplacedentSynchronizationEndpoint>()
                    .WithHandler<RazorCompletionEndpoint>()
                    .WithHandler<RazorLanguageEndpoint>()
                    .WithHandler<RazorProjectEndpoint>()
                    .WithServices(services =>
                    {
                        services.AddSingleton<RemoteTextLoaderFactory, DefaultRemoteTextLoaderFactory>();
                        services.AddSingleton<ProjectResolver, DefaultProjectResolver>();
                        services.AddSingleton<DoreplacedentResolver, DefaultDoreplacedentResolver>();
                        services.AddSingleton<FilePathNormalizer>();
                        services.AddSingleton<RazorProjectService, DefaultRazorProjectService>();
                        services.AddSingleton<ProjectSnapshotChangeTrigger, BackgroundDoreplacedentGenerator>();
                        services.AddSingleton<DoreplacedentProcessedListener, RazorDiagnosticsPublisher>();
                        services.AddSingleton<HostDoreplacedentFactory, DefaultHostDoreplacedentFactory>();
                        services.AddSingleton<ProjectSnapshotManagerAccessor, DefaultProjectSnapshotManagerAccessor>();
                        services.AddSingleton<TagHelperFactsService, DefaultTagHelperFactsService>();
                        services.AddSingleton<VisualStudio.Editor.Razor.TagHelperCompletionService, VisualStudio.Editor.Razor.DefaultTagHelperCompletionService>();
                        services.AddSingleton<TagHelperDescriptionFactory, DefaultTagHelperDescriptionFactory>();

                        // Completion
                        services.AddSingleton<Completion.TagHelperCompletionService, Completion.DefaultTagHelperCompletionService>();
                        services.AddSingleton<RazorCompletionItemProvider, DirectiveCompletionItemProvider>();
                        services.AddSingleton<RazorCompletionItemProvider, DirectiveAttributeCompletionItemProvider>();
                        services.AddSingleton<RazorCompletionItemProvider, DirectiveAttributeParameterCompletionItemProvider>();
                        services.AddSingleton<RazorCompletionItemProvider, DirectiveAttributeTransitionCompletionItemProvider>();

                        var foregroundDispatcher = new VSCodeForegroundDispatcher();
                        services.AddSingleton<ForegroundDispatcher>(foregroundDispatcher);
                        services.AddSingleton<RazorCompletionFactsService, DefaultRazorCompletionFactsService>();
                        var doreplacedentVersionCache = new DefaultDoreplacedentVersionCache(foregroundDispatcher);
                        services.AddSingleton<DoreplacedentVersionCache>(doreplacedentVersionCache);
                        services.AddSingleton<ProjectSnapshotChangeTrigger>(doreplacedentVersionCache);
                        var containerStore = new DefaultGeneratedCodeContainerStore(
                            foregroundDispatcher,
                            doreplacedentVersionCache,
                            new Lazy<ILanguageServer>(() => server));
                        services.AddSingleton<GeneratedCodeContainerStore>(containerStore);
                        services.AddSingleton<ProjectSnapshotChangeTrigger>(containerStore);
                    }));

            // Workaround for https://github.com/OmniSharp/csharp-language-server-protocol/issues/106
            var languageServer = (OmniSharp.Extensions.LanguageServer.Server.LanguageServer)server;
            languageServer.MinimumLogLevel = logLevel;

            try
            {
                var logger = factory.CreateLogger<Program>();
                var replacedemblyInformationAttribute = typeof(Program).replacedembly.GetCustomAttribute<replacedemblyInformationalVersionAttribute>();
                logger.LogInformation("Razor Language Server version " + replacedemblyInformationAttribute.InformationalVersion);
            }
            catch
            {
                // Swallow exceptions from determining replacedembly information.
            }

            await server.WaitForExit;

            TempDirectory.Instance.Dispose();
        }

19 View Source File : RazorDocumentSynchronizationEndpoint.cs
License : Apache License 2.0
Project Creator : aspnet

public Task<Unit> Handle(DidSaveTextDoreplacedentParams notification, CancellationToken token)
        {
            _logger.LogInformation($"Saved Doreplacedent {notification.TextDoreplacedent.Uri.AbsolutePath}");

            return Unit.Task;
        }

19 View Source File : BizTalkAnalyzerBase.cs
License : MIT License
Project Creator : Azure

public async Task replacedyzeAsync(CancellationToken token)
        {
            _logger.LogInformation(InformationMessages.RunningBizTalkreplacedyzer, Name);

            await replacedyzeInternalAsync(token).ConfigureAwait(false);
        }

19 View Source File : AssemblyDiscoverer.cs
License : MIT License
Project Creator : Azure

[System.Diagnostics.Codereplacedysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "This is by design")]
        private void DiscoverreplacedemblyContents(AzureIntegrationServicesModel model, MigrationContext context)
        {
            // Iterate through the applications and discover the contents of the replacedemblies.
            var group = model.GetSourceModel<ParsedBizTalkApplicationGroup>();

            if (group?.Applications == null)
            {
                _logger.LogDebug(TraceMessages.SkippingDiscoveryAsTheSourceModelIsMissing, nameof(replacedemblyDiscoverer));
            }
            else
            { 
                foreach (var application in group.Applications)
                {
                    _logger.LogDebug(TraceMessages.DiscoveringreplacedemblyContentsInResourceContainer, application.ResourceContainerKey);

                    // Find replacedemblies replacedociated with this application
                    var replacedemblies = from msiResourceContainer in model.MigrationSource.ResourceContainers
                                     from cabResourceContainer in msiResourceContainer.ResourceContainers
                                     from replacedemblyResourceContainers in cabResourceContainer.ResourceContainers
                                     from replacedembly in application.Application.replacedemblies
                                     where replacedembly.ResourceContainerKey == replacedemblyResourceContainers.Key &&                                        
                                        replacedemblyResourceContainers.Type == ModelConstants.ResourceContainerreplacedembly
                                     select replacedemblyResourceContainers;

                    // Iterate through the replacedemblies discovered for each application.
                    foreach (var replacedembly in replacedemblies)
                    {
                        try
                        { 
                            _logger.LogDebug(TraceMessages.DiscoveringTheResourcesInreplacedemblyCointainer, replacedembly.Name);

                            // Check to ensure the replacedembly is a managed (.Net) replacedembly
                            if (IsManagedreplacedembly(replacedembly.ContainerLocation))
                            {
                                using (var replacedemblyDefinition = replacedemblyDefinition.Readreplacedembly(replacedembly.ContainerLocation))
                                {
                                    // Loads the components that are packaged into a BizTalk replacedembly, adding them to the replacedembly container.
                                    LoadSchemas(replacedemblyDefinition, application, replacedembly);
                                    LoadTransforms(replacedemblyDefinition, application, replacedembly);
                                    LoadReceivePipelines(replacedemblyDefinition, application, replacedembly);
                                    LoadSendPipelines(replacedemblyDefinition, application, replacedembly);
                                    LoadOrchestrations(replacedemblyDefinition, application, replacedembly);
                                }
                            }
                            else
                            {
                                // Log and skip
                                _logger.LogInformation(InformationMessages.UnmanagedreplacedemblyDiscovered, replacedembly.Name);
                            }
                        }
                        catch (Exception ex)
                        {
                            var message = string.Format(CultureInfo.CurrentCulture, ErrorMessages.UnableToLoadreplacedembly, replacedembly.Name, ex.Message);
                            context.Errors.Add(new ErrorMessage(message));
                            _logger.LogError(message);
                        }
                    }
                }
            }
        }

19 View Source File : BizTalkReporterBase.cs
License : MIT License
Project Creator : Azure

public void Report()
        {
            Logger.LogInformation(InformationMessages.StartReport, GetType().Name);

            ReportInternal();

            Logger.LogInformation(InformationMessages.EndReport, GetType().Name);
        }

19 View Source File : ResourceGeneratorAnalyzer.cs
License : MIT License
Project Creator : Azure

protected override void GetArgs()
        {
            // Template Config Directory
            var argTemplateConfigDir = GetArg<string>(ArgTemplateConfigPath);
            if (!string.IsNullOrWhiteSpace(argTemplateConfigDir))
            {
                _logger.LogInformation(InformationMessages.ArgumentsFound, ArgTemplateConfigPath, argTemplateConfigDir);

                _templateConfigDir = new DirectoryInfo(argTemplateConfigDir).FullName;
            }

            // Azure Integration Services Target
            var argTarget = GetArg<string>(ArgAzureIntegrationServicesTarget);
            if (!string.IsNullOrWhiteSpace(argTarget))
            {
                _logger.LogInformation(InformationMessages.ArgumentsFound, ArgAzureIntegrationServicesTarget, argTarget);

                _target = Enum.Parse<AzureIntegrationServicesTargetEnvironment>(argTarget);
            }

            // Azure Subscription ID
            var argSubscriptionId = GetArg<string>(ArgAzureSubscriptionId);
            if (!string.IsNullOrWhiteSpace(argSubscriptionId))
            {
                _logger.LogInformation(InformationMessages.ArgumentsFound, ArgAzureSubscriptionId, argSubscriptionId);

                _subscriptionId = argSubscriptionId;
            }

            // Azure Primary Region
            var argPrimaryRegion = GetArg<string>(ArgAzurePrimaryRegion);
            if (!string.IsNullOrWhiteSpace(argPrimaryRegion))
            {
                _logger.LogInformation(InformationMessages.ArgumentsFound, ArgAzurePrimaryRegion, argPrimaryRegion);

                _primaryRegion = argPrimaryRegion;
            }

            // Azure Secondary Region
            var argSecondaryRegion = GetArg<string>(ArgAzureSecondaryRegion);
            if (!string.IsNullOrWhiteSpace(argSecondaryRegion))
            {
                _logger.LogInformation(InformationMessages.ArgumentsFound, ArgAzureSecondaryRegion, argSecondaryRegion);

                _secondaryRegion = argSecondaryRegion;
            }

            // Deployment Environment
            var argDeploymentEnv = GetArg<string>(ArgDeploymentEnvironment);
            if (!string.IsNullOrWhiteSpace(argDeploymentEnv))
            {
                _logger.LogInformation(InformationMessages.ArgumentsFound, ArgDeploymentEnvironment, argDeploymentEnv);

                _deploymentEnvironment = argDeploymentEnv;
            }

            // Unique Deployment ID
            var argUniqueDeploymentId = GetArg<string>(ArgUniqueDeploymentId);
            if (!string.IsNullOrWhiteSpace(argUniqueDeploymentId))
            {
                _logger.LogInformation(InformationMessages.ArgumentsFound, ArgUniqueDeploymentId, argUniqueDeploymentId);

                _uniqueDeploymentId = argUniqueDeploymentId;
            }
        }

19 View Source File : ArtifactGeneratorConverter.cs
License : MIT License
Project Creator : Azure

protected override void GetArgs()
        {
            // Conversion Directory
            var argConversionDir = GetArg<string>(ArgConversionPath);
            if (!string.IsNullOrWhiteSpace(argConversionDir))
            {
                _logger.LogInformation(InformationMessages.ArgumentsFound, ArgConversionPath, argConversionDir);

                _conversionPath = new DirectoryInfo(argConversionDir).FullName;
            }

            // Generation Directory
            var argGenerationDir = GetArg<string>(ArgGenerationPath);
            if (!string.IsNullOrWhiteSpace(argGenerationDir))
            {
                _logger.LogInformation(InformationMessages.ArgumentsFound, ArgGenerationPath, argGenerationDir);

                _generationPath = new DirectoryInfo(argGenerationDir).FullName;
            }

            // Template Directories
            var argValue = GetArg(ArgTemplatePaths);
            if (argValue != null)
            {
                _logger.LogInformation(InformationMessages.ArgumentsFound, ArgTemplatePaths, argValue);

                // Should be an array of directories
                foreach (var dir in (string[])argValue)
                {
                    _templatePaths.Add(dir);
                }
            }
        }

19 View Source File : MsiDiscoverer.cs
License : MIT License
Project Creator : Azure

protected override void GetArgs()
        {
            // MSI Files
            var argValue = GetArg(ArgMsiFiles);
            if (argValue != null)
            {
                _logger.LogInformation(InformationMessages.ArgumentsFound, ArgMsiFiles, argValue);

                // Is it a string array (multiple files)?
                var argMsiFiles = argValue as string[];
                if (argMsiFiles != null)
                {
                    foreach (var filePath in argMsiFiles)
                    {
                        _msiFiles.Add(new FileInfo(filePath).FullName);
                    }
                }
                else
                {
                    _msiFiles.Add(new FileInfo((string)argValue).FullName);
                }
            }

            // MSI Directory
            var argMsiDir = GetArg<string>(ArgMsiDirectory);
            if (!string.IsNullOrWhiteSpace(argMsiDir))
            {
                _logger.LogInformation(InformationMessages.ArgumentsFound, ArgMsiDirectory, argMsiDir);

                _msiDirectory = new DirectoryInfo(argMsiDir).FullName;
            }

            // Unpack Directory
            var argUnpackDir = GetArg<string>(ArgUnpackDirectory);
            if (!string.IsNullOrWhiteSpace(argUnpackDir))
            {
                _logger.LogInformation(InformationMessages.ArgumentsFound, ArgUnpackDirectory, argUnpackDir);

                _unpackDirectory = new DirectoryInfo(argUnpackDir).FullName;
            }
        }

19 View Source File : HtmlReporter.cs
License : MIT License
Project Creator : Azure

protected override void GetArgs()
        {
            // Report File
            var argReportFile = GetArg<string>(ArgReportFile);
            if (!string.IsNullOrWhiteSpace(argReportFile))
            {
                _logger.LogInformation(InformationMessages.ArgumentsFound, ArgReportFile, argReportFile);

                _reportFilePath = new FileInfo(argReportFile).FullName;
            }
        }

19 View Source File : TemplateRendererConverter.cs
License : MIT License
Project Creator : Azure

protected override async Task ConvertInternalAsync(CancellationToken token)
        {
            // Ensure conversion path exists
            var conversionPath = new DirectoryInfo(Context.ConversionFolder);
            if (!_fileRepository.DoesDirectoryExist(conversionPath.FullName))
            {
                _logger.LogDebug(TraceMessages.CreatingConversionPath, conversionPath.FullName);

                _fileRepository.CreateDirectory(conversionPath.FullName);
            }

            // Get template paths
            var templatePaths = Context.TemplateFolders.Select(p => new DirectoryInfo(p));
            if (templatePaths.Any())
            {
                // Render templates
                var generatedFiles = 0;
                var messageBus = Model.MigrationTarget.MessageBus;
                if (messageBus != null)
                {
                    // Message Bus
                    generatedFiles += await GenerateFilesAsync(messageBus, templatePaths, conversionPath).ConfigureAwait(false);

                    // Applications
                    if (messageBus.Applications.Any())
                    {
                        foreach (var application in messageBus.Applications)
                        {
                            generatedFiles += await GenerateFilesAsync(application, templatePaths, conversionPath).ConfigureAwait(false);

                            // Messages
                            if (application.Messages.Any())
                            {
                                foreach (var message in application.Messages)
                                {
                                    generatedFiles += await GenerateFilesAsync(message, templatePaths, conversionPath).ConfigureAwait(false);
                                }
                            }

                            // Channels
                            if (application.Channels.Any())
                            {
                                foreach (var channel in application.Channels)
                                {
                                    generatedFiles += await GenerateFilesAsync(channel, templatePaths, conversionPath).ConfigureAwait(false);
                                }
                            }

                            // Intermediaries
                            if (application.Intermediaries.Any())
                            {
                                foreach (var intermediary in application.Intermediaries)
                                {
                                    generatedFiles += await GenerateFilesAsync(intermediary, templatePaths, conversionPath).ConfigureAwait(false);
                                }
                            }

                            // Endpoints
                            if (application.Endpoints.Any())
                            {
                                foreach (var endpoint in application.Endpoints)
                                {
                                    generatedFiles += await GenerateFilesAsync(endpoint, templatePaths, conversionPath).ConfigureAwait(false);
                                }
                            }
                        }
                    }
                }

                if (generatedFiles == 0)
                {
                    _logger.LogInformation(InformationMessages.NoResourceTemplatesToConvert);
                }
                else
                {
                    _logger.LogInformation(InformationMessages.GeneratedResourceTemplateFiles, generatedFiles);
                }
            }
            else
            {
                _logger.LogWarning(WarningMessages.NoTemplatePathsFound);
            }
        }

19 View Source File : BizTalkDiscovererBase.cs
License : MIT License
Project Creator : Azure

public void Discover()
        {
            _logger.LogInformation(InformationMessages.RunningBizTalkDiscoverer, Name);

            DiscoverInternal(_model, _context);
        }

19 View Source File : TemplateRendererConverter.cs
License : MIT License
Project Creator : Azure

protected override void GetArgs()
        {
            // Conversion Directory
            var argConversionDir = GetArg<string>(ArtifactGeneratorConverter.ArgConversionPath);
            if (!string.IsNullOrWhiteSpace(argConversionDir))
            {
                _logger.LogInformation(InformationMessages.ArgumentsFound, ArtifactGeneratorConverter.ArgConversionPath, argConversionDir);

                _conversionPath = new DirectoryInfo(argConversionDir).FullName;
            }

            // Generation Directory
            var argGenerationDir = GetArg<string>(ArtifactGeneratorConverter.ArgGenerationPath);
            if (!string.IsNullOrWhiteSpace(argGenerationDir))
            {
                _logger.LogInformation(InformationMessages.ArgumentsFound, ArtifactGeneratorConverter.ArgGenerationPath, argGenerationDir);

                _generationPath = new DirectoryInfo(argGenerationDir).FullName;
            }

            // Template Directories
            var argValue = GetArg(ArtifactGeneratorConverter.ArgTemplatePaths);
            if (argValue != null)
            {
                _logger.LogInformation(InformationMessages.ArgumentsFound, ArtifactGeneratorConverter.ArgTemplatePaths, argValue);

                // Should be an array of directories
                foreach (var dir in (string[])argValue)
                {
                    _templatePaths.Add(dir);
                }
            }
        }

19 View Source File : HtmlReporter.cs
License : MIT License
Project Creator : Azure

protected override async Task InvokeRunAsync(IRunState state, CancellationToken token)
        {
            // Default file path if not specified
            if (string.IsNullOrWhiteSpace(_reportFilePath))
            {
                _reportFilePath = Path.Combine(Environment.CurrentDirectory, DefaultReportFileName);
            }

            _logger.LogInformation(InformationMessages.ReportFilePath, _reportFilePath);

            // Try and create directories if they doesn't exist
            var fileInfo = new FileInfo(_reportFilePath);
            if (!fileInfo.Directory.Exists)
            {
                _logger.LogDebug(TraceMessages.CreatingDirectoriesForReportFilePath, _reportFilePath);

                // Ensure directories exist
                Directory.CreateDirectory(fileInfo.Directory.FullName);
            }

            // Get context (initialize the context - means this runner MUST run first)
            var context = Container.GetRequiredService<MigrationContext>();
            context.ReportFilePath = _reportFilePath;

            // Build report (should be async)
            var reporter = Container.GetRequiredService<BizTalk.Report.HtmlReportFormatter>();
            reporter.Report();

            await Task.CompletedTask.ConfigureAwait(false);
        }

19 View Source File : Program.cs
License : MIT License
Project Creator : Azure

static void Main()
        {
            using (var loggerFactory = LoggerFactory.Create(builder => builder.AddConsole().SetMinimumLevel(LogLevel.Trace)))
            {
                var logger = loggerFactory.CreateLogger<Program>();

                var outputPath = @"../../../../../output/";
                outputPath = Path.GetFullPath(outputPath);

                var context = new MigrationContext() { WorkingFolder = outputPath };

                // Paths to the MSI test files
                var msiPaths = new string[]
                {
                @"../../../../../tests/BTS2010FlatFilePipelineSample.msi",
                @"../../../../../tests/BTS2020SimpleMessagingApplication.msi",
                @"../../../../../tests/BTS2020SimpleReferencedApplication.msi",
                @"../../../../../tests/BTS2020SimplePipelineDataApplication.msi",

                // Path to scenarios MSI
                @"../../../../../scenarios/001-FtpPreplacedthru/msi/Aim.FtpPreplacedthru.msi",
                @"../../../../../scenarios/002-XmlMapping/msi/XmlMapping.msi",
                @"../../../../../scenarios/003-SimpleOrchestration/msi/Aim.SimpleOrchestration.msi",
                @"../../../../../scenarios/004-HttpJsonOrch/msi/Aim.HttpJsonOrch.msi",
                };

                // New application model
                var model = new AzureIntegrationServicesModel();

                // New run state
                var state = new RunState(new RunnerConfiguration(), model);

                // Create the input criteria (paths to the MSIs)
                foreach (var path in msiPaths)
                {
                    var pathInfo = new FileInfo(path);
                    model.MigrationSource.ResourceContainers.Add(new ResourceContainer() { Key = pathInfo.Name, Name = pathInfo.Name, Type = ModelConstants.ResourceContainerMsi, ContainerLocation = pathInfo.FullName });
                }

                // Setup the discoverers.
                var discoverers = new IBizTalkDiscoverer[]
                {
                    new MsiDiscoverer(new FileRepository(), model, context, logger),
                    new replacedemblyDiscoverer(model, context, logger)
                };

                logger.LogInformation(InformationMessages.DiscoveringStarted);

                // Run the discoverers.
                foreach (var discoverer in discoverers)
                {
                    discoverer.Discover();
                }

                logger.LogInformation(InformationMessages.DiscoveringComplete);

                // Setup the parsers
                var parsers = new IBizTalkParser[]
                {
                    // Parse the application definition file
                    new ApplicationDefinitionParser(model, context, logger),
                    // Parse the application name
                    new BizTalkApplicationParser(model, context, logger),
                    // Parse the module Refs
                    new BindingFileParser(model, context, logger),
                    // Parse the send port
                    new SendPortParser(model, context, logger),
                    // Parse the Orchestration Odx contents.
                    new BizTalkOrchestrationParser(model, context, logger),
                    // Parse the send port group filters
                    new DistributionListParser(model, context, logger),
                    // Parse the pipelines
                    new BizTalkPipelineParser(model, context, logger),
                    // Parse the property schemas
                    new PropertySchemaPropertyParser(model, context, logger),
                    // Parse the doreplacedent schemas
                    new DoreplacedentSchemaParser(model, context, logger),
                    // Parse the send pipeline data
                    new SendPortPipelineDataParser(model, context, logger),
                    // Parse the receive pipeline data
                    new ReceivePortPipelineDataParser(model, context, logger),
                    // Parse the receive port
                    new ReceivePortParser(model, context, logger),
                    // Parse the transforms
                    new TransformParser(model, context, logger),
                    // Parse the pipeline components
                    new PipelineComponentParser(model, context, logger),
                    // Parse the orchestration correlation types
                    new OrchestrationCorrelationTypeParser(model, context, logger),
                    // Parse the orchestration port types
                    new OrchestrationPortTypeParser(model, context, logger),
                    // Parse the orchestration multi part message types
                    new OrchestrationMultiPartMessageTypeParser(model, context, logger),
                    // Parse the orchestration service declarations
                    new OrchestrationServiceDeclarationParser(model, context, logger)
                };

                logger.LogInformation(InformationMessages.ParsingStarted);

                foreach (var parser in parsers)
                {
                    parser.Parse();
                }

                logger.LogInformation(InformationMessages.ParsingComplete);

                var replacedyzers = new IBizTalkreplacedyzer[]
                {
                    new DP001SchemaDependencyreplacedyzer(model, context, logger),
                    new DP002TransformDependencyreplacedyzer(model, context, logger),
                    new DP003OrchestrationDependencyreplacedyzer(model, context, logger),
                    new DP004ApplicationDependencyreplacedyzer(model, context, logger),
                    new DP005DistributionListDependencyreplacedyzer(model, context, logger),
                    new DP006ParentChildDependencyreplacedyzer(model, context, logger),
                    new MB001MessageBusreplacedyzer(model, context, logger),
                    new AP001Applicationreplacedyzer(model, context, logger),
                    new AP002SystemApplicationreplacedyzer(model, context, logger),
                    new MB002MessageBoxreplacedyzer(model, context, logger),
                    new SC001Schemareplacedyzer(model, context, logger),
                    new SC002PropertySchemareplacedyzer(model, context, logger)
                };
                
                logger.LogInformation(InformationMessages.replacedysisStarted);

                foreach (var replacedyzer in replacedyzers) 
                {
                    var task = replacedyzer.replacedyzeAsync(CancellationToken.None);
                    task.Wait();
                }

                logger.LogInformation(InformationMessages.replacedysisComplete);

                logger.LogInformation(InformationMessages.ReportingStarting);

                var reportWriter = new FileReportWriter();
                context.ReportFilePath = Path.Combine(context.WorkingFolder, "BizTalkMigrationReport.html");
                var reporters = new IBizTalkReporter[]
                {
                    new HtmlReportFormatter(model, context, state, reportWriter, logger)
                };

                foreach (var reporter in reporters)
                {
                    reporter.Report();
                }

                logger.LogInformation(InformationMessages.ReportingComplete);

                // Output the results
                var serializer = new JsonSerializer();
                using var writer = new StringWriter();
                serializer.Serialize(writer, model);
                File.WriteAllText(Path.Combine(context.WorkingFolder, "model.json"), writer.ToString());
            }
        }

19 View Source File : AppOptionsService.cs
License : MIT License
Project Creator : Azure

public void PrintOptions()
        {
            // Print verb
            _logger.LogInformation(InformationMessages.Verb, Verb);

            // Common app options
            _logger.LogInformation(InformationMessages.Verbose, _options.Value.Verbose);

            if (_options.Value.Verbose)
            {
                _logger.LogInformation(InformationMessages.VerboseLevel, _options.Value.VerboseLevel);
            }

            _logger.LogInformation(InformationMessages.Abort, !_options.Value.NoAbort);

            if (_options.Value.AbortStage != null)
            {
                foreach (var stage in _options.Value.AbortStage)
                {
                    _logger.LogInformation(InformationMessages.AbortStage, stage);
                }
            }

            if (_options.Value.Arg != null)
            {
                foreach (var arg in _options.Value.Arg)
                {
                    _logger.LogInformation(InformationMessages.Arg, arg.Key, arg.Value);
                }
            }

            _logger.LogInformation(InformationMessages.ArgDelimiter, _options.Value.ArgDelimiter);

            if (_options.Value.FindPath != null)
            {
                foreach (var path in _options.Value.FindPath)
                {
                    _logger.LogInformation(InformationMessages.FindPath, path.FullName);
                }
            }

            _logger.LogInformation(InformationMessages.FindPattern, _options.Value.FindPattern);
            _logger.LogInformation(InformationMessages.WorkingPath, _options.Value.WorkingPath?.FullName);
            _logger.LogInformation(InformationMessages.StatePath, _options.Value.StatePath);
            _logger.LogInformation(InformationMessages.SaveState, _options.Value.SaveState);
            _logger.LogInformation(InformationMessages.SaveStageState, _options.Value.SaveStageState);
            _logger.LogInformation(InformationMessages.Target, _options.Value.Target);
            _logger.LogInformation(InformationMessages.DeploymentEnv, _options.Value.DeploymentEnv);
            _logger.LogInformation(InformationMessages.UniqueDeploymentId, _options.Value.UniqueDeploymentId);

            if (_options.Value.ConversionPath != null)
            {
                _logger.LogInformation(InformationMessages.ConversionPath, _options.Value.ConversionPath);
            }

            if (_options.Value.SubscriptionId != null)
            {
                _logger.LogInformation(InformationMessages.AzureSubscriptionId, _options.Value.SubscriptionId);
            }

            if (_options.Value.PrimaryRegion != null)
            {
                _logger.LogInformation(InformationMessages.AzurePrimaryRegion, _options.Value.PrimaryRegion);
            }

            if (_options.Value.SecondaryRegion != null)
            {
                _logger.LogInformation(InformationMessages.AzureSecondaryRegion, _options.Value.SecondaryRegion);
            }

            if (_options.Value.OutputModel != null)
            {
                _logger.LogInformation(InformationMessages.OutputModelFile, _options.Value.OutputModel);
            }

            if (_options.Value.TemplateConfigPath != null)
            {
                _logger.LogInformation(InformationMessages.TemplateConfigPath, _options.Value.TemplateConfigPath.FullName);
            }

            if (_options.Value.Model != null)
            {
                _logger.LogInformation(InformationMessages.ModelFile, _options.Value.Model.FullName);
            }

            if (_options.Value.TemplatePath != null)
            {
                foreach (var path in _options.Value.TemplatePath)
                {
                    _logger.LogInformation(InformationMessages.TemplatePath, path.FullName);
                }
            }
        }

19 View Source File : PluginFinder.cs
License : MIT License
Project Creator : Azure

public IEnumerable<string> FindPluginreplacedemblies(string pluginPath, Type[] sharedTypes)
        {
            _logger.LogInformation(InformationMessages.SearchingPluginPath, typeof(TPlugin).Name, pluginPath);

            var replacedemblyPaths = new List<string>();

            // Check directory
            var path = new DirectoryInfo(pluginPath);
            if (path.Exists)
            {
                var files = path.GetFiles(_options.FindPattern, SearchOption.AllDirectories);
                if (files.Any())
                {
                    _logger.LogInformation(InformationMessages.LibraryCountFoundInPath, files.Length, path.FullName);
                    _logger.LogInformation(InformationMessages.ScanningLibraries);

                    foreach (var libPath in files)
                    {
                        _logger.LogTrace(TraceMessages.CheckingLibraryForPlugins, libPath.FullName);

                        // Create plugin replacedembly load context to hold the replacedemblies and dependencies per library
                        var pluginContext = new PluginreplacedemblyLoadContext(libPath.FullName, sharedTypes);

                        // Don't load the library containing the plugin type itself into the plugin replacedemblyLoadContext,
                        // otherwise the IsreplacedignableFrom won't return a match, because the same replacedembly in different
                        // contexts have types that are not the same as each other when comparing in .NET Core.
                        if (libPath.Name != new FileInfo(typeof(TPlugin).replacedembly.Location).Name)
                        {
                            try
                            {
                                var replacedembly = pluginContext.LoadFromreplacedemblyPath(libPath.FullName);

                                foreach (var type in replacedembly.GetExportedTypes().Where(t => !t.IsAbstract))
                                {
                                    var interfaceType = typeof(TPlugin);
                                    if (interfaceType.IsreplacedignableFrom(type))
                                    {
                                        _logger.LogTrace(TraceMessages.FoundPlugin, type.FullName, libPath.FullName);

                                        replacedemblyPaths.Add(type.replacedembly.Location);
                                    }
                                }
                            }
                            catch (FileNotFoundException e)
                            {
                                _logger.LogDebug(TraceMessages.IgnoringLibraryMissingDependencies, libPath.FullName);
                                _logger.LogDebug(e.ToString());
                            }
                            catch (BadImageFormatException e)
                            {
                                _logger.LogDebug(TraceMessages.IgnoringLibraryNotDotNetImage, libPath.FullName);
                                _logger.LogDebug(e.ToString());
                            }
                            catch (FileLoadException e)
                            {
                                _logger.LogDebug(TraceMessages.IgnoringLibraryFileLoadFailed, libPath.FullName);
                                _logger.LogDebug(e.ToString());
                            }
                        }

                        // Unload context
                        pluginContext.Unload();

                        // Without collecting deterministically, some directories with lots of DLL's can
                        // eventually cause an Internal CLR error (segmentation fault).  This may still occur
                        // but this alleviates the issue.  Always use a search pattern (--find-pattern arg) to
                        // reduce number of DLL's to scan.
                        GC.Collect();
                        GC.WaitForPendingFinalizers();
                    }
                }
                else
                {
                    _logger.LogInformation(InformationMessages.LibrariesNotFoundInPath, path.FullName);
                }
            }
            else
            {
                _logger.LogError(ErrorMessages.PluginPathDoesNotExist, path.FullName);
            }

            return replacedemblyPaths;
        }

19 View Source File : App.cs
License : MIT License
Project Creator : Azure

[System.Diagnostics.Codereplacedysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "Converting to return code for command line.")]
        public async Task<int> RunAsync(CancellationToken token)
        {
            // Merge configuration
            _options.MergeConfig();

            // Set defaults if no value set in config or command line
            _options.ApplyDefaults();

            // Validate options
            if (!ValidateOptions(_options))
            {
                return await Task.FromResult(ReturnCodeConstants.ArgsError).ConfigureAwait(false);
            }

            // Set logging level
            SetLogLevel(_options);

            // Set options
            SetOptions(_options);

            // Print options
            _options.PrintOptions();

            // The model and stage runners may contain types that are not loaded into the default replacedembly load context
            // because they are types used by a plugin that populated the model.  Try and resolve any unresolved replacedemblies
            // with the plugin host instead when the runner is executed.  This particularly affects XmlSerializer where
            // it generates a custom serialization replacedembly that is always loaded into the default replacedembly load context.
            replacedemblyLoadContext.Default.Resolving += ResolvereplacedemblyHandler;

            try
            {
                // Build runner
                var runner = BuildRunner();
                if (runner != null)
                {
                    try
                    {
                        // Run app
                        await runner.RunAsync(token).ConfigureAwait(false);

                        // Save model (if required)
                        SaveModel(runner);

                        // Print out execution stats
                        PrintExecutionStats(runner.RunState);
                    }
                    catch (OperationCanceledException)
                    {
                        _logger.LogInformation(InformationMessages.RunnerCancelled);
                        return await Task.FromResult(ReturnCodeConstants.Cancelled).ConfigureAwait(false);
                    }
                    catch (RunnerException e)
                    {
                        if (_logger.IsEnabled(LogLevel.Debug))
                        {
                            _logger.LogError(e, ErrorMessages.FullExceptionDetails);
                        }

                        return await Task.FromResult(ReturnCodeConstants.AppError).ConfigureAwait(false);
                    }
                    catch (Exception e)
                    {
                        if (_logger.IsEnabled(LogLevel.Debug))
                        {
                            _logger.LogError(e, ErrorMessages.FullExceptionDetails);
                        }

                        return await Task.FromResult(ReturnCodeConstants.AppError).ConfigureAwait(false);
                    }

                    return await Task.FromResult(ReturnCodeConstants.Success).ConfigureAwait(false);
                }
                else
                {
                    // Nothing to run
                    return await Task.FromResult(ReturnCodeConstants.Success).ConfigureAwait(false);
                }
            }
            catch (Exception e)
            {
                _logger.LogError(ErrorMessages.FailedBuildingRunner, e.Message);

                if (_logger.IsEnabled(LogLevel.Debug))
                {
                    _logger.LogError(e, ErrorMessages.FullExceptionDetails);
                }

                return await Task.FromResult(ReturnCodeConstants.AppError).ConfigureAwait(false);
            }
            finally
            {
                // Unhook from event
                replacedemblyLoadContext.Default.Resolving -= ResolvereplacedemblyHandler;
            }
        }

19 View Source File : BizTalkConverterBase.cs
License : MIT License
Project Creator : Azure

public async Task ConvertAsync(CancellationToken token)
        {
            _logger.LogInformation(InformationMessages.RunningBizTalkConverter, Name);

            await ConvertInternalAsync(token).ConfigureAwait(false);
        }

19 View Source File : AssessCommandBuilder.cs
License : MIT License
Project Creator : Azure

public Command Build()
        {
            // Create command
            var command = new Command(OptionsResources.replacedessVerb, OptionsResources.replacedessVerbDescription);

            // Add options (switches)
            var outputModelAliases = new string[] { OptionsResources.OutputModelPathShort, OptionsResources.OutputModelPathLong };
            var outputModelOption = new Option<string>(outputModelAliases, OptionsResources.OutputModelPathDescription);
            command.AddOption(outputModelOption);

            var templateConfigDirAliases = new string[] { OptionsResources.TemplateConfigPathOptionShort, OptionsResources.TemplateConfigPathOptionLong };
            var templateConfigDirOption = new Option<DirectoryInfo>(templateConfigDirAliases, OptionsResources.TemplateConfigPathOptionDescription);
            command.AddGlobalOption(templateConfigDirOption);

            // Set handler
            command.Handler = CommandHandler.Create(async (IHost host, CancellationToken token) =>
            {
                // Get app
                var app = host.Services.GetRequiredService<IApp>();

                // Set verb
                var options = host.Services.GetRequiredService<IAppOptionsService>();
                options.Verb = CommandVerb.replacedess;

                try
                {
                    _logger.LogDebug(TraceMessages.InvokingApp, options.Verb);

                    // Invoke app
                    return await app.RunAsync(token).ConfigureAwait(false);
                }
                catch (OperationCanceledException)
                {
                    _logger.LogInformation(InformationMessages.AppCancelled);

                    return ReturnCodeConstants.Cancelled;
                }
            });

            return command;
        }

19 View Source File : ConvertCommandBuilder.cs
License : MIT License
Project Creator : Azure

public Command Build()
        {
            // Create command
            var command = new Command(OptionsResources.ConvertVerb, OptionsResources.ConvertVerbDescription);

            // Add options (switches)
            var modelAliases = new string[] { OptionsResources.ModelPathOptionShort, OptionsResources.ModelPathOptionLong };
            var modelOption = new Option<FileInfo>(modelAliases, OptionsResources.ModelPathOptionDescription)
            {
                IsRequired = true
            };
            command.AddOption(modelOption);

            var conversionDirAliases = new string[] { OptionsResources.ConversionPathOptionShort, OptionsResources.ConversionPathOptionLong };
            var conversionDirOption = new Option<string>(conversionDirAliases, OptionsResources.ConversionPathOptionDescription);
            command.AddGlobalOption(conversionDirOption);

            var templateDirAliases = new string[] { OptionsResources.TemplatePathOptionShort, OptionsResources.TemplatePathOptionLong };
            var templateDirOption = new Option<DirectoryInfo[]>(templateDirAliases, OptionsResources.TemplatePathOptionDescription);
            command.AddGlobalOption(templateDirOption);

            // Set handler
            command.Handler = CommandHandler.Create(async (IHost host, CancellationToken token) =>
            {
                // Get app
                var app = host.Services.GetRequiredService<IApp>();

                // Set verb
                var options = host.Services.GetRequiredService<IAppOptionsService>();
                options.Verb = CommandVerb.Convert;

                try
                {
                    _logger.LogDebug(TraceMessages.InvokingApp, options.Verb);

                    // Invoke app
                    return await app.RunAsync(token).ConfigureAwait(false);
                }
                catch (OperationCanceledException)
                {
                    _logger.LogInformation(InformationMessages.AppCancelled);

                    return ReturnCodeConstants.Cancelled;
                }
            });

            return command;
        }

19 View Source File : MigrateCommandBuilder.cs
License : MIT License
Project Creator : Azure

public Command Build()
        {
            // Create command
            var command = new Command(OptionsResources.MigrateVerb, OptionsResources.MigrateVerbDescription);

            // Add options (switches)
            var conversionDirAliases = new string[] { OptionsResources.ConversionPathOptionShort, OptionsResources.ConversionPathOptionLong };
            var conversionDirOption = new Option<string>(conversionDirAliases, OptionsResources.ConversionPathOptionDescription);
            command.AddGlobalOption(conversionDirOption);

            var templateConfigDirAliases = new string[] { OptionsResources.TemplateConfigPathOptionShort, OptionsResources.TemplateConfigPathOptionLong };
            var templateConfigDirOption = new Option<DirectoryInfo>(templateConfigDirAliases, OptionsResources.TemplateConfigPathOptionDescription);
            command.AddGlobalOption(templateConfigDirOption);

            var templateDirAliases = new string[] { OptionsResources.TemplatePathOptionShort, OptionsResources.TemplatePathOptionLong };
            var templateDirOption = new Option<DirectoryInfo[]>(templateDirAliases, OptionsResources.TemplatePathOptionDescription);
            command.AddGlobalOption(templateDirOption);

            // Set handler
            command.Handler = CommandHandler.Create(async (IHost host, CancellationToken token) =>
            {
                // Get app
                var app = host.Services.GetRequiredService<IApp>();

                // Set verb
                var options = host.Services.GetRequiredService<IAppOptionsService>();
                options.Verb = CommandVerb.Migrate;

                try
                {
                    _logger.LogDebug(TraceMessages.InvokingApp, options.Verb);

                    // Invoke app
                    return await app.RunAsync(token).ConfigureAwait(false);
                }
                catch (OperationCanceledException)
                {
                    _logger.LogInformation(InformationMessages.AppCancelled);

                    return ReturnCodeConstants.Cancelled;
                }
            });

            return command;
        }

19 View Source File : VerifyCommandBuilder.cs
License : MIT License
Project Creator : Azure

public Command Build()
        {
            // Create command
            var command = new Command(OptionsResources.VerifyVerb, OptionsResources.VerifyVerbDescription)
            {
                // Set handler
                Handler = CommandHandler.Create(async (IHost host, CancellationToken token) =>
                {
                    // Get app
                    var app = host.Services.GetRequiredService<IApp>();

                    // Set verb
                    var options = host.Services.GetRequiredService<IAppOptionsService>();
                    options.Verb = CommandVerb.Verify;

                    try
                    {
                        _logger.LogDebug(TraceMessages.InvokingApp, options.Verb);

                        // Invoke app
                        return await app.RunAsync(token).ConfigureAwait(false);
                    }
                    catch (OperationCanceledException)
                    {
                        _logger.LogInformation(InformationMessages.AppCancelled);

                        return ReturnCodeConstants.Cancelled;
                    }
                })
            };

            return command;
        }

19 View Source File : AppOptionsService.cs
License : MIT License
Project Creator : Azure

public void MergeConfig()
        {
            if (_config != null)
            {
                // Working path
                if (_options.Value.WorkingPath == null && !string.IsNullOrWhiteSpace(_config.WorkingPath))
                {
                    _options.Value.WorkingPath = new DirectoryInfo(_config.WorkingPath);
                }

                // State path
                if (_options.Value.StatePath == null && !string.IsNullOrWhiteSpace(_config.StatePath))
                {
                    _options.Value.StatePath = new DirectoryInfo(_config.StatePath).FullName;
                }

                // Find paths
                if (_config.FindPaths != null && _config.FindPaths.Any())
                {
                    // Merge existing paths if they exist
                    var findPaths = new List<DirectoryInfo>();
                    if (_options.Value.FindPath != null && _options.Value.FindPath.Any())
                    {
                        findPaths.AddRange(_options.Value.FindPath);
                    }

                    // Add new paths
                    findPaths.AddRange(_config.FindPaths.Where(p => !string.IsNullOrWhiteSpace(p)).Select(p => new DirectoryInfo(p)));

                    // Replace with new appended collection
                    _options.Value.FindPath = findPaths;
                }

                // Find pattern
                if (string.IsNullOrWhiteSpace(_options.Value.FindPattern) && !string.IsNullOrWhiteSpace(_config.FindPattern))
                {
                    _options.Value.FindPattern = _config.FindPattern;
                }

                // Template config path
                if (_options.Value.TemplateConfigPath == null && !string.IsNullOrWhiteSpace(_config.TemplateConfigPath))
                {
                    _options.Value.TemplateConfigPath = new DirectoryInfo(_config.TemplateConfigPath);
                }

                // Template path
                if (_config.TemplatePaths != null && _config.TemplatePaths.Any())
                {
                    // Merge existing paths if they exist
                    var templatePaths = new List<DirectoryInfo>();
                    if (_options.Value.TemplatePath != null && _options.Value.TemplatePath.Any())
                    {
                        templatePaths.AddRange(_options.Value.TemplatePath);
                    }

                    // Add new paths
                    templatePaths.AddRange(_config.TemplatePaths.Where(p => !string.IsNullOrWhiteSpace(p)).Select(p => new DirectoryInfo(p)));

                    // Replace with new appended collection
                    _options.Value.TemplatePath = templatePaths;
                }

                // Primary region
                if (!string.IsNullOrWhiteSpace(_options.Value.PrimaryRegion))
                {
                    _userProvidedPrimaryRegion = true;
                }

                if (string.IsNullOrWhiteSpace(_options.Value.PrimaryRegion) && !string.IsNullOrWhiteSpace(_config.PrimaryRegion))
                {
                    _options.Value.PrimaryRegion = _config.PrimaryRegion;
                }

                // Secondary region
                if (!string.IsNullOrWhiteSpace(_options.Value.SecondaryRegion))
                {
                    _userProvidedSecondaryRegion = true;
                }

                if (string.IsNullOrWhiteSpace(_options.Value.SecondaryRegion) && !string.IsNullOrWhiteSpace(_config.SecondaryRegion))
                {
                    _options.Value.SecondaryRegion = _config.SecondaryRegion;
                }

                // Check paired regions
                if (_userProvidedPrimaryRegion && !_userProvidedSecondaryRegion)
                {
                    var pairedRegion = _regionProvider.GetPairedRegion(_options.Value.PrimaryRegion);
                    if (pairedRegion != null && _options.Value.SecondaryRegion != pairedRegion)
                    {
                        // Secondary region not specified on command line but isn't the paired region for the primary region, replace it
                        _logger.LogInformation(InformationMessages.SecondaryRegionChangedToMatchPairedRegionOfPrimary, _options.Value.SecondaryRegion, _options.Value.PrimaryRegion, pairedRegion);

                        _options.Value.SecondaryRegion = pairedRegion;
                    }
                }

                if (!_userProvidedPrimaryRegion && _userProvidedSecondaryRegion)
                {
                    var pairedRegion = _regionProvider.GetPairedRegion(_options.Value.SecondaryRegion);
                    if (pairedRegion != null && _options.Value.PrimaryRegion != pairedRegion)
                    {
                        // Primary region not specified on command line but isn't the paired region for the secondary region, replace it
                        _logger.LogInformation(InformationMessages.PrimaryRegionChangedToMatchPairedRegionOfSecondary, _options.Value.PrimaryRegion, _options.Value.SecondaryRegion, pairedRegion);

                        _options.Value.PrimaryRegion = pairedRegion;
                    }
                }

                if (_userProvidedPrimaryRegion && _userProvidedSecondaryRegion)
                {
                    var pairedRegion = _regionProvider.GetPairedRegion(_options.Value.PrimaryRegion);
                    if (_options.Value.SecondaryRegion != pairedRegion)
                    {
                        // Secondary region is not the paired region, just output a warning in case this was not intended
                        _logger.LogWarning(WarningMessages.SecondaryRegionIsNotPairedWithPrimary, _options.Value.SecondaryRegion, _options.Value.PrimaryRegion, pairedRegion);
                    }
                }
            }
        }

19 View Source File : PluginHost.cs
License : MIT License
Project Creator : Azure

public void LoadPlugins(IEnumerable<string> replacedemblyPaths, Type[] sharedTypes)
        {
            _ = replacedemblyPaths ?? throw new ArgumentNullException(nameof(replacedemblyPaths));

            // Create a plugin context per replacedembly (in case any weird dependent replacedembly version requirements)
            foreach (var replacedemblyPath in replacedemblyPaths)
            {
                var replacedemblyFile = new FileInfo(replacedemblyPath);

                // Don't scan the library containing the plugin type itself into the replacedemblyLoadContext,
                // otherwise the IsreplacedignableFrom won't return a match, because the same replacedembly in different
                // contexts have types that are not the same as each other when comparing in .NET Core.
                if (replacedemblyFile.Name != new FileInfo(typeof(TPlugin).replacedembly.Location).Name)
                {
                    var pluginPath = replacedemblyFile.Directory.FullName;

                    // Find context if one already exists for this path
                    if (!_pluginContexts.TryGetValue(pluginPath, out var pluginContext))
                    {
                        _logger.LogDebug(TraceMessages.CreatingNewPluginreplacedemblyLoadContext, pluginPath);

                        // Create plugin replacedembly load context to hold the replacedembly (with shared types).
                        // NOTE: This has to be a non-collectible replacedemblyLoadContext because of a bug in .NET Core 3
                        // due to the use of XmlSerializer in a collectible context which creates a dynamic replacedembly
                        // and puts it in the default context.  This will be fixed in .NET 5 timeframe.
                        // https://github.com/dotnet/runtime/issues/1388
                        pluginContext = new PluginreplacedemblyLoadContext(replacedemblyFile.FullName, sharedTypes, false);

                        // Save context
                        _pluginContexts.Add(pluginPath, pluginContext);
                    }

                    // Has it already been loaded?
                    if (!_plugins.ContainsKey(replacedemblyPath))
                    {
                        _logger.LogDebug(TraceMessages.LoadingPluginreplacedembly, typeof(TPlugin).Name, replacedemblyPath);

                        var plugins = new List<TPlugin>();

                        // Load replacedembly from the path (will put it into the new context)
                        var replacedembly = ((PluginreplacedemblyLoadContext)pluginContext).LoadFromreplacedemblyPath(replacedemblyPath);

                        foreach (var type in replacedembly.GetExportedTypes().Where(t => !t.IsAbstract))
                        {
                            var interfaceType = typeof(TPlugin);
                            if (interfaceType.IsreplacedignableFrom(type))
                            {
                                _logger.LogDebug(TraceMessages.LoadingPluginFromType, type.FullName);

                                // Create instance of plugin
                                plugins.Add(GetPlugin(type));
                            }
                        }

                        _plugins.Add(replacedemblyPath, plugins);
                    }
                    else
                    {
                        _logger.LogDebug(TraceMessages.PluginreplacedemblyAlreadyLoaded, replacedemblyPath);
                    }
                }
            }

            _logger.LogInformation(InformationMessages.LoadedPlugins, _plugins.Values.SelectMany(p => p).Count());
        }

19 View Source File : PluginModelComponentProvider.cs
License : MIT License
Project Creator : Azure

public IApplicationModelProvider FindModelProvider()
        {
            _logger.LogInformation(InformationMessages.FindingModelProvider);

            if (_options.FindPath != null && _options.FindPath.Any())
            {
                FileInfo providerreplacedembly = null;

                foreach (var path in _options.FindPath)
                {
                    // Find plugin replacedembly locations
                    var replacedemblies = _pluginFinder.FindPluginreplacedemblies(path.FullName, _sharedTypes);

                    // Remove duplicates (based on filename, without path), if any
                    var distinctreplacedemblies = replacedemblies.Select(a => new FileInfo(a)).GroupBy(f => f.Name).Select(f => f.First());

                    if (distinctreplacedemblies.Any())
                    {
                        _logger.LogInformation(InformationMessages.replacedemblyCountInPath, distinctreplacedemblies.Count(), path.FullName);

                        // There should be only one, so break after the first one found
                        providerreplacedembly = distinctreplacedemblies.First();
                        break;
                    }
                    else
                    {
                        _logger.LogDebug(TraceMessages.ModelProviderreplacedemblyNotFoundInPath, path.FullName);
                    }
                }

                if (providerreplacedembly != null)
                {
                    // Load provider into separate plugin host
                    _pluginHost.LoadPlugins(new string[1] { providerreplacedembly.FullName }, _sharedTypes);

                    return _pluginHost.GetPlugins().Where(p => p is IApplicationModelProvider).Select(p => (IApplicationModelProvider)p).First();
                }
                else
                {
                    _logger.LogWarning(WarningMessages.ModelProviderreplacedemblyNotFound);
                }
            }

            return null;
        }

19 View Source File : PluginStageComponentProvider.cs
License : MIT License
Project Creator : Azure

public IEnumerable<IStageRunner> FindComponents(IRunnerConfiguration config)
        {
            _logger.LogInformation(InformationMessages.FindingStageRunners);

            if (_options.FindPath != null && _options.FindPath.Any())
            {
                var stageRunnerreplacedemblies = new List<FileInfo>();

                foreach (var path in _options.FindPath)
                {
                    // Find plugin replacedembly locations
                    var replacedemblies = _pluginFinder.FindPluginreplacedemblies(path.FullName, _sharedTypes);

                    // Remove duplicates (based on filename, without path), if any
                    var distinctreplacedemblies = replacedemblies.Select(a => new FileInfo(a)).GroupBy(f => f.Name).Select(f => f.First());

                    if (distinctreplacedemblies.Any())
                    {
                        _logger.LogInformation(InformationMessages.replacedemblyCountInPath, distinctreplacedemblies.Count(), path.FullName);

                        foreach (var replacedembly in distinctreplacedemblies)
                        {
                            stageRunnerreplacedemblies.Add(replacedembly);
                        }
                    }
                    else
                    {
                        _logger.LogDebug(TraceMessages.StageRunnerreplacedembliesNotFoundInPath, path.FullName);
                    }
                }

                if (stageRunnerreplacedemblies.Count > 0)
                {
                    // Load stage runners into separate plugin host
                    var distinctStageRunnerreplacedemblies = stageRunnerreplacedemblies.GroupBy(f => f.Name).Select(f => f.First().FullName);
                    _pluginHost.LoadPlugins(distinctStageRunnerreplacedemblies, _sharedTypes);

                    return _pluginHost.GetPlugins().Where(p => p is IStageRunner).Select(p => (IStageRunner)p);
                }
                else
                {
                    _logger.LogWarning(WarningMessages.StageRunnerreplacedembliesNotFound);
                }
            }

            return Enumerable.Empty<IStageRunner>();
        }

19 View Source File : App.cs
License : MIT License
Project Creator : Azure

[System.Diagnostics.Codereplacedysis.SuppressMessage("Design", "CA1031:Do not catch general exception types", Justification = "Converting to return code for command line.")]
        private IRunner BuildRunner()
        {
            // Build runner
            IRunnerBuilder runnerBuilder = null;
            switch (_options.Verb)
            {
                case CommandVerb.replacedess:

                    _logger.LogInformation(InformationMessages.Runningreplacedessment);

                    runnerBuilder = _builder
                        .DisableStage(Stages.Convert)
                        .DisableStage(Stages.Verify);

                    break;

                case CommandVerb.Migrate:

                    _logger.LogInformation(InformationMessages.RunningMigration);

                    runnerBuilder = _builder;

                    break;

                case CommandVerb.Convert:

                    _logger.LogInformation(InformationMessages.RunningConversion);

                    runnerBuilder = _builder
                        .DisableStage(Stages.Discover)
                        .DisableStage(Stages.Parse)
                        .DisableStage(Stages.replacedyze)
                        .DisableStage(Stages.Report);

                    break;

                case CommandVerb.Verify:

                    _logger.LogInformation(InformationMessages.RunningVerification);

                    runnerBuilder = _builder
                        .DisableStage(Stages.Discover)
                        .DisableStage(Stages.Parse)
                        .DisableStage(Stages.replacedyze)
                        .DisableStage(Stages.Report)
                        .DisableStage(Stages.Convert);

                    break;
            }

            if (runnerBuilder != null)
            {
                // Enable flags and stages, if set
                runnerBuilder = _options.Options.NoAbort ? runnerBuilder : runnerBuilder.EnableFailFast();
                if (_options.Options.AbortStage != null && _options.Options.AbortStage.Any())
                {
                    foreach (var stage in _options.Options.AbortStage)
                    {
                        runnerBuilder = runnerBuilder.EnableFailStage(stage);
                    }
                }

                // Load model (if required), otherwise get model from provider
                Func<IApplicationModel> modelFunc = () =>
                {
                    IApplicationModel model = null;
                    if (_options.Verb == CommandVerb.Convert)
                    {
                        model = LoadModel();
                        if (model == null)
                        {
                            throw new ApplicationException(string.Format(CultureInfo.CurrentCulture, ErrorMessages.FailedToLoadModel, _options.Options.Model.FullName));
                        }
                    }
                    else
                    {
                        // Find model provider
                        var provider = _modelProvider.FindModelProvider();
                        if (provider == null)
                        {
                            throw new ApplicationException(ErrorMessages.FailedToFindModelProvider);
                        }
                        else
                        {
                            model = provider.GetModel();
                        }
                    }

                    return model;
                };

                // Build runner
                var runner = runnerBuilder
                    .FindStageRunners(_provider)
                    .SetLogger(_runnerLogger)
                    .SetArgs(_options.ParseArgs())
                    .SetModel(modelFunc)
                    .Build();

                // Attach event handlers if required
                if (_options.Options.SaveState)
                {
                    _logger.LogDebug(TraceMessages.SettingStageRunnerStateEventHandlers);

                    runner.BeforeStageRunner += (s, e) =>
                    {
                        var state = ((IRunner)s).RunState;
                        SaveState(BuildStatePath(_options.Options.StatePath, false, false, state), state);
                    };

                    runner.AfterStageRunner += (s, e) =>
                    {
                        var state = ((IRunner)s).RunState;
                        SaveState(BuildStatePath(_options.Options.StatePath, true, false, state), state);
                    };
                }

                if (_options.Options.SaveStageState)
                {
                    _logger.LogDebug(TraceMessages.SettingStageStateEventHandlers);

                    runner.BeforeStage += (s, e) =>
                    {
                        var state = ((IRunner)s).RunState;
                        SaveState(BuildStatePath(_options.Options.StatePath, false, true, state), state);
                    };

                    runner.AfterStage += (s, e) =>
                    {
                        var state = ((IRunner)s).RunState;
                        SaveState(BuildStatePath(_options.Options.StatePath, true, true, state), state);
                    };
                }

                return runner;
            }
            else
            {
                return null;
            }
        }

See More Examples