Exemplo n.º 1
0
        static void Main(string[] args)
        {
            Log.Logger = StandardLoggerConfigurator.GetEnrichedLogger();
            Log.Logger.Information("Starting migration...");

            try
            {
                var settings = new Configuration();
                var migrator = new DbMigrator(settings);

                Log.Logger.Information("Migrating " + settings.TargetDatabase);

                foreach (var pendingMigration in migrator.GetPendingMigrations())
                {
                    Log.Logger.Debug("Pending migration: " + pendingMigration);
                }

                migrator.Update();
            }
            catch (Exception e)
            {
                Log.Logger.Error(e, "Error during migration");
                throw;
            }
            Log.Logger.Information("Migration done without problems...");
        }
Exemplo n.º 2
0
        private static void Main(string[] args)
        {
            Log.Logger = StandardLoggerConfigurator.GetEnrichedLogger();

            using (var wrapper = new TopshelfWrapper <Worker>(
                       () =>
            {
                Mapper.Initialize(cfg =>
                {
                    cfg.CreateMap <FileProcessedEvent, FileReadyForCleanupEvent>();
                    cfg.CreateMap <FileUploadedEvent, FileReadyForProcessingEvent>();
                    cfg.CreateMap <FileReadyForProcessingEvent, FileProcessedEvent>();
                });
            },
                       s =>
            {
                var appSettings = new AppSettings();
                var repository = new Repository(appSettings);
                var subscriptionService = new SubscriptionService(repository);
                var mailSender = new MailSender();
                var radapter = new Radapter(appSettings);
                IBusAdapter bus = new BusAdapter(appSettings);
                var mailMessageService = new MailMessageService(appSettings, subscriptionService);

                s.ConstructUsing(name => new Worker(bus, appSettings,
                                                    new HandleSendEmailConfirmingUpload(bus, mailMessageService, mailSender, appSettings),
                                                    new HandleProcessUploadedFileThroughR(bus, appSettings, radapter),
                                                    new HandleSendEmailWithResults(bus, mailMessageService, mailSender, appSettings),
                                                    new HandleUpdateSubscriptionDatabase(subscriptionService)));
            }))
            {
                wrapper.Run();
            }
        }
Exemplo n.º 3
0
        public void Configuration(IAppBuilder app)
        {
            Log.Logger = StandardLoggerConfigurator
                         .GetLoggerConfig().MinimumLevel
                         .Debug()
                         .CreateLogger();

            Log.Logger.Information("Starting...");
            Log.Logger.Information("Version is... " + ConfigurationManager.AppSettings["ReleaseNumber"]);

            // setup http configuration
            var httpConfig = new HttpConfiguration();

            //configure dependency injection
            var container = IoC.Initialize();

            container.AssertConfigurationIsValid();
            Debug.WriteLine(container.WhatDoIHave());
            Log.Logger.Debug(container.WhatDoIHave());
            httpConfig.DependencyResolver = new StructureMapWebApiDependencyResolver(container);

            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary <string, string>();

            app.UseIdentityServerBearerTokenAuthentication(
                new IdentityServerBearerTokenAuthenticationOptions
            {
                Authority      = ConfigurationManager.AppSettings["IdentityServerApplicationUrl"],
                RequiredScopes = new[] { "gallerymanagement" }
            });

            WebApiConfig.Register(httpConfig);
            app.UseWebApi(httpConfig);

            AutoMapperInitializor.Init();
        }
