Exemplo n.º 1
0
        static App()
        {
            XmlConfigurator.Configure();
            Logger = LogManager.GetLogger("default");

            ServiceInjector.InjectServices();
        }
Exemplo n.º 2
0
        private void Initialize()
        {
            // Show the window in normal state
            WindowState = WindowState.Normal;

            ServiceInjector.InjectServices();

            _coreViewModel = new CoreViewModel();
            DataContext    = _coreViewModel;
            _coreViewModel.InitializeEnvironmentVariables();

            switch (_coreViewModel.InitResult)
            {
            case InitResultType.InitOk:
                break;

            case InitResultType.AccessDenied:
                MessageBox.Show("Cannot access Environment variables! Please restart NVM# as an Administrator.", "NVM#");
                Application.Current.Shutdown();
                break;

            case InitResultType.OtherError:
                MessageBox.Show("NVM# encountered an error and needs to close!", "NVM#");
                Application.Current.Shutdown();
                break;
            }

            UserButton.IsChecked = true;

            SizeChanged += (o, a) =>
            {
                switch (WindowState)
                {
                case WindowState.Maximized:
                    SplitViewMenu.Width = (int)SplitViewMenuWidth.Wide;
                    break;

                case WindowState.Normal:
                    SplitViewMenu.Width = (int)SplitViewMenuWidth.Narrow;
                    break;
                }

                RootGrid.ColumnDefinitions[0] = new ColumnDefinition {
                    Width = new GridLength(SplitViewMenu.Width)
                };
                RootGrid.InvalidateVisual();
            };

            // Enable the tooltip for SplitView menu buttons only if the SplitView width is narrow
            SplitViewMenu.SizeChanged += (o, a) =>
            {
                var isNarrowMenu = (int)SplitViewMenu.Width == (int)SplitViewMenuWidth.Narrow;
                ToolTipService.SetIsEnabled(UserButton, isNarrowMenu);
                ToolTipService.SetIsEnabled(SystemButton, isNarrowMenu);
                ToolTipService.SetIsEnabled(ImportButton, isNarrowMenu);
                ToolTipService.SetIsEnabled(ExportButton, isNarrowMenu);
                ToolTipService.SetIsEnabled(AboutButton, isNarrowMenu);
            };
        }
Exemplo n.º 3
0
        static App()
        {
            XmlConfigurator.Configure();
            Logger = LogManager.GetLogger("default");

            // Create service model to ensure available services
            ServiceInjector.InjectServices();
        }
Exemplo n.º 4
0
        public MainWindow()
        {
            InitializeComponent();

            ServiceInjector.InjectServices();      // Start-up services

            Loaded += MainWindow_LoadedAsync;
        }
Exemplo n.º 5
0
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            MainWindow window = new MainWindow();

            ServiceInjector.InjectServices();
            ViewModelBase mainViewModel = new MainWindowViewModel();

            window.DataContext = mainViewModel;
            window.Show();
        }
Exemplo n.º 6
0
        private async void PerformStartup(object sender, StartupEventArgs e)
        {
            var screen = new SplashScreen("Resources/Images/startup.png");

            screen.Show(false, true);

            Current.DispatcherUnhandledException += AppDispatcherUnhandledException;

            ServiceInjector.InjectServices();
            var svc = new WarlockService();

            svc.Load();
            ServiceManager.Instance.AddService <Services.Interfaces.IWarlockService>(svc);
            if (svc.Servers == null)
            {
                svc.Servers = new ObservableCollection <Server>(new[] { new Server() });
                screen.Close(TimeSpan.FromSeconds(1));
                MainWindowViewModel.Instance.ShowMainWindow();
            }
            else if (svc.Servers.Count == 0)
            {
                svc.Servers = new ObservableCollection <Server>(new[] { new Server() });
                screen.Close(TimeSpan.Zero);
                MainWindowViewModel.Instance.ShowMainWindow();
            }
            else
            {
                if (svc.Servers.Any(c => c.enabled))
                {
                    try
                    {
                        MainWindowViewModel.Instance.Status = Status.Busy;
                        await svc.StartAll().ConfigureAwait(true);

                        MainWindowViewModel.Instance.Status = Status.Ready;
                    }
                    catch (Exception ex)
                    {
                        MainWindowViewModel.Instance.Status = Status.Disabled;
                        Logging.LogUsefulException(ex);
                    }
                    screen.Close(TimeSpan.Zero);
                    MainWindowViewModel.Instance.MinimizeToTray();
                }
                else
                {
                    screen.Close(TimeSpan.Zero);
                    MainWindowViewModel.Instance.ShowMainWindow();
                }
            }
        }
