public ParameterEmitBody(DependencyProvider dependencyProvider) { _dependencyProvider = dependencyProvider; }
/// <summary> /// Cleans up and removes stale workload packs. /// </summary> public void GarbageCollectInstalledWorkloadPacks(DirectoryPath?offlineCache = null) { try { ReportPendingReboot(); Log?.LogMessage("Starting garbage collection."); IEnumerable <SdkFeatureBand> installedFeatureBands = GetInstalledFeatureBands(); IEnumerable <WorkloadId> installedWorkloads = RecordRepository.GetInstalledWorkloads(_sdkFeatureBand); IEnumerable <PackInfo> expectedWorkloadPacks = installedWorkloads .SelectMany(workload => _workloadResolver.GetPacksInWorkload(workload)) .Select(pack => _workloadResolver.TryGetPackInfo(pack)) .Where(pack => pack != null); IEnumerable <WorkloadPackId> expectedPackIds = expectedWorkloadPacks.Select(p => p.Id); foreach (PackInfo expectedPack in expectedWorkloadPacks) { Log?.LogMessage($"Expected workload pack, ID: {expectedPack.ResolvedPackageId}, version: {expectedPack.Version}."); } foreach (SdkFeatureBand installedFeatureBand in installedFeatureBands) { Log?.LogMessage($"Installed feature band: {installedFeatureBand}"); } IEnumerable <WorkloadPackRecord> installedWorkloadPacks = WorkloadPackRecords.Values.SelectMany(r => r); List <WorkloadPackRecord> packsToRemove = new List <WorkloadPackRecord>(); // We first need to clean up the dependents and then do a pass at removing them. Querying the installed packs // is effectively a table scan of the registry to make sure we have accurate information and there's a // potential perf hit for both memory and speed when enumerating large sets of registry entries. foreach (WorkloadPackRecord packRecord in installedWorkloadPacks) { DependencyProvider depProvider = new DependencyProvider(packRecord.ProviderKeyName); // Find all the dependents that look like they belong to SDKs. We only care // about dependents that match the SDK host we're running under. For example, an x86 SDK should not be // modifying the x64 MSI dependents. IEnumerable <string> sdkDependents = depProvider.Dependents .Where(d => d.StartsWith($"{DependentPrefix}")) .Where(d => d.EndsWith($",{HostArchitecture}")); foreach (string dependent in sdkDependents) { Log?.LogMessage($"Evaluating dependent for workload pack, dependent: {dependent}, pack ID: {packRecord.PackId}, pack version: {packRecord.PackVersion}"); // Dependents created by the SDK should have 3 parts, for example, "Microsoft.NET.Sdk,6.0.100,x86". string[] dependentParts = dependent.Split(','); if (dependentParts.Length != 3) { Log?.LogMessage($"Skipping dependent: {dependent}"); continue; } try { SdkFeatureBand dependentFeatureBand = new SdkFeatureBand(dependentParts[1]); if (!installedFeatureBands.Contains(dependentFeatureBand)) { Log?.LogMessage($"Removing dependent '{dependent}' from provider key '{depProvider.ProviderKeyName}' because its SDK feature band does not match any installed feature bands."); UpdateDependent(InstallRequestType.RemoveDependent, depProvider.ProviderKeyName, dependent); } if (dependentFeatureBand.Equals(_sdkFeatureBand)) { // If the current SDK feature band is listed as a dependent, we can validate // the workload pack against the expected pack IDs and versions to potentially remove it. if (!expectedWorkloadPacks.Where(p => packRecord.PackId.ToString().Equals(p.ResolvedPackageId)) .Where(p => p.Version.Equals(packRecord.PackVersion.ToString())).Any()) { Log?.LogMessage($"Removing dependent '{dependent}' because the pack record does not match any expected packs."); UpdateDependent(InstallRequestType.RemoveDependent, depProvider.ProviderKeyName, dependent); } } } catch (Exception e) { Log?.LogMessage($"{e.Message}"); Log?.LogMessage($"{e.StackTrace}"); continue; } } // Recheck the registry to see if there are any remaining dependents. If not, we can // remove the workload pack. We'll add it to the list and remove the packs at the end. IEnumerable <string> remainingDependents = depProvider.Dependents; if (remainingDependents.Any()) { Log?.LogMessage($"{packRecord.PackId} ({packRecord.PackVersion}) will not be removed because other dependents remain: {string.Join(", ", remainingDependents)}."); } else { packsToRemove.Add(packRecord); } } foreach (WorkloadPackRecord record in packsToRemove) { // We need to make sure the product is actually installed and that we're not dealing with an orphaned record, e.g. // if a previous removal was interrupted. We can't safely clean up orphaned records because it's too expensive // to query all installed components and determine the product codes associated with the component that // created the record. DetectState state = DetectPackage(record.ProductCode, out Version _); if (state == DetectState.Present) { // Manually construct the MSI payload package details string id = $"{record.PackId}.Msi.{HostArchitecture}"; MsiPayload msi = GetCachedMsiPayload(id, record.PackVersion.ToString(), offlineCache); // Make sure the package we have in the cache matches with the record. If it doesn't, we'll do the uninstall // the hard way if (!string.Equals(record.ProductCode, msi.ProductCode, StringComparison.OrdinalIgnoreCase)) { Log?.LogMessage($"ProductCode mismatch! Cached package: {msi.ProductCode}, pack record: {record.ProductCode}."); string logFile = GetMsiLogName(record, InstallAction.Uninstall); uint error = ExecuteWithProgress(String.Format(LocalizableStrings.MsiProgressUninstall, id), () => UninstallMsi(record.ProductCode, logFile)); ExitOnError(error, $"Failed to uninstall {msi.MsiPath}."); } else { // No need to plan. We know that there are no other dependents, the MSI is installed and we // want to remove it. VerifyPackage(msi); ExecutePackage(msi, InstallAction.Uninstall); } } } } catch (Exception e) { LogException(e); throw; } }
public EditFolderMapping() { _navigationManager = DependencyProvider.GetRequiredService <INavigationManager>(); }
public Membership() { _navigationManager = DependencyProvider.GetRequiredService <INavigationManager>(); }
public View() { controller = new Factory().DigitalAssetsController; _navigationManager = DependencyProvider.GetRequiredService <INavigationManager>(); }
public Purchase() { _navigationManager = DependencyProvider.GetRequiredService <INavigationManager>(); }
static async Task <int> Main() { AppDomain currentDomain = AppDomain.CurrentDomain; currentDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledExceptionHandler); LogManager.Configuration.Variables["fileName"] = $"{appId}-{DateTime.UtcNow.ToString("ddMMyyyy")}.log"; LogManager.Configuration.Variables["archiveFileName"] = $"{appId}-{DateTime.UtcNow.ToString("ddMMyyyy")}.log"; var cfgBuilder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile($"appsettings.{appId}.json"); var configuration = cfgBuilder.Build(); var app = configuration.Get <App>(); try { var servicesProvider = DependencyProvider.Get(app); var jobFactory = new JobFactory(servicesProvider); _schedulerFactory = new StdSchedulerFactory(); _scheduler = await _schedulerFactory.GetScheduler(); _scheduler.JobFactory = jobFactory; await _scheduler.Start(); #region Buy Deep Sell High IJobDetail bdshJob = JobBuilder.Create <BuyDeepSellHighJob>() .WithIdentity("BuyDeepSellHighJob") .Build(); bdshJob.JobDataMap["FileName"] = app.FileName; bdshJob.JobDataMap["Version"] = app.Version; bdshJob.JobDataMap["ApiKey"] = app.Exchange.ApiKey; bdshJob.JobDataMap["ApiSecret"] = app.Exchange.ApiSecret; bdshJob.JobDataMap["PassPhrase"] = app.Exchange.PassPhrase; bdshJob.JobDataMap["ExchangeType"] = app.Exchange.Type; var bdshBuilder = TriggerBuilder.Create() .WithIdentity("BuyDeepSellHighJobTrigger") .StartNow(); bdshBuilder.WithSimpleSchedule(x => x .WithIntervalInMinutes(app.IntervalInMinutes) .RepeatForever()); var bdshTrigger = bdshBuilder.Build(); #endregion await _scheduler.ScheduleJob(bdshJob, bdshTrigger); await Task.Delay(TimeSpan.FromSeconds(30)); Console.Read(); } catch (SchedulerException ex) { Logger.Fatal($"{ex.Message}"); } LogManager.Shutdown(); return(0); }
public HtmlModule() { _navigationManager = DependencyProvider.GetRequiredService <INavigationManager>(); }
public override bool CanSupplyValueFor(DependencyProvider provider) { return(false); }
public PasswordReset() { _navigationManager = DependencyProvider.GetRequiredService <INavigationManager>(); }
public PackageRestoreContext() { _dependencies = new DependencyProvider(AssemblyProbingPaths, NativeProbingRoots); AppDomain.CurrentDomain.AssemblyLoad += OnAssemblyLoad; }
public OrderServiceTest() { _orderService = DependencyProvider.CreateOrderService(); }
/// <summary> /// Kiểm tra phân quyền của user đang truy cập /// </summary> /// <param name="context"></param> /// <param name="user"></param> /// <returns></returns> private bool CheckPermission(ActionExecutingContext context, SysUser user) { if (user.RoleId == null) { context.Result = GetResultError("User chưa được phân quyền.", HttpStatusCode.Unauthorized); return(false); } string fnCd = IsRequestAPI(context) ? Convert.ToString(((dynamic)context.ActionArguments["action"]).FnCd) : context.HttpContext.Request.Query["fnCode"].ToString(); if (string.IsNullOrEmpty(fnCd)) { context.Result = GetResultError("Không tìm thấy thông tin FnCd.", HttpStatusCode.BadRequest); return(false); } IRepository <SysPermission> repoPermis = DependencyProvider.Resolve <IRepository <SysPermission> >(); var permisRecord = repoPermis.FindOne(x => x.RoleId.Equals(user.RoleId.Value) && x.FnCd.Equals(fnCd)); if (!IsRequestAPI(context)) { if (permisRecord == null || !permisRecord.View) { context.Result = GetResultError("Bạn không có quyền truy cập trang này !", HttpStatusCode.Unauthorized); return(false); } return(true); } var attrs = context.ActionArguments["action"].GetType().GetCustomAttributes(typeof(PermisOption), false); IList <string> permisTypes; if (attrs.Count() == 0) { permisTypes = new List <string>(); string actionName = context.ActionArguments["action"].GetType().Name; if (actionName.StartsWith("Get")) { permisTypes.Add("View"); } else if (actionName.StartsWith("Update") || actionName.StartsWith("Edit")) { permisTypes.Add("Update"); } else if (actionName.StartsWith("Insert") || actionName.StartsWith("Create")) { permisTypes.Add("Insert"); } else if (actionName.StartsWith("Remove") || actionName.StartsWith("Delete")) { permisTypes.Add("Remove"); } else if (actionName.StartsWith("Import")) { permisTypes.Add("Import"); } else if (actionName.StartsWith("Export")) { permisTypes.Add("Export"); } else { context.Result = GetResultError("Action này chưa được phân quyền", HttpStatusCode.Unauthorized); return(false); } } else { permisTypes = ((PermisOption)attrs[0]).PermisTypes; } if (permisTypes.Count == 0) { throw new Exception("Exist apply attribute PermisOption but not value"); } if (permisTypes.Any(x => x.Equals("*"))) { return(true); } if (permisRecord == null) { context.Result = GetResultError("Không tìm thấy thông tin phân quyền với FnCd này.", HttpStatusCode.Unauthorized); return(false); } foreach (var type in permisTypes) { var permisValue = ObjectHelper.GetValue(type, permisRecord); if (permisValue == null || (bool)permisValue == false) { context.Result = GetResultError("Bạn không có quyền truy cập action này !", HttpStatusCode.Unauthorized); return(false); } } return(true); }
static async Task <int> Main() { var cancellationTokenSource = new CancellationTokenSource(); AppDomain currentDomain = AppDomain.CurrentDomain; currentDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledExceptionHandler); AppDomain.CurrentDomain.ProcessExit += (s, e) => cancellationTokenSource.Cancel(); Console.CancelKeyPress += (s, e) => cancellationTokenSource.Cancel(); LogManager.Configuration.Variables["fileName"] = $"{appId}-{DateTime.UtcNow:ddMMyyyy}.log"; LogManager.Configuration.Variables["archiveFileName"] = $"{appId}-{DateTime.UtcNow:ddMMyyyy}.log"; var cfgBuilder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile($"appsettings.{appId}.json"); var configuration = cfgBuilder.Build(); var app = configuration.Get <AgentApp>(); try { var servicesProvider = DependencyProvider.Get(app); var jobFactory = new JobFactory(servicesProvider); _schedulerFactory = new StdSchedulerFactory(); _scheduler = await _schedulerFactory.GetScheduler(); _scheduler.JobFactory = jobFactory; await _scheduler.Start(); #region Fetch Data Uniswap var fdfu = app.Jobs.FirstOrDefault(j => j.Name == "j-fetch-data-from-uniswap"); var fdfuJob = JobBuilder.Create <FetchDataFromUniswapJob>() .WithIdentity($"{fdfu.Name}Job") .Build(); fdfuJob.JobDataMap["FileName"] = fdfu.Name; fdfuJob.JobDataMap["StoragePath"] = app.StoragePath; var fdfuBuilder = TriggerBuilder.Create() .WithIdentity($"{fdfu.Name}Trigger") .StartNow(); fdfuBuilder.WithSimpleSchedule(x => x .WithIntervalInMinutes(fdfu.IntervalInMinutes) .RepeatForever()); var fdfuTrigger = fdfuBuilder.Build(); #endregion #region Fetch Data Kyber var fdfk = app.Jobs.FirstOrDefault(j => j.Name == "j-fetch-data-from-kyber"); var fdfkJob = JobBuilder.Create <FetchDataFromKyberJob>() .WithIdentity($"{fdfk.Name}Job") .Build(); fdfkJob.JobDataMap["FileName"] = fdfk.Name; fdfkJob.JobDataMap["StoragePath"] = app.StoragePath; var fdfkBuilder = TriggerBuilder.Create() .WithIdentity($"{fdfk.Name}Trigger") .StartNow(); fdfkBuilder.WithSimpleSchedule(x => x .WithIntervalInMinutes(fdfk.IntervalInMinutes) .RepeatForever()); var fdfkTrigger = fdfkBuilder.Build(); #endregion #region Send Summary var ss = app.Jobs.FirstOrDefault(j => j.Name == "j-send-summary"); var ssJob = JobBuilder.Create <SendSummaryJob>() .WithIdentity($"{ss.Name}Job") .Build(); ssJob.JobDataMap["FileName"] = ss.Name; ssJob.JobDataMap["StoragePath"] = app.StoragePath; ssJob.JobDataMap["Interval"] = ss.IntervalInMinutes; var ssBuilder = TriggerBuilder.Create() .WithIdentity($"{ss.Name}Trigger") .StartNow(); ssBuilder.WithSimpleSchedule(x => x .WithIntervalInMinutes(ss.IntervalInMinutes) .RepeatForever()); var ssTrigger = ssBuilder.Build(); #endregion if (fdfu.IsActive) { await _scheduler.ScheduleJob(fdfuJob, fdfuTrigger); } if (fdfk.IsActive) { await _scheduler.ScheduleJob(fdfkJob, fdfkTrigger); } if (ss.IsActive) { await _scheduler.ScheduleJob(ssJob, ssTrigger); } await Task.Delay(TimeSpan.FromSeconds(30)); await Task.Delay(-1, cancellationTokenSource.Token).ContinueWith(t => { }); } catch (SchedulerException ex) { Logger.Fatal($"{ex.GetFullMessage()}"); } LogManager.Shutdown(); return(0); }
private void HandlePreDestroy(DependencyProvider dp, object obj) { dp.PostApply -= HandlePreDestroy; RemoveSingleton (_dependencyMappingIds [dp]); _dependencyMappingIds.Remove (dp); }
public override bool CanSupplyValueFor(DependencyProvider provider) { Requires.NotNull(provider, "provider"); return(false); }
public ModuleSettingsPage() { _navigationManager = DependencyProvider.GetRequiredService <INavigationManager>(); }
internal protected override DependencyProvider CreateDependencyProvider(ObjectDescription description, ParameterInfo paramInfo, bool strongTyped) { return(strongTyped ? DependencyProvider.CreateAutowiredDependencyProvider <TParam>(new ParameterInjectionTargetInfo(paramInfo, description)) : DependencyProvider.CreateAutowiredDependencyProvider(new ParameterInjectionTargetInfo(paramInfo, description))); }
public static void Main(string[] args) { var app = new CommandLineApplication(false) { Name = "Coalesce" }; app.HelpOption("-h|--help"); var dataContextClass = app.Option("-dc|--dataContext", "Data Context containing the classes to scaffold", CommandOptionType.SingleValue); var force = app.Option("-f|--force", "Use this option to overwrite existing files", CommandOptionType.SingleValue); var relativeFolderPath = app.Option("-outDir|--relativeFolderPath", "Specify the relative output folder path from project where the file needs to be generated, if not specified, file will be generated in the project folder", CommandOptionType.SingleValue); var onlyGenerateFiles = app.Option("-filesOnly|--onlyGenerateFiles", "Will only generate the file output and will not restore any of the packages", CommandOptionType.SingleValue); var validateOnly = app.Option("-vo|--validateOnly", "Validates the model but does not generate the models", CommandOptionType.SingleValue); var area = app.Option("-a|--area", "The area where the generated/scaffolded code should be placed", CommandOptionType.SingleValue); var module = app.Option("-m|--module", "The prefix to apply to the module name of the generated typescript files", CommandOptionType.SingleValue); var webProject = app.Option("-wp|--webproject", "Relative path to the web project; if empty will search up from current folder for first project.json", CommandOptionType.SingleValue); var dataProject = app.Option("-dp|--dataproject", "Relative path to the data project", CommandOptionType.SingleValue); var targetNamespace = app.Option("-ns|--namespace", "Target Namespace for the generated code", CommandOptionType.SingleValue); app.OnExecute(async() => { var model = new CommandLineGeneratorModel { DataContextClass = dataContextClass.Value() ?? "", Force = force.Value() != null && force.Value().ToLower() == "true", RelativeFolderPath = relativeFolderPath.Value() ?? "", OnlyGenerateFiles = onlyGenerateFiles.Value() != null && onlyGenerateFiles.Value().ToLower() == "true", ValidateOnly = validateOnly.Value() != null && validateOnly.Value().ToLower() == "true", AreaLocation = area.Value() ?? "", TypescriptModulePrefix = module.Value() ?? "", TargetNamespace = targetNamespace.Value() ?? "" }; // Find the web project ProjectContext webContext = DependencyProvider.ProjectContext(webProject.Value()); if (webContext == null) { throw new ArgumentException("Web project or target namespace was not found."); } // Find the data project ProjectContext dataContext = DependencyProvider.ProjectContext(dataProject.Value()); if (dataContext == null) { throw new ArgumentException("Data project was not found."); } Console.WriteLine(""); CommandLineGenerator generator = new CommandLineGenerator(webContext, dataContext); await generator.GenerateCode(model); return(0); }); try { app.Execute(args); } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); if (ex.InnerException != null) { Console.WriteLine(ex.InnerException.Message); Console.WriteLine(ex.InnerException.StackTrace); } } }
public override bool CanSupplyValueFor(DependencyProvider provider) { Requires.NotNull(provider, "provider"); return(_paramName.Equals(provider.TargetName) && provider.TargetType.IsAssignableFrom(ParameterType)); }
public GroupsModuleBase() { NavigationManager = DependencyProvider.GetRequiredService <INavigationManager>(); }
internal protected override DependencyProvider CreateDependencyProvider(ObjectDescription description, ParameterInfo paramInfo, bool strongTyped) { return(strongTyped ? DependencyProvider.CreateStrongConstantParameterProvider(MyParamValue, paramInfo) : DependencyProvider.CreateWeakConstantParameterProvider(MyParamValue, paramInfo)); }
public EmitParameterMerger(DependencyProvider[] dependencyProviders) { VerfiyConstructorParameterLength(dependencyProviders, 1); _depProvider0 = (DependencyProvider <T0>)dependencyProviders[0]; }
/// <summary> /// Determines whether this parameter can supply value for the injection target represented by the specified injectionInfo. /// </summary> /// <param name="provider">The provider.</param> /// <returns> /// <c>true</c> if this parameter can supply value for the injection target represented by the specified injectionInfo; otherwise, <c>false</c>. /// </returns> /// <remarks> /// Should we use the parameter value provided with this instance at the time of resolution, when the injection target already /// has default parameter value out there? /// </remarks> public abstract bool CanSupplyValueFor(DependencyProvider provider);
public void InstallWorkloadManifest(ManifestId manifestId, ManifestVersion manifestVersion, SdkFeatureBand sdkFeatureBand, DirectoryPath?offlineCache = null, bool isRollback = false) { try { ReportPendingReboot(); // Rolling back a manifest update after a successful install is essentially a downgrade, which is blocked so we have to // treat it as a special case and is different from the install failing and rolling that back, though depending where the install // failed, it may have removed the old product already. Log?.LogMessage($"Installing manifest: Id: {manifestId}, version: {manifestVersion}, feature band: {sdkFeatureBand}, rollback: {isRollback}."); // Resolve the package ID for the manifest payload package string msiPackageId = WorkloadManifestUpdater.GetManifestPackageId(sdkFeatureBand, manifestId, InstallType.Msi).ToString(); string msiPackageVersion = $"{manifestVersion}"; Log?.LogMessage($"Resolving {manifestId} ({manifestVersion}) to {msiPackageId} ({msiPackageVersion})."); // Retrieve the payload from the MSI package cache. MsiPayload msi = GetCachedMsiPayload(msiPackageId, msiPackageVersion, offlineCache); VerifyPackage(msi); DetectState state = DetectPackage(msi.ProductCode, out Version installedVersion); InstallAction plannedAction = PlanPackage(msi, state, InstallAction.Install, installedVersion, out IEnumerable <string> relatedProducts); // If we've detected a downgrade, it's possible we might be doing a rollback after the manifests were updated, // but another error occurred. In this case we need to try and uninstall the upgrade and then install the lower // version of the MSI. The downgrade can also be a deliberate rollback. if (plannedAction == InstallAction.Downgrade && isRollback && state == DetectState.Absent) { Log?.LogMessage($"Rolling back manifest update."); // The provider keys for manifest packages are stable across feature bands so we retain dependents during upgrades. DependencyProvider depProvider = new DependencyProvider(msi.Manifest.ProviderKeyName); // Try and remove the SDK dependency, but ignore any remaining dependencies since // we want to force the removal of the old version. The remaining dependencies and the provider // key won't be removed. UpdateDependent(InstallRequestType.RemoveDependent, msi.Manifest.ProviderKeyName, _dependent); // Since we don't have records for manifests, we need to try and retrieve the ProductCode of // the newer MSI that's installed that we want to remove using its dependency provider. string productCode = depProvider.ProductCode; if (string.IsNullOrWhiteSpace(productCode)) { // We don't know the MSI package that wrote this provider key, so if the ProductCode is missing // we can't do anything else. Log?.LogMessage($"Failed to retrieve the ProductCode for provider: {depProvider.ProviderKeyName}."); return; } Log?.LogMessage($"Found ProductCode {productCode} registered against provider, {depProvider.ProviderKeyName}."); // This is a best effort. If for some reason the manifest installers were fixed, for example, manually // adding additional upgrade paths to work around previous faulty authoring, we may have multiple related // products. The best we can do is to check for at least one match and remove it and then try the rollback. if (!relatedProducts.Contains(productCode, StringComparer.OrdinalIgnoreCase)) { Log?.LogMessage($"Cannot rollback manifest. ProductCode does not match any detected related products."); return; } string logFile = GetMsiLogName(productCode, InstallAction.Uninstall); uint error = UninstallMsi(productCode, logFile, ignoreDependencies: true); ExitOnError(error, "Failed to uninstall manifest package."); // Detect the package again and fall through to the original execution. If that fails, then there's nothing // we could have done. Log?.LogMessage("Replanning manifest package."); state = DetectPackage(msi, out Version _); plannedAction = PlanPackage(msi, state, InstallAction.Install, installedVersion, out IEnumerable <string> _); } ExecutePackage(msi, plannedAction); // Update the reference count against the MSI. UpdateDependent(InstallRequestType.AddDependent, msi.Manifest.ProviderKeyName, _dependent); } catch (Exception e) { LogException(e); throw; } }
public async Task WalkAsyncAddsTransitiveCentralDependency(string centralPackageVersion, string otherVersion) { var centralPackageName = "D"; var framework = NuGetFramework.Parse("net45"); var context = new TestRemoteWalkContext(); var provider = new DependencyProvider(); // D is a transitive dependency for package A through package B -> C -> D // D is defined as a Central Package Version // In this context Package D with version centralPackageVersion will be added as inner node of Node A, next to B // Input // A -> B (version = otherVersion) -> C (version = otherVersion) -> D (version = otherVersion) // A ~> D (the version 2.0.0 or as defined by "centralPackageVersion" argument // the dependency is not direct, // it simulates the fact that there is a centrally defined "D" package // the information is added to the provider) // The expected output graph // -> B (version = otherVersion) -> C (version = otherVersion) // A // -> D (version = 2.0.0) provider.Package("A", otherVersion) .DependsOn("B", otherVersion); provider.Package("B", otherVersion) .DependsOn("C", otherVersion); provider.Package("C", otherVersion) .DependsOn(centralPackageName, otherVersion); // Simulates the existence of a D centrally defined package that is not direct dependency provider.Package("A", otherVersion) .DependsOn(centralPackageName, centralPackageVersion, LibraryDependencyTarget.Package, versionCentrallyManaged: true, libraryDependencyReferenceType: LibraryDependencyReferenceType.None); // Add central package to the source with multiple versions provider.Package(centralPackageName, "1.0.0"); provider.Package(centralPackageName, centralPackageVersion); provider.Package(centralPackageName, "3.0.0"); context.LocalLibraryProviders.Add(provider); var walker = new RemoteDependencyWalker(context); // Act var rootNode = await DoWalkAsync(walker, "A", framework); // Assert Assert.Equal(2, rootNode.InnerNodes.Count); var centralVersionInGraphNode = rootNode.InnerNodes.Where(n => n.Item.Key.Name == centralPackageName).FirstOrDefault(); Assert.NotNull(centralVersionInGraphNode); Assert.Equal(centralPackageVersion, centralVersionInGraphNode.Item.Key.Version.ToNormalizedString()); Assert.True(centralVersionInGraphNode.Item.IsCentralTransitive); var BNode = rootNode.InnerNodes.Where(n => n.Item.Key.Name == "B").FirstOrDefault(); Assert.NotNull(BNode); Assert.Equal(1, BNode.InnerNodes.Count); Assert.Equal(otherVersion, BNode.Item.Key.Version.ToNormalizedString()); Assert.False(BNode.Item.IsCentralTransitive); var CNode = BNode.InnerNodes.Where(n => n.Item.Key.Name == "C").FirstOrDefault(); Assert.NotNull(CNode); Assert.Equal(otherVersion, CNode.Item.Key.Version.ToNormalizedString()); Assert.Equal(0, CNode.InnerNodes.Count); Assert.False(CNode.Item.IsCentralTransitive); }
public ViewConsole() { _navigationManager = DependencyProvider.GetRequiredService <INavigationManager>(); }
public void ConfigureServices(IServiceCollection services) { services.AddScoped <IDependencyProvider>(x => { var d = new DependencyProvider { ServiceProvider = x }; return(d); }); services.AddHttpClient(); services.AddScoped <ISessionContext, SessionContext>(); DependencyRegistrar.RegisterDependencies(services); services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(configureOptions => { configureOptions.RequireHttpsMetadata = false; // configureOptions.SaveToken = true; // after sucesfull authentication, token to be save on the server. configureOptions.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Settings.Default.UserSecretKey)), ValidateIssuer = false, ValidateAudience = false }; configureOptions.Events = new JwtBearerEvents { OnAuthenticationFailed = context => { context.Response.Headers.Add("Unauthorized AccessException", "true"); return(System.Threading.Tasks.Task.CompletedTask); } }; }); services.AddControllers(); services.AddCors(setup => setup.AddPolicy("CorsPolicy", builder => { builder.AllowAnyOrigin() .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials(); })); services.AddMvc((opt) => { opt.Filters.Add(new TransactionFilter()); opt.Filters.Add(new DataFilter()); opt.Filters.Add(new ExceptionFilter()); }); services.AddDbContext <ApplicationDbContext>(); }
public Export() { _navigationManager = DependencyProvider.GetRequiredService <INavigationManager>(); }
public ProfileDefinitions() { _navigationManager = DependencyProvider.GetRequiredService <INavigationManager>(); }
public Register() { _navigationManager = DependencyProvider.GetRequiredService <INavigationManager>(); }
private void HandlePostApply (DependencyProvider dp, object obj) { AddSingleton (_dependencyMappingIds [dp], obj); dp.PostApply -= HandlePostApply; dp.PreDestroy += HandlePreDestroy; }