Exemplo n.º 4
0
        static void Main(string[] args)
        {
            Log.Logger = StandardLoggerConfigurator
                         .GetLoggerConfig().MinimumLevel
                         .Debug()
                         .CreateLogger();

            Log.Logger.Debug("Started...");

            var path    = GetArg(args, "-p", "c:\\temp");
            var pattern = GetArg(args, "-m", "*.*");
            var age     = Convert.ToInt32(GetArg(args, "-a", "7"));
            var keep    = Convert.ToInt32(GetArg(args, "-k", "0"));

            Log.Logger.Debug("Args: ... Path=" + path);
            Log.Logger.Debug("Args: ... Pattern=" + pattern);
            Log.Logger.Debug("Args: ... Age=" + age);
            Log.Logger.Debug("Args: ... Keep=" + keep);


            var threshold = DateTime.Now.AddDays(-age);

            var files = Directory
                        .EnumerateFiles(path, pattern)
                        .Select(x => new FileAndDate(x, File.GetCreationTime(x)))
                        .OrderBy(fd => fd.DateTime)
                        .ToArray();

            Log.Logger.Debug("Found files: ... ", files.Length);

            while (files.Length > 0)
            {
                if (files.Length <= keep)
                {
                    Log.Logger.Debug("Less (or equal) number of files than required to keep.");
                    return;
                }

                var file = files.First();

                if (file.DateTime < threshold)
                {
                    Log.Logger.Debug("Deleting " + file.FileName);
                    File.Delete(file.FileName);
                }
                else
                {
                    Log.Logger.Debug("NOT Deleting " + file.FileName);
                    Log.Logger.Debug("Oldest file is not old enough to be deleted.");
                    return;
                }
                files = files.Skip(1).ToArray();
            }
        }
Exemplo n.º 5
0
        protected void Application_Start()
        {
            Log.Logger = StandardLoggerConfigurator.GetEnrichedLogger();
            Log.Logger.Information("Starting...");

            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            Log.Logger.Information("Done app start...");
        }
Exemplo n.º 6
0
        private static void Main(string[] args)
        {
            Log.Logger = StandardLoggerConfigurator
                         .GetLoggerConfig().MinimumLevel
                         .Debug()
                         .CreateLogger();

            Log.Logger.Information("Starting Service with args: " + string.Join("|", args));

            using (var container = ServiceIoC.Initialize())
            {
                Log.Logger.Debug("WhatDoIHave" + "\n" + container.WhatDoIHave());

                Log.Logger.Information("Container created.");

                using (var wrapper = new TopshelfWrapper <WorkerDirWatcher>(
                           () => {},
                           s =>
                {
                    s.ConstructUsing(name =>
                    {
                        try
                        {
                            var instance = container.GetInstance <WorkerDirWatcher>();
                            Log.Logger.Debug("I have instance of WorkerDirWatcher!");
                            return(instance);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e);
                            throw;
                        }
                    });
                }))
                {
                    try
                    {
                        wrapper.Run();
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                        throw;
                    }
                }
            }
        }
Exemplo n.º 7
0
        static void Main(string[] args)
        {
            Log.Logger = StandardLoggerConfigurator.GetEnrichedLogger();
            Log.Logger.Information("Starting migration...");

            try
            {
                var settings = new Configuration();
                var migrator = new DbMigrator(settings);
                migrator.Update();
            }
            catch (Exception e)
            {
                Log.Logger.Error(e, "Error during migration");
                throw;
            }
            Log.Logger.Information("Migration done without problems...");
        }
Exemplo n.º 8
0
        private static void Main(string[] args)
        {
            Log.Logger = StandardLoggerConfigurator.GetEnrichedLogger();

            try
            {
                var appSettings = new AppSettings();

                HostFactory.Run(x =>        //1
                {
                    x.Service <Worker>(s => //2
                    {
                        try
                        {
                            s.ConstructUsing(name => new Worker(appSettings)); //3
                            s.WhenStarted(tc =>
                            {
                                Log.Logger.Information("Starting service");
                                tc.Start();
                                Log.Logger.Information("Service started.");
                            }); //4
                            s.WhenStopped(tc =>
                            {
                                Log.Logger.Information("Stopping service.");
                                tc.Stop();
                                Log.Logger.Information("Service stopped.");
                            }); //5
                            s.WhenPaused(tc =>
                            {
                                Log.Logger.Information("Pausing service.");
                                tc.Stop();
                                Log.Logger.Information("Service paused.");
                            }); //5

                            s.WhenContinued(tc =>
                            {
                                Log.Logger.Information("Continuing service.");
                                tc.Start();
                                Log.Logger.Information("Service continued.");
                            }); //5
                            s.WhenSessionChanged((w, sca) =>
                            {
                                Log.Logger.Information("Session changed: " + w);
                                Log.Logger.Information("Session changed: " + sca);
                            });
                        }
                        catch (Exception ex)
                        {
                            Log.Error(ex, "Fra program");
                            throw;
                        }
                    });
                    x.RunAsLocalSystem();                      //6

                    x.SetDescription(appSettings.Description); //7
                    x.SetDisplayName(appSettings.DisplayName); //8
                    x.SetServiceName(appSettings.ServiceName); //9
                });                                            //10        }
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Yderste");
                throw;
            }
        }