Exemplo n.º 7
0
        public static void Main()
        {
            if (SingleInstance <App> .InitializeAsFirstInstance(UniqueName))
            {
                ServiceInjector.InjectServices();
                _application = new App();

                _application.InitializeComponent();
                _application.Run();

                // Allow single instance code to perform cleanup operations
                SingleInstance <App> .Cleanup();
            }
        }
Exemplo n.º 8
0
        /// <summary>
        ///     Starts the complete update process and uses the integrated user interface for user interaction.
        /// </summary>
        public async void ShowUserInterface()
        {
            if (_active)
            {
                return;
            }
            _active = true;

            ServiceInjector.InjectServices();

            var dialogService     = ServiceContainer.Instance.GetService <IDialogWindowService>();
            var messageboxService = ServiceContainer.Instance.GetService <IMessageboxService>();

            var lp = LocalizationHelper.GetLocalizationProperties(UpdateManager.LanguageCulture,
                                                                  UpdateManager.CultureFilePaths);


            try
            {
                if (!UseHiddenSearch)
                {
                    var vmUpdateSearch = new UpdateSearchViewModel(UpdateManager);
                    dialogService.ShowDialog("searchforupdates", vmUpdateSearch);

                    if (vmUpdateSearch.HasError)
                    {
                        return;
                    }

                    if (!vmUpdateSearch.UpdatesFound)
                    {
                        messageboxService.Show(lp.NoUpdateDialogInfoText, lp.NoUpdateDialogHeader,
                                               EnuMessageBoxButton.Ok,
                                               EnuMessageBoxImage.Information);
                        return;
                    }
                }
                else
                {
                    try
                    {
                        if (!await UpdateManager.SearchForUpdatesAsync())
                        {
                            return;
                        }
                    }
                    catch (Exception ex)
                    {
                        messageboxService.Show(ex.Message, lp.UpdateSearchErrorCaption, EnuMessageBoxButton.Ok,
                                               EnuMessageBoxImage.Error);
                        return;
                    }
                }

                var vmChangelog = new ChangelogViewModel(UpdateManager);
                dialogService.ShowDialog("showChangelog", vmChangelog);

                if (!vmChangelog.DialogResult)
                {
                    return;
                }

                var vmDownload = new DownloadUpdateViewModel(UpdateManager);
                dialogService.ShowDialog("downloadUpdates", vmDownload);

                if (!vmDownload.DialogResult)
                {
                    return;
                }

                bool valid;
                try
                {
                    valid = UpdateManager.ValidatePackages();
                }
                catch (FileNotFoundException)
                {
                    messageboxService.Show(lp.PackageNotFoundErrorText, lp.PackageValidityCheckErrorCaption,
                                           EnuMessageBoxButton.Ok,
                                           EnuMessageBoxImage.Error);
                    return;
                }
                catch (ArgumentException)
                {
                    messageboxService.Show(lp.InvalidSignatureErrorText, lp.PackageValidityCheckErrorCaption,
                                           EnuMessageBoxButton.Ok,
                                           EnuMessageBoxImage.Error);
                    return;
                }
                catch (Exception ex)
                {
                    messageboxService.Show(ex.Message, lp.PackageValidityCheckErrorCaption, EnuMessageBoxButton.Ok,
                                           EnuMessageBoxImage.Error);
                    return;
                }

                if (!valid)
                {
                    messageboxService.Show(lp.SignatureNotMatchingErrorText, lp.InvalidSignatureErrorCaption,
                                           EnuMessageBoxButton.Ok,
                                           EnuMessageBoxImage.Error);
                }

                else
                {
                    try
                    {
                        UpdateManager.InstallPackage();
                    }
                    catch (Exception ex)
                    {
                        messageboxService.Show($"{lp.SignatureNotMatchingErrorText} Error: {ex}",
                                               lp.InvalidSignatureErrorCaption, EnuMessageBoxButton.Ok,
                                               EnuMessageBoxImage.Error);
                    }
                }
            }
            finally
            {
                _active = false;
            }
        }
Exemplo n.º 9
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors();
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);


            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info
                {
                    Version        = "v1",
                    Title          = "GemSto API",
                    Description    = "GemSto - The Gem Merchant",
                    TermsOfService = "None",
                    Contact        = new Contact()
                    {
                        Name = "GemSto"                      /*, Email = "*****@*****.**", Url = "www.talkingdotnet.com"*/
                    }
                });

                var security = new Dictionary <string, IEnumerable <string> >
                {
                    { "Bearer", new string[] { } },
                };

                c.AddSecurityDefinition("Bearer", new ApiKeyScheme
                {
                    Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                    Name        = "Authorization",
                    In          = "header",
                    Type        = "apiKey"
                });
                c.AddSecurityRequirement(security);
            });


            services.AddAuthentication()
            .AddJwtBearer(cfg =>
            {
                cfg.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidIssuer      = Configuration["Tokens:Issuer"],
                    ValidAudience    = Configuration["Tokens:Audience"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Tokens:Key"]))
                };
            });

            #region dbcontext

            services.AddDbContext <MyContext>(options =>
                                              options.UseSqlServer(Configuration.GetConnectionString("MyContext")));

            #endregion

            #region AutoMapper

            // services.AddAutoMapper();

            Mapper.Initialize(cfg =>
            {
                cfg.AddProfile <Automapper>();
            });

            var config = new MapperConfiguration(cfg =>
            {
                cfg.AddProfile(new Automapper());
            });
            var mapper = config.CreateMapper();
            services.AddSingleton(mapper);

            #endregion

            #region service injector

            ServiceInjector.InjectServices(services);

            #endregion
        }