Exemplo n.º 9
0
        public void BuildMsi()
        {
            Log.Logger = StandardLoggerConfigurator
                         .GetLoggerConfig()
                         .CreateLogger();

            try
            {
                Log.Logger.Debug(@"Building MSI...");

                IMsiBuilderSettings msiBuilderSettings = new MsiBuilderSettings();

                var pathChoices = msiBuilderSettings.PathChoices;
                var uiExe       = msiBuilderSettings.UiExe;

                Log.Logger.Debug(@"Creating installer for: " + uiExe);

                var path = pathChoices.FirstOrDefault(x => File.Exists(x + @"\" + uiExe));
                if (string.IsNullOrEmpty(path))
                {
                    throw new ArgumentException("The uiExe was not found: " + uiExe);
                }

                Log.Logger.Debug(@"Chosen path: " + path);

                var guidString = GetGuidString();

                var envStringToShow = GetEnvStringToShow(msiBuilderSettings);
                var releaseNumber   = msiBuilderSettings.ReleaseNumber;

                Log.Logger.Debug(@"Release number is: " + releaseNumber);

                var companyName    = msiBuilderSettings.CompanyName;
                var productWithEnv = msiBuilderSettings.ProductName + $"{envStringToShow}";

                Log.Logger.Debug(@"Product with env is: " + productWithEnv);

                var x64SqLite = new Feature("x64SqLite");
                var x86SqLite = new Feature("x86SqLite");

                //var exeFileShortcut1 = new ExeFileShortcut(productWithEnv,
                //    $@"%ProgramFiles%\\{companyName}\\{productWithEnv}\\JCI.ITC.SABPrice.UI.exe",
                //    "");
                var exeFileShortcut1 = new ExeFileShortcut(productWithEnv,
                                                           $@"[INSTALLDIR]\\" + msiBuilderSettings.UiExe,
                                                           "");
                var exeFileShortcut2 = new ExeFileShortcut($"Uninstall {productWithEnv}", "[System64Folder]msiexec.exe",
                                                           "/x [ProductCode]");
                var menuDir = new Dir(
                    $"%ProgramMenu%\\{companyName}\\{productWithEnv}",
                    exeFileShortcut1,
                    exeFileShortcut2);

                const string appIconName = "app_icon.ico";
                if (!File.Exists(appIconName))
                {
                    throw new ArgumentException("No app icon file found named : " + appIconName);
                }


                var msiPrefix = msiBuilderSettings.MsiPrefix;
                var project   = new Project(
                    $"{productWithEnv} {releaseNumber}",
                    new Dir(
                        $@"%ProgramFiles%\{companyName}\{productWithEnv}",
                        new Files(path + @"\*.*",
                                  f => !f.EndsWith(".pdb") && !f.EndsWith(".msi")
                                  )
                        //,new Files(x64SqLite, path + @"\x64\SQLite.Interop.dll")
                        //,new Files(x86SqLite, path + @"\x86\SQLite.Interop.dll")
                        ),
                    menuDir
                    )
                {
                    GUID                 = new Guid(guidString),
                    OutFileName          = $@".\{msiPrefix}{envStringToShow}.{releaseNumber}",
                    MajorUpgradeStrategy = MajorUpgradeStrategy.Default,
                    Version              = new Version(releaseNumber),
                    ControlPanelInfo     = { ProductIcon = appIconName }
                };

                var exe = project
                          .ResolveWildCards()
                          .FindFile(f => f.Name.EndsWith(uiExe))
                          .First();

                exe.Shortcuts = new[]
                {
                    new FileShortcut(productWithEnv, "%Desktop%")
                };

                project.Version = new Version(releaseNumber);

                project.ControlPanelInfo.Comments        = productWithEnv;
                project.ControlPanelInfo.Readme          = "https://jci.com/";
                project.ControlPanelInfo.HelpLink        = "https://jci.com/";
                project.ControlPanelInfo.HelpTelephone   = "(+45) 6170 8335";
                project.ControlPanelInfo.UrlInfoAbout    = "https://jci.com/";
                project.ControlPanelInfo.UrlUpdateInfo   = "https://jci.com/";
                project.ControlPanelInfo.ProductIcon     = appIconName;
                project.ControlPanelInfo.Contact         = "*****@*****.**";
                project.ControlPanelInfo.Manufacturer    = "Sabroe Factory by Johnson Controls";
                project.ControlPanelInfo.InstallLocation = "[INSTALLDIR]";
                project.ControlPanelInfo.NoModify        = true;
                //project.ControlPanelInfo.NoRepair = true,
                //project.ControlPanelInfo.NoRemove = true,
                //project.ControlPanelInfo.SystemComponent = true, //if set will not be shown in Control Panel


                project.BannerImage     = "TopBanner.bmp";
                project.BackgroundImage = "MainPage.bmp";

                Log.Logger.Debug(@"BuildMSI ");
                Compiler.BuildMsi(project);

                Log.Logger.Debug(@"Succesfully created ");
                Log.Logger.Debug(project.Name);
            }
            catch (Exception e)
            {
                Log.Logger.Error(e, "During Setup / MSI creation.");
                Environment.ExitCode = 1;
                throw;
            }
        }
Exemplo n.º 10
0
        public void Configuration(IAppBuilder app)
        {
            Log.Logger = StandardLoggerConfigurator
                         .GetLoggerConfig().MinimumLevel
                         .Debug()
                         .CreateLogger();

            Log.Logger.Information("Starting...");
            Log.Logger.Information("Version is... " + ConfigurationManager.AppSettings["ReleaseNumber"]);

            //Mapper.Initialize(cfg =>
            //{
            //    cfg.CreateMap<Event, EventViewModel>()
            //        .ForMember(x => x.ViewModelMode, x => x.Ignore())
            //        .ForMember(x => x.CarEmail, x => x.Ignore())
            //        .ForMember(x => x.CarName, x => x.Ignore())
            //        .ForMember(x => x.CarPhone, x => x.Ignore());
            //});

            //Mapper.Configuration.AssertConfigurationIsValid();

            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary <string, string>();

            AntiForgeryConfig.UniqueClaimTypeIdentifier =
                JwtClaimTypes.Name;

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "Cookies",
                ExpireTimeSpan     = new TimeSpan(0, 30, 0),
                SlidingExpiration  = true
            });

            app.Use((context, next) =>
            {
                Debug.WriteLine("Hello world");
                return(next.Invoke());
            });

            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
            {
                ClientId    = ClientId,
                Authority   = ConfigurationManager.AppSettings["IdentityServerApplicationUrl"],
                RedirectUri = ConfigurationManager.AppSettings["UrlHansJuergenWeb"],
                SignInAsAuthenticationType = "Cookies",
                ResponseType          = "code id_token token",
                Scope                 = "openid profile address gallerymanagement roles offline_access email",
                UseTokenLifetime      = false,
                PostLogoutRedirectUri = ConfigurationManager.AppSettings["UrlHansJuergenWeb"],

                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    SecurityTokenValidated = async n =>
                    {
                        TokenHelper.DecodeAndWrite(n.ProtocolMessage.IdToken);
                        TokenHelper.DecodeAndWrite(n.ProtocolMessage.AccessToken);

                        var givenNameClaim = n.AuthenticationTicket
                                             .Identity.FindFirst(JwtClaimTypes.GivenName);

                        var familyNameClaim = n.AuthenticationTicket
                                              .Identity.FindFirst(JwtClaimTypes.FamilyName);

                        var subClaim = n.AuthenticationTicket
                                       .Identity.FindFirst(JwtClaimTypes.Subject);

                        var roleClaim = n.AuthenticationTicket
                                        .Identity.FindFirst(JwtClaimTypes.Role);

                        var emailClaim = n.AuthenticationTicket
                                         .Identity.FindFirst(JwtClaimTypes.Email);

                        // create a new claims, issuer + sub as unique identifier
                        var nameClaim = new Claim(JwtClaimTypes.Name,
                                                  Constants.TripGalleryIssuerUri + subClaim.Value);

                        var newClaimsIdentity = new ClaimsIdentity(
                            n.AuthenticationTicket.Identity.AuthenticationType,
                            JwtClaimTypes.Name,
                            JwtClaimTypes.Role);

                        newClaimsIdentity.AddClaim(nameClaim);

                        if (givenNameClaim != null)
                        {
                            newClaimsIdentity.AddClaim(givenNameClaim);
                        }

                        if (familyNameClaim != null)
                        {
                            newClaimsIdentity.AddClaim(familyNameClaim);
                        }

                        if (roleClaim != null)
                        {
                            newClaimsIdentity.AddClaim(roleClaim);
                        }

                        if (emailClaim != null)
                        {
                            newClaimsIdentity.AddClaim(emailClaim);
                        }

                        // request a refresh token
                        var tokenClientForRefreshToken = new TokenClient(
                            ConfigurationManager.AppSettings["IdentityServerApplicationUrl"] + "/connect/token",
                            ClientId,
                            Constants.TripGalleryClientSecret);

                        var refreshResponse = await
                                              tokenClientForRefreshToken.RequestAuthorizationCodeAsync(
                            n.ProtocolMessage.Code,
                            ConfigurationManager.AppSettings["UrlHansJuergenWeb"]);

                        if (refreshResponse == null)
                        {
                            Log.Logger.Debug("refreshResponse==null");
                        }
                        else
                        {
                            Log.Logger.Debug("refreshResponse == " + Json.Encode(refreshResponse));
                        }

                        var expirationDateAsRoundtripString
                            = DateTime.SpecifyKind(DateTime.UtcNow.AddSeconds(refreshResponse.ExpiresIn)
                                                   , DateTimeKind.Utc).ToString("o");


                        newClaimsIdentity.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken));
                        newClaimsIdentity.AddClaim(new Claim("refresh_token", refreshResponse.RefreshToken));
                        newClaimsIdentity.AddClaim(new Claim("access_token", refreshResponse.AccessToken));
                        newClaimsIdentity.AddClaim(new Claim("expires_at", expirationDateAsRoundtripString));
                        newClaimsIdentity.AddClaim(new Claim("sub", subClaim.Value));

                        // create a new authentication ticket, overwriting the old one.
                        n.AuthenticationTicket = new AuthenticationTicket(
                            newClaimsIdentity,
                            n.AuthenticationTicket.Properties);

                        //await UserService.CreateUserIfNotExisting(newClaimsIdentity);
                    },
                    RedirectToIdentityProvider = async n =>
                    {
                        await Task.FromResult(0);

                        // get id token to add as id token hint
                        if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.LogoutRequest)
                        {
                            var identityTokenHint = n.OwinContext.Authentication.User.FindFirst("id_token");

                            if (identityTokenHint != null)
                            {
                                n.ProtocolMessage.IdTokenHint = identityTokenHint.Value;
                            }
                        }
                        //else if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.AuthenticationRequest)
                        //{
                        //    string existingAcrValues = null;
                        //    if (n.ProtocolMessage.Parameters.TryGetValue("acr_values", out existingAcrValues))
                        //    {
                        //        // add "2fa" - acr_values are separated by a space
                        //        n.ProtocolMessage.Parameters["acr_values"] = existingAcrValues + " 2fa";
                        //    }

                        //    n.ProtocolMessage.Parameters["acr_values"] = "2fa";
                        //}
                    }
                }
            });
        }