Exemplo n.º 10
0
 public App()
 {
     ServiceInjector.InjectServices();
 }
Exemplo n.º 11
0
 static MsgBoxBase()
 {
     ServiceInjector.InjectServices();
 }
Exemplo n.º 12
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors();
            services.AddDbContext <DataContext>(o => o.UseSqlServer(Configuration.GetConnectionString("vshopDBConnectionString"))); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);;
            services.AddAutoMapper();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info
                {
                    Version     = "v1",
                    Title       = "Test API",
                    Description = "ASP.NET Core Web API"
                });
                c.AddSecurityDefinition("Bearer",
                                        new ApiKeyScheme
                {
                    In          = "header",
                    Description = "Please enter into field the word 'Bearer' following by space and JWT",
                    Name        = "Authorization",
                    Type        = "apiKey"
                });
                c.AddSecurityRequirement(new Dictionary <string, IEnumerable <string> > {
                    { "Bearer", Enumerable.Empty <string>() },
                });
            });

            // configure strongly typed settings objects
            var appSettingsSection = Configuration.GetSection("AppSettings");

            services.Configure <AppSettings>(appSettingsSection);

            // configure jwt authentication
            var appSettings = appSettingsSection.Get <AppSettings>();
            var key         = Encoding.ASCII.GetBytes(appSettings.Secret);

            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x =>
            {
                x.Events = new JwtBearerEvents
                {
                    OnTokenValidated = context =>
                    {
                        var userService = context.HttpContext.RequestServices.GetRequiredService <IUserService>();
                        var userId      = int.Parse(context.Principal.Identity.Name);
                        var user        = Task.Run(async() => await userService.GetByIdAsync(userId));
                        if (user == null)
                        {
                            // return unauthorized if user no longer exists
                            context.Fail("Unauthorized");
                        }
                        return(Task.CompletedTask);
                    }
                };
                x.RequireHttpsMetadata      = false;
                x.SaveToken                 = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(key),
                    ValidateIssuer           = false,
                    ValidateAudience         = false
                };
            });

            #region Automapper
            Mapper.Initialize(cfg =>
            {
                cfg.AddProfile <Automapper>();
            });

            var config = new MapperConfiguration(cfg =>
            {
                cfg.AddProfile(new Automapper());
            });
            var mapper = config.CreateMapper();
            services.AddSingleton(mapper);
            #endregion

            // configure DI for application services
            ServiceInjector.InjectServices(services);
        }
Exemplo n.º 13
0
 static Msg()
 {
     ServiceInjector.InjectServices();
 }
Exemplo n.º 14
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors();

            //Connection String
            services.AddDbContext <AppDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            //Identity
            services.AddIdentity <User, IdentityRole>()
            .AddRoles <IdentityRole>()
            .AddEntityFrameworkStores <AppDbContext>();

            //JWT
            services.AddAuthentication()
            .AddJwtBearer(cfg =>
            {
                cfg.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidIssuer      = Configuration["Tokens:Issuer"],
                    ValidAudience    = Configuration["Tokens:Audience"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Tokens:Key"]))
                };
            });

            //AutoMapper
            var mapping = new MapperConfiguration(mc =>
            {
                mc.AddProfile(new AutoMapperConfig());
            });

            IMapper mapper = mapping.CreateMapper();

            services.AddSingleton(mapper);

            //Dependency Injection
            ServiceInjector.InjectServices(services);

            services.AddMvc(options => options.EnableEndpointRouting = false);

            // In production, the Angular files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/dist";
            });

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Title       = "Tutor 101 API",
                    Version     = "v1",
                    Description = "Tutor 101 Application",
                });

                c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    Name         = "Authorization",
                    Type         = SecuritySchemeType.ApiKey,
                    Scheme       = "Bearer",
                    BearerFormat = "JWT",
                    In           = ParameterLocation.Header,
                    Description  = "JWT Authorization header using the Bearer scheme."
                });

                c.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference
                            {
                                Type = ReferenceType.SecurityScheme,
                                Id   = "Bearer"
                            }
                        },
                        new string[] {}
                    }
                });
            });
        }