Example #1
0
        public RegisterRepository(IMasterRepository masterRepository, IRegisterService service, IDynamixService dynamix = null,
                                  IDynamixReturnService <List <DynamixContact> > dynamixReturn           = null,
                                  IDynamixReturnService <DynamixPolicy> dynasmicPolicyReturn             = null,
                                  IDynamixReturnService <DynamixCommunity> dynamixCommunityReturnService = null,
                                  IDynamixReturnService <GetUserReturnModel> dynamixUserReturnService    = null)
            : base(masterRepository)
        {
            _Service                       = service;
            _DynamixService                = dynamix;
            _DynamixReturnService          = dynamixReturn;
            _DynamixPolicyReturnService    = dynasmicPolicyReturn;
            _DynamixCommunityReturnService = dynamixCommunityReturnService;
            _DynamixUserReturnService      = dynamixUserReturnService;
            _PlatformBonsai                = new PlatformBonsai();
            BlobStorageRepository          = new AzureBlobStorageRepository(_MasterRepo);
            var platform = new PlatformRepository <RegisterViewModel>(masterRepository, _PlatformBonsai)
            {
                OnError = (errs) =>
                {
                    OnError?.Invoke(errs);
                }
            };

            _SelfieRepo = new SelfieRepository(_MasterRepo);
        }
Example #2
0
        public void InsertThenUpdate_ShouldReflectChanges()
        {
            // Arrange
            var expectedValue = "*****@*****.**";
            var dummyString   = Guid.NewGuid().ToString().Replace("-", "");
            var dbModel       = new PlatformModel()
            {
                Description = dummyString,
            };

            // Act
            var newId = new PlatformRepository(AppState.ConnectionString)
                        .Insert(dbModel);
            var dbModel2 = new PlatformRepository(AppState.ConnectionString)
                           .Select(newId);

            dbModel2.Description = expectedValue;

            new PlatformRepository(AppState.ConnectionString)
            .Update(dbModel2);
            var actualValue = new PlatformRepository(AppState.ConnectionString)
                              .Select(newId)
                              .Description;

            // Assert
            Assert.AreEqual(expectedValue, actualValue);
        }
Example #3
0
        public void InsertBulkThenSelectList_ShouldEqualTwo()
        {
            // Arrange
            var expectedValue = 2;
            var dummyString   = Guid.NewGuid().ToString().Replace("-", "");
            var listPoco      = new List <PlatformModel>()
            {
                new PlatformModel()
                {
                    Description = dummyString,
                },
                new PlatformModel()
                {
                    Description = dummyString,
                }
            };

            // Act
            new PlatformRepository(AppState.ConnectionString).InsertBulk(listPoco);
            var actualValue = new PlatformRepository(AppState.ConnectionString)
                              .SelectList()
                              .Where(x => x.Description.Equals(dummyString))
                              .ToList()
                              .Count;

            // Assert
            Assert.AreEqual(expectedValue, actualValue);
        }
Example #4
0
 public UnitOfWork(NerdyContext context)
 {
     _context = context;
     Book     = new BookRepository(context);
     Genre    = new GenreRepository(context);
     Platform = new PlatformRepository(context);
     Order    = new OrderRepository(context);
 }
        public DashboardRepository(IMasterRepository masterRepository, IDashboardService <T> service)
            : base(masterRepository)
        {
            _Service        = service;
            _PlatformBonsai = new PlatformBonsai();
            var platform = new PlatformRepository <DashboardViewModel>(masterRepository, _PlatformBonsai);

            platform.OnError = (errs) =>
            {
                OnError?.Invoke(errs);
            };
        }
        public void LoadByGuid()
        {
            IPlatformRepository iPlatformDAL = new PlatformRepository(this.Client, this.Database);

            IEnumerable<Platform> platforms = iPlatformDAL.FindAll();

            foreach (Platform platform in platforms)
            {
                Platform platformToCheck = iPlatformDAL.Find(platform.Guid);
                Assert.IsTrue(platformToCheck.Id > 0);
                Assert.IsNotNull(platformToCheck.Name);
            }
        }
Example #7
0
        public void LoadByGuid()
        {
            IPlatformRepository iPlatformDAL = new PlatformRepository(this.Client, this.Database);

            IEnumerable <Platform> platforms = iPlatformDAL.FindAll();

            foreach (Platform platform in platforms)
            {
                Platform platformToCheck = iPlatformDAL.Find(platform.Guid);
                Assert.IsTrue(platformToCheck.Id > 0);
                Assert.IsNotNull(platformToCheck.Name);
            }
        }
        public void Save_Platforms_Against_An_Application()
        {
            IApplicationRepository applicationRepository = new ApplicationRepository(this.Client, this.Database);
            IPlatformRepository    iPlatformDAL          = new PlatformRepository(this.Client, this.Database);

            Application application = new Application(Guid.NewGuid().ToString());

            application.Platforms = iPlatformDAL.FindAll().ToList();
            applicationRepository.Save(application);

            Application applicationFound = applicationRepository.Find(application.Guid);

            Assert.IsNotNull(applicationFound.Platforms);
            Assert.IsTrue(applicationFound.Platforms.Count == application.Platforms.Count);
        }
        public void GetPlatformSDK()
        {
            IPlatformRepository iPlatformDAL = new PlatformRepository(this.Client, this.Database);

            IEnumerable<Platform> platforms = iPlatformDAL.FindAll();

            foreach (Platform platform in platforms)
            {
                Platform platformSDK = iPlatformDAL.Find(platform.Id);
                Assert.IsTrue(platformSDK.Id > 0);
                Assert.IsNotNull(platformSDK.Name);
                Assert.IsNotNull(platformSDK.Url);
                Assert.IsNotNull(platformSDK.UrlTitle);
            }
        }
Example #10
0
        public void GetPlatformSDK()
        {
            IPlatformRepository iPlatformDAL = new PlatformRepository(this.Client, this.Database);

            IEnumerable <Platform> platforms = iPlatformDAL.FindAll();

            foreach (Platform platform in platforms)
            {
                Platform platformSDK = iPlatformDAL.Find(platform.Id);
                Assert.IsTrue(platformSDK.Id > 0);
                Assert.IsNotNull(platformSDK.Name);
                Assert.IsNotNull(platformSDK.Url);
                Assert.IsNotNull(platformSDK.UrlTitle);
            }
        }
        public void Remove_Platforms_From_Application()
        {
            IApplicationRepository applicationRepository = new ApplicationRepository(this.Client, this.Database);
            IPlatformRepository iPlatformDAL = new PlatformRepository(this.Client, this.Database);

            Application application = new Application(Guid.NewGuid().ToString());
            application.Platforms = iPlatformDAL.FindAll().ToList();
            applicationRepository.Save(application);

            Application applicationFound = applicationRepository.Find(application.Guid);
            applicationFound.Platforms = new List<Platform>();
            applicationRepository.Update(application);

            Application applicationRemovedPlatforms = applicationRepository.Find(application.Guid);
            Assert.IsTrue(applicationRemovedPlatforms.Platforms.Count == 0);
        }
Example #12
0
        public void TesteSalvarJogoView()
        {
            IgdbService        igdb     = new IgdbService();
            DadosGameResponse  response = igdb.DadosJogo(428).FirstOrDefault();
            PlatformRepository pr       = new PlatformRepository();
            List <DadosDeveloperPublisherResponse> devs = igdb.DadosDeveloperPublisher(response.Developers.ToArray());
            List <DadosDeveloperPublisherResponse> pubs = igdb.DadosDeveloperPublisher(response.Publishers.ToArray());

            GameDataView gameDataView = GameDataView.init();

            gameDataView.Titulo      = response.Name;
            gameDataView.Descricao   = response.Summary;
            gameDataView.CloudnaryId = response.Cover.CloudinaryId;

            foreach (DadosDeveloperPublisherResponse dev in devs)
            {
                gameDataView.ListaDeveloper.Add(new developerPublisher {
                    name = dev.Name
                });
            }

            foreach (DadosDeveloperPublisherResponse pub in pubs)
            {
                gameDataView.ListaPublisher.Add(new developerPublisher {
                    name = pub.Name
                });
            }

            foreach (ReleaseDate lancamento in response.ReleaseDates)
            {
                platform plataforma = pr.GetPlatformByIgdb(lancamento.Platform);
                if (plataforma != null)
                {
                    DateTime data = new DateTime(1970, 1, 1, 0, 0, 0).AddMilliseconds(Convert.ToDouble(Convert.ToDouble(lancamento.Date)));
                    gameDataView.Platforms.Add(new game_platform {
                        id_platform  = plataforma.id,
                        release_date = data,
                        id_region    = lancamento.Region
                    });
                }
            }

            GameRepository gameRepository = new GameRepository();

            gameRepository.Adicionar(gameDataView);
        }
Example #13
0
        public static LayoutView init()
        {
            GameRepository     gr = new GameRepository();
            PlatformRepository platformRepository = new PlatformRepository();

            view        = new LayoutView();
            view.ativos = new List <int>();
            view.totais = new List <Totais>();

            Dictionary <string, int> total = gr.GetTotalJogosStatus();
            List <game_platform>     jogos = gr.GetListaGeral();

            view.listaPlatform = platformRepository.Listar();

            view.total_colecao   = total["Coleção"];
            view.total_wishlist  = total["Wishlist"];
            view.total_watchlist = total["Watchlist"];
            view.total_plus      = total["Plus"];

            foreach (platform plat in view.listaPlatform)
            {
                view.totais.Add(new Totais {
                    plataforma = plat.sigla,
                    status     = "colecao",
                    total      = jogos.FindAll(j => (j.id_status == 1) && (j.platform.sigla == plat.sigla)).Count
                });
                view.totais.Add(new Totais {
                    plataforma = plat.sigla,
                    status     = "wishlist",
                    total      = jogos.FindAll(j => (j.id_status == 2) && (j.platform.sigla == plat.sigla)).Count
                });
                view.totais.Add(new Totais {
                    plataforma = plat.sigla,
                    status     = "watchlist",
                    total      = jogos.FindAll(j => (j.id_status == 3) && (j.platform.sigla == plat.sigla)).Count
                });
                view.totais.Add(new Totais {
                    plataforma = plat.sigla,
                    status     = "plus",
                    total      = jogos.FindAll(j => (j.id_status == 4) && (j.platform.sigla == plat.sigla)).Count
                });
            }

            return(view);
        }
Example #14
0
        public void InsertAndSelect_ShouldEqualInserted()
        {
            // Arrange
            var dbModel = new PlatformModel()
            {
                Description = "ex",
            };
            var expectedValue = new PlatformRepository(AppState.ConnectionString)
                                .Insert(dbModel);

            // Act
            var actualValue = new PlatformRepository(AppState.ConnectionString)
                              .Select(expectedValue)
                              .Id;

            // Assert
            Assert.AreEqual(expectedValue, actualValue);
        }
Example #15
0
        public DashboardRepository(
            IMasterRepository masterRepository,
            IDashboardService <T> service,
            ITrackLocationService <TrackLocationViewModel> trackLocationService,
            DashboardViewModel model)
            : base(masterRepository)
        {
            //var tracker = new TrackLocationRepository<TrackLocationViewModel>(_MasterRepo, trackLocationService);
            _Service = service;
            _Model   = model;
            var platform = new PlatformRepository <DashboardViewModel>(masterRepository);

            platform.OnError = (errs) =>
            {
                OnError?.Invoke(errs);
            };
            var FingerPrint = new FingerPrintRepository <DashboardViewModel>(masterRepository);
        }
        public void Remove_Platforms_From_Application()
        {
            IApplicationRepository applicationRepository = new ApplicationRepository(this.Client, this.Database);
            IPlatformRepository    iPlatformDAL          = new PlatformRepository(this.Client, this.Database);

            Application application = new Application(Guid.NewGuid().ToString());

            application.Platforms = iPlatformDAL.FindAll().ToList();
            applicationRepository.Save(application);

            Application applicationFound = applicationRepository.Find(application.Guid);

            applicationFound.Platforms = new List <Platform>();
            applicationRepository.Update(applicationFound);

            Application applicationRemovedPlatforms = applicationRepository.Find(application.Guid);

            Assert.IsTrue(applicationRemovedPlatforms.Platforms.Count == 0);
        }
        public void initNonExistingRepo(bool withUnitOfWork = false)
        {
            // Als we een repo met UoW willen gebruiken en als er nog geen uowManager bestaat:
            // Dan maken we de uowManager aan en gebruiken we de context daaruit om de repo aan te maken.

            if (withUnitOfWork)
            {
                if (uowManager == null)
                {
                    uowManager         = new UnitOfWorkManager();
                    platformRepository = new PlatformRepository(uowManager.UnitOfWork);
                }
            }
            // Als we niet met UoW willen werken, dan maken we een repo aan als die nog niet bestaat.
            else
            {
                platformRepository = (platformRepository == null) ? new PlatformRepository() : platformRepository;
            }
        }
Example #18
0
        public void InsertAndDelete_ShouldNoLongerExistAfterDelete()
        {
            // Arrange
            var expectedValue = 0;
            var dbModel       = new PlatformModel()
            {
                Description = "ex",
            };

            // Act
            var newId = new PlatformRepository(AppState.ConnectionString).Insert(dbModel);

            new PlatformRepository(AppState.ConnectionString).Delete(newId);
            var actualValue = new PlatformRepository(AppState.ConnectionString)
                              .Select(newId)
                              .Id;

            // Assert
            Assert.AreEqual(expectedValue, actualValue);
        }
 public PlatformManager(UnitOfWorkManager unitOfWorkManager)
 {
     repo        = new PlatformRepository(unitOfWorkManager.UnitOfWork);
     userManager = new ApplicationUserManager(unitOfWorkManager);
 }
Example #20
0
        public async Task <ActionResult> PreencherDadosGameIgdbJquery(int id_igdb, int Id = 0)
        {
            IgdbService       igdb     = new IgdbService();
            DadosGameResponse response = igdb.DadosJogo(id_igdb).FirstOrDefault();
            List <DadosDeveloperPublisherResponse> devs = new List <DadosDeveloperPublisherResponse>();
            List <DadosDeveloperPublisherResponse> pubs = new List <DadosDeveloperPublisherResponse>();
            List <DadosGenreResponse> genres            = new List <DadosGenreResponse>();
            List <ReleaseDate>        lancamentos       = new List <ReleaseDate>();

            PlatformRepository pr = new PlatformRepository();

            if (response.Developers != null && response.Developers.Count > 0)
            {
                devs = igdb.DadosDeveloperPublisher(response.Developers.ToArray());
            }
            if (response.Publishers != null && response.Publishers.Count > 0)
            {
                pubs = igdb.DadosDeveloperPublisher(response.Publishers.ToArray());
            }
            if (response.Genres != null && response.Genres.Count > 0)
            {
                genres = igdb.DadosGenre(response.Genres.ToArray());
            }
            if (response.ReleaseDates != null && response.ReleaseDates.Count > 0)
            {
                lancamentos = response.ReleaseDates;
            }

            GameDataView gameDataView = GameDataView.GetGameDataView();

            gameDataView.Id        = Id;
            gameDataView.id_igdb   = id_igdb;
            gameDataView.Titulo    = response.Name;
            gameDataView.Descricao = response.Summary;

            if (response.Cover != null)
            {
                gameDataView.Imagem      = gameDataView.BigCoverUrl + response.Cover.CloudinaryId + ".jpg";
                gameDataView.CloudnaryId = response.Cover.CloudinaryId;
            }
            else
            {
                gameDataView.Imagem = "/Content/ps.png";
            }

            gameDataView.InitListas();

            foreach (DadosDeveloperPublisherResponse dev in devs)
            {
                gameDataView.ListaDeveloper.Add(new developerPublisher {
                    name    = dev.Name,
                    id_igdb = dev.Id
                });
            }

            foreach (DadosDeveloperPublisherResponse pub in pubs)
            {
                gameDataView.ListaPublisher.Add(new developerPublisher {
                    name    = pub.Name,
                    id_igdb = pub.Id
                });
            }

            foreach (DadosGenreResponse genre in genres)
            {
                gameDataView.ListaGenre.Add(new genre {
                    id_igdb = genre.Id,
                    name    = genre.Name
                });
            }

            try {
                var buscaMetacritic = await Metacritic.SearchFor().Games().UsingTextAsync(response.Name);

                foreach (ReleaseDate lancamento in lancamentos)
                {
                    platform plataforma = pr.GetPlatformByIgdb(lancamento.Platform);
                    int?     meta       = null;
                    if (plataforma != null)
                    {
                        string sigla;
                        switch (plataforma.sigla)
                        {
                        case "PS1":
                            sigla = "PS";
                            break;

                        case "PSVITA":
                            sigla = "VITA";
                            break;

                        default:
                            sigla = plataforma.sigla;
                            break;
                        }

                        var resultado = buscaMetacritic.Where(m => m.Platform == sigla).Where(m => m.Name.ToLowerInvariant() == response.Name.ToLowerInvariant()).FirstOrDefault();
                        if (resultado != null)
                        {
                            meta = resultado.Score;
                        }

                        DateTime data = new DateTime(1970, 1, 1, 0, 0, 0).AddSeconds(Convert.ToDouble(Convert.ToDouble(lancamento.Date)));
                        gameDataView.Platforms.Add(new game_platform {
                            id_platform  = plataforma.id,
                            release_date = data,
                            metacritic   = meta,
                            id_region    = lancamento.Region
                        });
                    }
                }
            }
            catch (Exception ex) {
            }

            return(PartialView("FormGameView", gameDataView));
        }
Example #21
0
        public void ExportarJogosJquery()
        {
            string[] Scopes = { SheetsService.Scope.Spreadsheets };

            UserCredential credential;

            using (var stream =
                       new FileStream("client_secret.json", FileMode.Open, FileAccess.Read)) {
                string credPath = System.Environment.GetFolderPath(
                    System.Environment.SpecialFolder.Personal);
                credPath = Path.Combine(credPath, ".credentials/games.json");

                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
            }

            // Create Google Sheets API service.
            SheetsService sheetsService = new SheetsService(new BaseClientService.Initializer {
                HttpClientInitializer = credential,
                ApplicationName       = "Google-SheetsSample/0.1",
            });

            string id = "1k7Reqz1ZqGXwr8lTy5Y5r6bX53hxWv4kJSWTs3ptAuc";

            GameRepository     game       = new GameRepository();
            PlatformRepository plataforma = new PlatformRepository();

            SpreadsheetsResource.GetRequest get = sheetsService.Spreadsheets.Get(id);
            Spreadsheet planilhas = get.Execute();

            SpreadsheetsResource.ValuesResource.UpdateRequest.ValueInputOptionEnum valueInputOption = (SpreadsheetsResource.ValuesResource.UpdateRequest.ValueInputOptionEnum) 2;

            foreach (Sheet planilha in planilhas.Sheets)
            {
                var aba = planilha.Properties.Title;

                ClearValuesRequest clearRequest = new ClearValuesRequest();
                SpreadsheetsResource.ValuesResource.ClearRequest request = sheetsService.Spreadsheets.Values.Clear(clearRequest, id, aba + "!A1:Z1000");
                ClearValuesResponse response = request.Execute();

                List <GameView> lista     = new List <GameView>();
                List <int>      plat      = new List <int>();
                List <object>   cabecalho = null;

                switch (aba)
                {
                case "Wishlist":
                    lista = game.ListarJogosWishlist(new List <int> {
                        0
                    });
                    cabecalho = new List <object>()
                    {
                        "", "Título", "Lançamento", "Plataformas"
                    };
                    break;

                case "Watchlist":
                    lista = game.ListarJogos(new List <int> {
                        0
                    }, 3);
                    cabecalho = new List <object>()
                    {
                        "", "Título", "Lançamento", "Plataformas"
                    };
                    break;

                default:
                    int?plataformas = plataforma.GetIdBySigla(aba);
                    plat = new List <int> {
                        plataformas.Value
                    };
                    lista     = game.ListarJogos(plat, 1);
                    cabecalho = new List <object>()
                    {
                        "", "Título"
                    };
                    break;
                }

                string range = aba + "!A1:D" + lista.Count + 1;

                List <IList <object> > dados = new List <IList <object> >();
                dados.Add(cabecalho);

                foreach (GameView jogo in lista)
                {
                    if (cabecalho.Count == 2)
                    {
                        dados.Add(new List <object>()
                        {
                            "=IMAGE(\"https://images.igdb.com/igdb/image/upload/t_micro/" + jogo.CloudnaryId + ".jpg\")", jogo.Name
                        });
                    }
                    else
                    {
                        string data = null;
                        if (jogo.ReleaseDate != null)
                        {
                            data = jogo.ReleaseDate.Value.ToShortDateString();
                        }
                        dados.Add(new List <object>()
                        {
                            "=IMAGE(\"https://images.igdb.com/igdb/image/upload/t_micro/" + jogo.CloudnaryId + ".jpg\")", jogo.Name, data, String.Join(", ", jogo.Plataformas)
                        });
                    }
                }

                ValueRange valueRange = new ValueRange();
                valueRange.Values = dados;

                SpreadsheetsResource.ValuesResource.UpdateRequest updateRequest = sheetsService.Spreadsheets.Values.Update(valueRange, id, range);
                updateRequest.ValueInputOption = valueInputOption;

                UpdateValuesResponse resposta = updateRequest.Execute();

                Request alignLeftRequest = new Request();
                alignLeftRequest.RepeatCell        = new RepeatCellRequest();
                alignLeftRequest.RepeatCell.Fields = "userEnteredFormat(HorizontalAlignment)";
                alignLeftRequest.RepeatCell.Range  = new GridRange {
                    SheetId = planilha.Properties.SheetId, StartColumnIndex = 2, EndColumnIndex = 3
                };
                alignLeftRequest.RepeatCell.Cell = new CellData {
                    UserEnteredFormat = new CellFormat {
                        HorizontalAlignment = "LEFT"
                    }
                };

                Request alignCenterRequest = new Request();
                alignCenterRequest.RepeatCell        = new RepeatCellRequest();
                alignCenterRequest.RepeatCell.Fields = "userEnteredFormat(HorizontalAlignment)";
                alignCenterRequest.RepeatCell.Range  = new GridRange {
                    SheetId = planilha.Properties.SheetId, StartColumnIndex = 0, EndColumnIndex = 1
                };
                alignCenterRequest.RepeatCell.Cell = new CellData {
                    UserEnteredFormat = new CellFormat {
                        HorizontalAlignment = "Center"
                    }
                };

                Request resizeRequest = new Request();
                resizeRequest.AutoResizeDimensions            = new AutoResizeDimensionsRequest();
                resizeRequest.AutoResizeDimensions.Dimensions = new DimensionRange {
                    SheetId = planilha.Properties.SheetId, Dimension = "COLUMNS", StartIndex = 1, EndIndex = cabecalho.Count
                };

                BatchUpdateSpreadsheetRequest batch = new BatchUpdateSpreadsheetRequest();
                batch.Requests = new List <Request>();
                batch.Requests.Add(alignLeftRequest);
                batch.Requests.Add(alignCenterRequest);
                batch.Requests.Add(resizeRequest);

                SpreadsheetsResource.BatchUpdateRequest u = sheetsService.Spreadsheets.BatchUpdate(batch, id);
                BatchUpdateSpreadsheetResponse          responseResize = u.Execute();
            }
        }
Example #22
0
        public void Load()
        {
            IPlatformRepository iPlatformDAL = new PlatformRepository(this.Client, this.Database);

            Assert.IsTrue(iPlatformDAL.FindAll().Count() > 0);
        }
Example #23
0
        private static void InitializePlatform(IAppBuilder app, IUnityContainer container, string connectionStringName, HangfireLauncher hangfireLauncher)
        {
            container.RegisterType <ICurrentUser, CurrentUser>(new HttpContextLifetimeManager());
            container.RegisterType <IUserNameResolver, UserNameResolver>();

            #region Setup database

            using (var db = new SecurityDbContext(connectionStringName))
            {
                new IdentityDatabaseInitializer().InitializeDatabase(db);
            }

            using (var context = new PlatformRepository(connectionStringName, container.Resolve <AuditableInterceptor>(), new EntityPrimaryKeyGeneratorInterceptor()))
            {
                new PlatformDatabaseInitializer().InitializeDatabase(context);
            }

            hangfireLauncher.ConfigureDatabase();

            #endregion


            Func <IPlatformRepository> platformRepositoryFactory = () => new PlatformRepository(connectionStringName, container.Resolve <AuditableInterceptor>(), new EntityPrimaryKeyGeneratorInterceptor());
            container.RegisterType <IPlatformRepository>(new InjectionFactory(c => platformRepositoryFactory()));
            container.RegisterInstance(platformRepositoryFactory);
            var moduleCatalog    = container.Resolve <IModuleCatalog>();
            var manifestProvider = container.Resolve <IModuleManifestProvider>();

            #region Caching
            var cacheManager = CacheFactory.Build("platformCache", settings =>
            {
                //Should be aware to using Web cache cache handle because it not worked in native threads. (Hangfire jobs)
                settings
                .WithUpdateMode(CacheUpdateMode.Up)
                .WithSystemRuntimeCacheHandle("memCacheHandle")
                .WithExpiration(ExpirationMode.Absolute, TimeSpan.FromDays(1));
            });
            container.RegisterInstance(cacheManager);
            #endregion

            #region Settings

            var platformSettings = new[]
            {
                new ModuleManifest
                {
                    Id              = "VirtoCommerce.Platform",
                    Version         = PlatformVersion.CurrentVersion.ToString(),
                    PlatformVersion = PlatformVersion.CurrentVersion.ToString(),
                    Settings        = new[]
                    {
                        new ModuleSettingsGroup
                        {
                            Name     = "Система|Уведомления|SendGrid",
                            Settings = new []
                            {
                                new ModuleSetting
                                {
                                    Name        = "VirtoCommerce.Platform.Notifications.SendGrid.UserName",
                                    ValueType   = ModuleSetting.TypeString,
                                    Title       = "SendGrid Имя пользователя",
                                    Description = "Имя учетной записи SendGrid"
                                },
                                new ModuleSetting
                                {
                                    Name        = "VirtoCommerce.Platform.Notifications.SendGrid.Secret",
                                    ValueType   = ModuleSetting.TypeString,
                                    Title       = "SendGrid Пароль",
                                    Description = "Пароль учетной записи SendGrid"
                                }
                            }
                        },

                        new ModuleSettingsGroup
                        {
                            Name     = "Система|Уведомления|SendingJob",
                            Settings = new []
                            {
                                new ModuleSetting
                                {
                                    Name        = "VirtoCommerce.Platform.Notifications.SendingJob.TakeCount",
                                    ValueType   = ModuleSetting.TypeInteger,
                                    Title       = "Job Take Count",
                                    Description = "Take count for sending job"
                                }
                            }
                        },

                        new ModuleSettingsGroup
                        {
                            Name     = "Система|Уведомления|SmtpClient",
                            Settings = new []
                            {
                                new ModuleSetting
                                {
                                    Name        = "VirtoCommerce.Platform.Notifications.SmptClient.Host",
                                    ValueType   = ModuleSetting.TypeString,
                                    Title       = "Smtp server host",
                                    Description = "Smtp server host"
                                },
                                new ModuleSetting
                                {
                                    Name        = "VirtoCommerce.Platform.Notifications.SmptClient.Port",
                                    ValueType   = ModuleSetting.TypeInteger,
                                    Title       = "Smtp server port",
                                    Description = "Smtp server port"
                                },
                                new ModuleSetting
                                {
                                    Name        = "VirtoCommerce.Platform.Notifications.SmptClient.Login",
                                    ValueType   = ModuleSetting.TypeString,
                                    Title       = "Smtp server login",
                                    Description = "Smtp server login"
                                },
                                new ModuleSetting
                                {
                                    Name        = "VirtoCommerce.Platform.Notifications.SmptClient.Password",
                                    ValueType   = ModuleSetting.TypeString,
                                    Title       = "Smtp server password",
                                    Description = "Smtp server password"
                                },
                                new ModuleSetting
                                {
                                    Name        = "VirtoCommerce.Platform.Notifications.SmptClient.UseSsl",
                                    ValueType   = ModuleSetting.TypeBoolean,
                                    Title       = "Use SSL",
                                    Description = "Use secure connection"
                                },
                            }
                        },

                        new ModuleSettingsGroup
                        {
                            Name     = "Система|Безопасность",
                            Settings = new []
                            {
                                new ModuleSetting
                                {
                                    Name         = "VirtoCommerce.Platform.Security.AccountTypes",
                                    ValueType    = ModuleSetting.TypeString,
                                    Title        = "Типы учетных записей",
                                    Description  = "Словарь Типов учетных записей",
                                    IsArray      = true,
                                    ArrayValues  = Enum.GetNames(typeof(AccountType)),
                                    DefaultValue = AccountType.CompanyManager.ToString()
                                }
                            }
                        },
                        new ModuleSettingsGroup
                        {
                            Name     = "Система|Пользовательский интерфейс",
                            Settings = new[]
                            {
                                new ModuleSetting
                                {
                                    Name      = "VirtoCommerce.Platform.UI.MainMenu.State",
                                    ValueType = ModuleSetting.TypeText,
                                    Title     = "Persisted state of main menu (JSON)"
                                },
                                new ModuleSetting
                                {
                                    Name         = "VirtoCommerce.Platform.UI.Language",
                                    ValueType    = ModuleSetting.TypeString,
                                    Title        = "Language",
                                    Description  = "Default language (two letter code from ISO 639-1)",
                                    DefaultValue = "ru"
                                }
                            }
                        }
                    }
                }
            };

            var settingsManager = new SettingsManager(manifestProvider, platformRepositoryFactory, cacheManager, platformSettings);
            container.RegisterInstance <ISettingsManager>(settingsManager);

            #endregion

            #region Dynamic Properties

            container.RegisterType <IDynamicPropertyService, DynamicPropertyService>(new ContainerControlledLifetimeManager());

            #endregion

            #region Notifications

            var hubSignalR = GlobalHost.ConnectionManager.GetHubContext <ClientPushHub>();
            var notifier   = new InMemoryPushNotificationManager(hubSignalR);
            container.RegisterInstance <IPushNotificationManager>(notifier);

            var resolver = new LiquidNotificationTemplateResolver();
            container.RegisterInstance <INotificationTemplateResolver>(resolver);

            var notificationTemplateService = new NotificationTemplateServiceImpl(platformRepositoryFactory);
            container.RegisterInstance <INotificationTemplateService>(notificationTemplateService);
            var notificationManager = new NotificationManager(resolver, platformRepositoryFactory, notificationTemplateService);
            container.RegisterInstance <INotificationManager>(notificationManager);
            IEmailNotificationSendingGateway emailNotificationSendingGateway = null;

            var emailNotificationSendingGatewayName = ConfigurationManager.AppSettings.GetValue("VirtoCommerce:Notifications:Gateway", "Default");

            if (string.Equals(emailNotificationSendingGatewayName, "Default", StringComparison.OrdinalIgnoreCase))
            {
                emailNotificationSendingGateway = new DefaultSmtpEmailNotificationSendingGateway(settingsManager);
            }
            else if (string.Equals(emailNotificationSendingGatewayName, "SendGrid", StringComparison.OrdinalIgnoreCase))
            {
                emailNotificationSendingGateway = new SendGridEmailNotificationSendingGateway(settingsManager);
            }

            if (emailNotificationSendingGateway != null)
            {
                container.RegisterInstance(emailNotificationSendingGateway);
            }

            var defaultSmsNotificationSendingGateway = new DefaultSmsNotificationSendingGateway();
            container.RegisterInstance <ISmsNotificationSendingGateway>(defaultSmsNotificationSendingGateway);

            #endregion

            #region Assets

            var blobConnectionString = BlobConnectionString.Parse(ConfigurationManager.ConnectionStrings["AssetsConnectionString"].ConnectionString);

            if (string.Equals(blobConnectionString.Provider, FileSystemBlobProvider.ProviderName, StringComparison.OrdinalIgnoreCase))
            {
                var fileSystemBlobProvider = new FileSystemBlobProvider(NormalizePath(blobConnectionString.RootPath), blobConnectionString.PublicUrl);

                container.RegisterInstance <IBlobStorageProvider>(fileSystemBlobProvider);
                container.RegisterInstance <IBlobUrlResolver>(fileSystemBlobProvider);
            }
            else if (string.Equals(blobConnectionString.Provider, AzureBlobProvider.ProviderName, StringComparison.OrdinalIgnoreCase))
            {
                var azureBlobProvider = new AzureBlobProvider(blobConnectionString.ConnectionString);

                container.RegisterInstance <IBlobStorageProvider>(azureBlobProvider);
                container.RegisterInstance <IBlobUrlResolver>(azureBlobProvider);
            }

            #endregion

            #region Packaging

            var packagesPath   = HostingEnvironment.MapPath(VirtualRoot + "/App_Data/InstalledPackages");
            var packageService = new ZipPackageService(moduleCatalog, manifestProvider, packagesPath);
            container.RegisterInstance <IPackageService>(packageService);

            var uploadsPath = HostingEnvironment.MapPath(VirtualRoot + "/App_Data/Uploads");
            container.RegisterType <ModulesController>(new InjectionConstructor(packageService, uploadsPath, notifier, container.Resolve <IUserNameResolver>()));

            #endregion

            #region ChangeLogging

            var changeLogService = new ChangeLogService(platformRepositoryFactory);
            container.RegisterInstance <IChangeLogService>(changeLogService);

            #endregion

            #region Security
            container.RegisterInstance <IPermissionScopeService>(new PermissionScopeService());
            container.RegisterType <IRoleManagementService, RoleManagementService>(new ContainerControlledLifetimeManager());

            var apiAccountProvider = new ApiAccountProvider(platformRepositoryFactory, cacheManager);
            container.RegisterInstance <IApiAccountProvider>(apiAccountProvider);

            container.RegisterType <IClaimsIdentityProvider, ApplicationClaimsIdentityProvider>(new ContainerControlledLifetimeManager());

            container.RegisterInstance(app.GetDataProtectionProvider());
            container.RegisterType <SecurityDbContext>(new InjectionConstructor(connectionStringName));
            container.RegisterType <IUserStore <ApplicationUser>, ApplicationUserStore>();
            container.RegisterType <IAuthenticationManager>(new InjectionFactory(c => HttpContext.Current.GetOwinContext().Authentication));
            container.RegisterType <ApplicationUserManager>();
            container.RegisterType <ApplicationSignInManager>();

            var nonEditableUsers = ConfigurationManager.AppSettings.GetValue("VirtoCommerce:NonEditableUsers", string.Empty);
            container.RegisterInstance <ISecurityOptions>(new SecurityOptions(nonEditableUsers));

            container.RegisterType <ISecurityService, SecurityService>();

            #endregion

            #region ExportImport
            container.RegisterType <IPlatformExportImportManager, PlatformExportImportManager>();
            #endregion

            #region Serialization

            container.RegisterType <IExpressionSerializer, XmlExpressionSerializer>();

            #endregion
        }
        public void Load()
        {
            IPlatformRepository iPlatformDAL = new PlatformRepository(this.Client, this.Database);

            Assert.IsTrue(iPlatformDAL.FindAll().Count() > 0);
        }
Example #25
0
        private static void InitializePlatform(IAppBuilder app, IUnityContainer container, string connectionStringName, HangfireLauncher hangfireLauncher, string modulesPath)
        {
            container.RegisterType <ICurrentUser, CurrentUser>(new HttpContextLifetimeManager());
            container.RegisterType <IUserNameResolver, UserNameResolver>();

            #region Setup database

            using (var db = new SecurityDbContext(connectionStringName))
            {
                new IdentityDatabaseInitializer().InitializeDatabase(db);
            }

            using (var context = new PlatformRepository(connectionStringName, container.Resolve <AuditableInterceptor>(), new EntityPrimaryKeyGeneratorInterceptor()))
            {
                new PlatformDatabaseInitializer().InitializeDatabase(context);
            }

            hangfireLauncher.ConfigureDatabase();

            #endregion

            Func <IPlatformRepository> platformRepositoryFactory = () => new PlatformRepository(connectionStringName, container.Resolve <AuditableInterceptor>(), new EntityPrimaryKeyGeneratorInterceptor());
            container.RegisterType <IPlatformRepository>(new InjectionFactory(c => platformRepositoryFactory()));
            container.RegisterInstance(platformRepositoryFactory);
            var moduleCatalog = container.Resolve <IModuleCatalog>();

            #region Caching

            //Cure for System.Runtime.Caching.MemoryCache freezing
            //https://www.zpqrtbnk.net/posts/appdomains-threads-cultureinfos-and-paracetamol
            app.SanitizeThreadCulture();
            ICacheManager <object> cacheManager = null;

            //Try to load cache configuration from web.config first
            //Should be aware to using Web cache cache handle because it not worked in native threads. (Hangfire jobs)
            var cacheManagerSection = ConfigurationManager.GetSection(CacheManagerSection.DefaultSectionName) as CacheManagerSection;
            if (cacheManagerSection != null && cacheManagerSection.CacheManagers.Any(p => p.Name.EqualsInvariant("platformCache")))
            {
                var configuration = ConfigurationBuilder.LoadConfiguration("platformCache") as CacheManagerConfiguration;

                if (configuration != null)
                {
                    configuration.LoggerFactoryType          = typeof(CacheManagerLoggerFactory);
                    configuration.LoggerFactoryTypeArguments = new[] { container.Resolve <ILog>() };
                    cacheManager = CacheFactory.FromConfiguration <object>(configuration);
                }
            }
            if (cacheManager == null)
            {
                cacheManager = CacheFactory.Build("platformCache", settings =>
                {
                    settings.WithUpdateMode(CacheUpdateMode.Up)
                    .WithSystemRuntimeCacheHandle("memCacheHandle")
                    .WithExpiration(ExpirationMode.Sliding, TimeSpan.FromMinutes(5));
                });
            }

            container.RegisterInstance(cacheManager);

            #endregion

            #region Settings

            var platformModuleManifest = new ModuleManifest
            {
                Id              = "VirtoCommerce.Platform",
                Version         = PlatformVersion.CurrentVersion.ToString(),
                PlatformVersion = PlatformVersion.CurrentVersion.ToString(),
                Settings        = new[]
                {
                    new ModuleSettingsGroup
                    {
                        Name     = "Platform|Notifications|SendGrid",
                        Settings = new []
                        {
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.Notifications.SendGrid.ApiKey",
                                ValueType   = ModuleSetting.TypeSecureString,
                                Title       = "SendGrid API key",
                                Description = "Your SendGrid API key"
                            }
                        }
                    },
                    new ModuleSettingsGroup
                    {
                        Name     = "Platform|Notifications|SendingJob",
                        Settings = new []
                        {
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.Notifications.SendingJob.TakeCount",
                                ValueType   = ModuleSetting.TypeInteger,
                                Title       = "Job Take Count",
                                Description = "Take count for sending job"
                            }
                        }
                    },
                    new ModuleSettingsGroup
                    {
                        Name     = "Platform|Notifications|SmtpClient",
                        Settings = new []
                        {
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.Notifications.SmptClient.Host",
                                ValueType   = ModuleSetting.TypeString,
                                Title       = "Smtp server host",
                                Description = "Smtp server host"
                            },
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.Notifications.SmptClient.Port",
                                ValueType   = ModuleSetting.TypeInteger,
                                Title       = "Smtp server port",
                                Description = "Smtp server port"
                            },
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.Notifications.SmptClient.Login",
                                ValueType   = ModuleSetting.TypeString,
                                Title       = "Smtp server login",
                                Description = "Smtp server login"
                            },
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.Notifications.SmptClient.Password",
                                ValueType   = ModuleSetting.TypeSecureString,
                                Title       = "Smtp server password",
                                Description = "Smtp server password"
                            },
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.Notifications.SmptClient.UseSsl",
                                ValueType   = ModuleSetting.TypeBoolean,
                                Title       = "Use SSL",
                                Description = "Use secure connection"
                            },
                        }
                    },
                    new ModuleSettingsGroup
                    {
                        Name     = "Platform|Security",
                        Settings = new []
                        {
                            new ModuleSetting
                            {
                                Name         = "VirtoCommerce.Platform.Security.AccountTypes",
                                ValueType    = ModuleSetting.TypeString,
                                Title        = "Account types",
                                Description  = "Dictionary for possible account types",
                                IsArray      = true,
                                ArrayValues  = Enum.GetNames(typeof(AccountType)),
                                DefaultValue = AccountType.Manager.ToString()
                            }
                        }
                    },
                    new ModuleSettingsGroup
                    {
                        Name     = "Platform|User Profile",
                        Settings = new[]
                        {
                            new ModuleSetting
                            {
                                Name      = "VirtoCommerce.Platform.UI.MainMenu.State",
                                ValueType = ModuleSetting.TypeJson,
                                Title     = "Persisted state of main menu"
                            },
                            new ModuleSetting
                            {
                                Name         = "VirtoCommerce.Platform.UI.Language",
                                ValueType    = ModuleSetting.TypeString,
                                Title        = "Language",
                                Description  = "Default language (two letter code from ISO 639-1, case-insensitive). Example: en, de",
                                DefaultValue = "en"
                            },
                            new ModuleSetting
                            {
                                Name         = "VirtoCommerce.Platform.UI.RegionalFormat",
                                ValueType    = ModuleSetting.TypeString,
                                Title        = "Regional format",
                                Description  = "Default regional format (CLDR locale code, with dash or underscore as delemiter, case-insensitive). Example: en, en_US, sr_Cyrl, sr_Cyrl_RS",
                                DefaultValue = "en"
                            },
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.UI.TimeZone",
                                ValueType   = ModuleSetting.TypeString,
                                Title       = "Time zone",
                                Description = "Default time zone (IANA time zone name [tz database], exactly as in database, case-sensitive). Examples: America/New_York, Europe/Moscow"
                            },
                            new ModuleSetting
                            {
                                Name         = "VirtoCommerce.Platform.UI.UseTimeAgo",
                                ValueType    = ModuleSetting.TypeBoolean,
                                Title        = "Use time ago format when is possible",
                                Description  = "When set to true (by default), system will display date in format like 'a few seconds ago' when possible",
                                DefaultValue = true.ToString()
                            },
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.UI.FullDateThreshold",
                                ValueType   = ModuleSetting.TypeInteger,
                                Title       = "Full date threshold",
                                Description = "Number of units after time ago format will be switched to full date format"
                            },
                            new ModuleSetting
                            {
                                Name          = "VirtoCommerce.Platform.UI.FullDateThresholdUnit",
                                ValueType     = ModuleSetting.TypeString,
                                Title         = "Full date threshold unit",
                                Description   = "Unit of full date threshold",
                                DefaultValue  = "Never",
                                AllowedValues = new[]
                                {
                                    "Never",
                                    "Seconds",
                                    "Minutes",
                                    "Hours",
                                    "Days",
                                    "Weeks",
                                    "Months",
                                    "Quarters",
                                    "Years"
                                }
                            }
                        }
                    },
                    new ModuleSettingsGroup
                    {
                        Name     = "Platform|User Interface",
                        Settings = new[]
                        {
                            new ModuleSetting
                            {
                                Name         = "VirtoCommerce.Platform.UI.Customization",
                                ValueType    = ModuleSetting.TypeJson,
                                Title        = "Customization",
                                Description  = "JSON contains personalization settings of manager UI",
                                DefaultValue = "{\n" +
                                               "  \"title\": \"Virto Commerce\",\n" +
                                               "  \"logo\": \"Content/themes/main/images/logo.png\",\n" +
                                               "  \"contrast_logo\": \"Content/themes/main/images/contrast-logo.png\"\n" +
                                               "}"
                            }
                        }
                    }
                }
            };

            var settingsManager = new SettingsManager(moduleCatalog, platformRepositoryFactory, cacheManager, new[] { new ManifestModuleInfo(platformModuleManifest) });
            container.RegisterInstance <ISettingsManager>(settingsManager);

            #endregion

            #region Dynamic Properties

            container.RegisterType <IDynamicPropertyService, DynamicPropertyService>(new ContainerControlledLifetimeManager());

            #endregion

            #region Notifications

            var hubSignalR = GlobalHost.ConnectionManager.GetHubContext <ClientPushHub>();
            var notifier   = new InMemoryPushNotificationManager(hubSignalR);
            container.RegisterInstance <IPushNotificationManager>(notifier);

            var resolver = new LiquidNotificationTemplateResolver();
            container.RegisterInstance <INotificationTemplateResolver>(resolver);

            var notificationTemplateService = new NotificationTemplateServiceImpl(platformRepositoryFactory);
            container.RegisterInstance <INotificationTemplateService>(notificationTemplateService);

            var notificationManager = new NotificationManager(resolver, platformRepositoryFactory, notificationTemplateService);
            container.RegisterInstance <INotificationManager>(notificationManager);

            IEmailNotificationSendingGateway emailNotificationSendingGateway = null;

            var emailNotificationSendingGatewayName = ConfigurationManager.AppSettings.GetValue("VirtoCommerce:Notifications:Gateway", "Default");

            if (string.Equals(emailNotificationSendingGatewayName, "Default", StringComparison.OrdinalIgnoreCase))
            {
                emailNotificationSendingGateway = new DefaultSmtpEmailNotificationSendingGateway(settingsManager);
            }
            else if (string.Equals(emailNotificationSendingGatewayName, "SendGrid", StringComparison.OrdinalIgnoreCase))
            {
                emailNotificationSendingGateway = new SendGridEmailNotificationSendingGateway(settingsManager);
            }

            if (emailNotificationSendingGateway != null)
            {
                container.RegisterInstance(emailNotificationSendingGateway);
            }

            var defaultSmsNotificationSendingGateway = new DefaultSmsNotificationSendingGateway();
            container.RegisterInstance <ISmsNotificationSendingGateway>(defaultSmsNotificationSendingGateway);

            #endregion

            #region Assets

            var blobConnectionString = BlobConnectionString.Parse(ConfigurationManager.ConnectionStrings["AssetsConnectionString"].ConnectionString);

            if (string.Equals(blobConnectionString.Provider, FileSystemBlobProvider.ProviderName, StringComparison.OrdinalIgnoreCase))
            {
                var fileSystemBlobProvider = new FileSystemBlobProvider(NormalizePath(blobConnectionString.RootPath), blobConnectionString.PublicUrl);

                container.RegisterInstance <IBlobStorageProvider>(fileSystemBlobProvider);
                container.RegisterInstance <IBlobUrlResolver>(fileSystemBlobProvider);
            }
            else if (string.Equals(blobConnectionString.Provider, AzureBlobProvider.ProviderName, StringComparison.OrdinalIgnoreCase))
            {
                var azureBlobProvider = new AzureBlobProvider(blobConnectionString.ConnectionString);
                container.RegisterInstance <IBlobStorageProvider>(azureBlobProvider);
                container.RegisterInstance <IBlobUrlResolver>(azureBlobProvider);
            }


            #endregion

            #region Modularity

            var modulesDataSources    = ConfigurationManager.AppSettings.SplitStringValue("VirtoCommerce:ModulesDataSources");
            var externalModuleCatalog = new ExternalManifestModuleCatalog(moduleCatalog.Modules, modulesDataSources, container.Resolve <ILog>());
            container.RegisterType <ModulesController>(new InjectionConstructor(externalModuleCatalog, new ModuleInstaller(modulesPath, externalModuleCatalog), notifier, container.Resolve <IUserNameResolver>(), settingsManager));

            #endregion

            #region ChangeLogging

            var changeLogService = new ChangeLogService(platformRepositoryFactory);
            container.RegisterInstance <IChangeLogService>(changeLogService);

            #endregion

            #region Security
            container.RegisterInstance <IPermissionScopeService>(new PermissionScopeService());
            container.RegisterType <IRoleManagementService, RoleManagementService>(new ContainerControlledLifetimeManager());

            var apiAccountProvider = new ApiAccountProvider(platformRepositoryFactory, cacheManager);
            container.RegisterInstance <IApiAccountProvider>(apiAccountProvider);

            container.RegisterType <IClaimsIdentityProvider, ApplicationClaimsIdentityProvider>(new ContainerControlledLifetimeManager());

            container.RegisterInstance(app.GetDataProtectionProvider());
            container.RegisterType <SecurityDbContext>(new InjectionConstructor(connectionStringName));
            container.RegisterType <IUserStore <ApplicationUser>, ApplicationUserStore>();
            container.RegisterType <IAuthenticationManager>(new InjectionFactory(c => HttpContext.Current.GetOwinContext().Authentication));
            container.RegisterType <ApplicationUserManager>();
            container.RegisterType <ApplicationSignInManager>();

            var nonEditableUsers = ConfigurationManager.AppSettings.GetValue("VirtoCommerce:NonEditableUsers", string.Empty);
            container.RegisterInstance <ISecurityOptions>(new SecurityOptions(nonEditableUsers));

            container.RegisterType <ISecurityService, SecurityService>();

            #endregion

            #region ExportImport
            container.RegisterType <IPlatformExportImportManager, PlatformExportImportManager>();
            #endregion

            #region Serialization

            container.RegisterType <IExpressionSerializer, XmlExpressionSerializer>();

            #endregion
        }
        public void Save_Platforms_Against_An_Application()
        {
            IApplicationRepository applicationRepository = new ApplicationRepository(this.Client, this.Database);
            IPlatformRepository iPlatformDAL = new PlatformRepository(this.Client, this.Database);

            Application application = new Application(Guid.NewGuid().ToString());
            application.Platforms = iPlatformDAL.FindAll().ToList();
            applicationRepository.Save(application);

            Application applicationFound = applicationRepository.Find(application.Guid);
            Assert.IsNotNull(applicationFound.Platforms);
            Assert.IsTrue(applicationFound.Platforms.Count == application.Platforms.Count);
        }
        private static IPlatformRepository GetPlatformRepository()
        {
            var result = new PlatformRepository("VirtoCommerce", new EntityPrimaryKeyGeneratorInterceptor(), new AuditableInterceptor(null));

            return(result);
        }
Example #28
0
        private static void InitializePlatform(IUnityContainer container, string connectionStringName)
        {
            #region Setup database

            using (var db = new SecurityDbContext(connectionStringName))
            {
                new IdentityDatabaseInitializer().InitializeDatabase(db);
            }

            using (var context = new PlatformRepository(connectionStringName, new AuditableInterceptor(), new EntityPrimaryKeyGeneratorInterceptor()))
            {
                new PlatformDatabaseInitializer().InitializeDatabase(context);
            }

            // Create Hangfire tables
            new SqlServerStorage(connectionStringName);

            #endregion

            Func <IPlatformRepository> platformRepositoryFactory = () => new PlatformRepository(connectionStringName, new AuditableInterceptor(), new EntityPrimaryKeyGeneratorInterceptor());
            container.RegisterType <IPlatformRepository>(new InjectionFactory(c => platformRepositoryFactory()));
            container.RegisterInstance <Func <IPlatformRepository> >(platformRepositoryFactory);
            var moduleCatalog    = container.Resolve <IModuleCatalog>();
            var manifestProvider = container.Resolve <IModuleManifestProvider>();

            #region Caching

            var cacheProvider = new HttpCacheProvider();
            var cacheSettings = new[]
            {
                new CacheSettings(CacheGroups.Settings, TimeSpan.FromDays(1)),
                new CacheSettings(CacheGroups.Security, TimeSpan.FromMinutes(1)),
            };

            var cacheManager = new CacheManager(cacheProvider, cacheSettings);
            container.RegisterInstance <CacheManager>(cacheManager);

            #endregion

            #region Settings

            var platformSettings = new[]
            {
                new ModuleManifest
                {
                    Settings = new[]
                    {
                        new ModuleSettingsGroup
                        {
                            Name     = "Platform|Notifications|SendGrid",
                            Settings = new []
                            {
                                new ModuleSetting
                                {
                                    Name        = "VirtoCommerce.Platform.Notifications.SendGrid.UserName",
                                    ValueType   = ModuleSetting.TypeString,
                                    Title       = "SendGrid UserName",
                                    Description = "Your SendGrid account username"
                                },
                                new ModuleSetting
                                {
                                    Name        = "VirtoCommerce.Platform.Notifications.SendGrid.Secret",
                                    ValueType   = ModuleSetting.TypeString,
                                    Title       = "SendGrid Password",
                                    Description = "Your SendGrid account password"
                                }
                            }
                        },

                        new ModuleSettingsGroup
                        {
                            Name     = "Platform|Notifications|SendingJob",
                            Settings = new []
                            {
                                new ModuleSetting
                                {
                                    Name        = "VirtoCommerce.Platform.Notifications.SendingJob.TakeCount",
                                    ValueType   = ModuleSetting.TypeInteger,
                                    Title       = "Job Take Count",
                                    Description = "Take count for sending job"
                                }
                            }
                        }
                    }
                }
            };

            var settingsManager = new SettingsManager(manifestProvider, platformRepositoryFactory, cacheManager, platformSettings);
            container.RegisterInstance <ISettingsManager>(settingsManager);

            #endregion

            #region Dynamic Properties

            container.RegisterType <IDynamicPropertyService, DynamicPropertyService>();

            #endregion

            #region Notifications

            var hubSignalR = GlobalHost.ConnectionManager.GetHubContext <ClientPushHub>();
            var notifier   = new InMemoryNotifierImpl(hubSignalR);
            container.RegisterInstance <INotifier>(notifier);

            var resolver = new LiquidNotificationTemplateResolver();
            var notificationTemplateService = new NotificationTemplateServiceImpl(platformRepositoryFactory);
            var notificationManager         = new NotificationManager(resolver, platformRepositoryFactory, notificationTemplateService);

            var emailNotificationSendingGateway = new DefaultEmailNotificationSendingGateway(settingsManager);

            var defaultSmsNotificationSendingGateway = new DefaultSmsNotificationSendingGateway();

            container.RegisterInstance <INotificationTemplateService>(notificationTemplateService);
            container.RegisterInstance <INotificationManager>(notificationManager);
            container.RegisterInstance <INotificationTemplateResolver>(resolver);
            container.RegisterInstance <IEmailNotificationSendingGateway>(emailNotificationSendingGateway);
            container.RegisterInstance <ISmsNotificationSendingGateway>(defaultSmsNotificationSendingGateway);

            //notificationManager.RegisterNotificationType(
            //	() => new RegistrationSmsNotification(defaultSmsNotificationSendingGateway)
            //	{
            //		DisplayName = "Registration notification",
            //		Description = "This notification sends by sms to client when he finish registration",
            //		ObjectId = "Platform",
            //		NotificationTemplate = new NotificationTemplate
            //		{
            //			Body = @"Dear {{ context.first_name }} {{ context.last_name }}, you has registered on our site. Your login  - {{ context.login }} Your login - {{ context.password }}",
            //			Subject = @"",
            //			NotificationTypeId = "RegistrationSmsNotification",
            //			ObjectId = "Platform"
            //		}
            //	}
            //);

            #endregion

            #region Assets

            var assetsConnection = ConfigurationManager.ConnectionStrings["AssetsConnectionString"];

            if (assetsConnection != null)
            {
                var properties             = assetsConnection.ConnectionString.ToDictionary(";", "=");
                var provider               = properties["provider"];
                var assetsConnectionString = properties.ToString(";", "=", "provider");

                if (string.Equals(provider, FileSystemBlobProvider.ProviderName, StringComparison.OrdinalIgnoreCase))
                {
                    var fileSystemBlobProvider = new FileSystemBlobProvider(assetsConnectionString);

                    container.RegisterInstance <IBlobStorageProvider>(fileSystemBlobProvider);
                    container.RegisterInstance <IBlobUrlResolver>(fileSystemBlobProvider);
                }
                else if (string.Equals(provider, AzureBlobProvider.ProviderName, StringComparison.OrdinalIgnoreCase))
                {
                    var azureBlobProvider = new AzureBlobProvider(assetsConnectionString);

                    container.RegisterInstance <IBlobStorageProvider>(azureBlobProvider);
                    container.RegisterInstance <IBlobUrlResolver>(azureBlobProvider);
                }
            }

            #endregion

            #region Packaging

            var sourcePath   = HostingEnvironment.MapPath("~/App_Data/SourcePackages");
            var packagesPath = HostingEnvironment.MapPath("~/App_Data/InstalledPackages");

            var packageService = new ZipPackageService(moduleCatalog, manifestProvider, packagesPath, sourcePath);
            container.RegisterInstance <IPackageService>(packageService);
            container.RegisterType <ModulesController>(new InjectionConstructor(packageService, sourcePath));

            #endregion

            #region ChangeLogging

            var changeLogService = new ChangeLogService(platformRepositoryFactory);
            container.RegisterInstance <IChangeLogService>(changeLogService);

            #endregion

            #region Security

            var permissionService = new PermissionService(platformRepositoryFactory, manifestProvider, cacheManager);
            container.RegisterInstance <IPermissionService>(permissionService);

            container.RegisterType <IRoleManagementService, RoleManagementService>(new ContainerControlledLifetimeManager());

            var apiAccountProvider = new ApiAccountProvider(platformRepositoryFactory, cacheManager);
            container.RegisterInstance <IApiAccountProvider>(apiAccountProvider);

            container.RegisterType <IClaimsIdentityProvider, ApplicationClaimsIdentityProvider>(new ContainerControlledLifetimeManager());

            container.RegisterType <ApplicationSignInManager>(new InjectionFactory(c => HttpContext.Current.GetOwinContext().Get <ApplicationSignInManager>()));
            container.RegisterType <ApplicationUserManager>(new InjectionFactory(c => HttpContext.Current.GetOwinContext().GetUserManager <ApplicationUserManager>()));
            container.RegisterType <IAuthenticationManager>(new InjectionFactory(c => HttpContext.Current.GetOwinContext().Authentication));

            container.RegisterType <ISecurityService, SecurityService>();

            #endregion

            #region ExportImport
            container.RegisterType <IPlatformExportImportManager, PlatformExportImportManager>();
            #endregion
        }
Example #29
0
        private static void InitializePlatform(IAppBuilder app, IUnityContainer container, string connectionStringName, HangfireLauncher hangfireLauncher, string modulesPath)
        {
            container.RegisterType <ICurrentUser, CurrentUser>(new HttpContextLifetimeManager());
            container.RegisterType <IUserNameResolver, UserNameResolver>();

            #region Setup database

            using (var db = new SecurityDbContext(connectionStringName))
            {
                new IdentityDatabaseInitializer().InitializeDatabase(db);
            }

            using (var context = new PlatformRepository(connectionStringName, container.Resolve <AuditableInterceptor>(), new EntityPrimaryKeyGeneratorInterceptor()))
            {
                new PlatformDatabaseInitializer().InitializeDatabase(context);
            }

            hangfireLauncher.ConfigureDatabase();

            #endregion


            Func <IPlatformRepository> platformRepositoryFactory = () => new PlatformRepository(connectionStringName, container.Resolve <AuditableInterceptor>(), new EntityPrimaryKeyGeneratorInterceptor());
            container.RegisterType <IPlatformRepository>(new InjectionFactory(c => platformRepositoryFactory()));
            container.RegisterInstance(platformRepositoryFactory);
            var moduleCatalog = container.Resolve <IModuleCatalog>();

            #region Caching
            ICacheManager <object> cacheManager = null;
            //Try to load cache configuration from web.config first
            if (ConfigurationManager.GetSection(CacheManagerSection.DefaultSectionName) != null)
            {
                cacheManager = CacheFactory.FromConfiguration <object>("platformCache");
            }
            else
            {
                cacheManager = CacheFactory.Build("platformCache", settings =>
                {
                    //Should be aware to using Web cache cache handle because it not worked in native threads. (Hangfire jobs)
                    settings.WithUpdateMode(CacheUpdateMode.Up)
                    .WithSystemRuntimeCacheHandle("memCacheHandle")
                    .WithExpiration(ExpirationMode.Absolute, TimeSpan.FromDays(1));
                });
            }
            container.RegisterInstance(cacheManager);
            #endregion

            #region Settings

            var platformModuleManifest = new ModuleManifest
            {
                Id              = "VirtoCommerce.Platform",
                Version         = PlatformVersion.CurrentVersion.ToString(),
                PlatformVersion = PlatformVersion.CurrentVersion.ToString(),
                Settings        = new[]
                {
                    new ModuleSettingsGroup
                    {
                        Name     = "Platform|Notifications|SendGrid",
                        Settings = new []
                        {
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.Notifications.SendGrid.ApiKey",
                                ValueType   = ModuleSetting.TypeString,
                                Title       = "SendGrid API key",
                                Description = "Your SendGrid API key"
                            }
                        }
                    },
                    new ModuleSettingsGroup
                    {
                        Name     = "Platform|Notifications|SendingJob",
                        Settings = new []
                        {
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.Notifications.SendingJob.TakeCount",
                                ValueType   = ModuleSetting.TypeInteger,
                                Title       = "Job Take Count",
                                Description = "Take count for sending job"
                            }
                        }
                    },
                    new ModuleSettingsGroup
                    {
                        Name     = "Platform|Notifications|SmtpClient",
                        Settings = new []
                        {
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.Notifications.SmptClient.Host",
                                ValueType   = ModuleSetting.TypeString,
                                Title       = "Smtp server host",
                                Description = "Smtp server host"
                            },
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.Notifications.SmptClient.Port",
                                ValueType   = ModuleSetting.TypeInteger,
                                Title       = "Smtp server port",
                                Description = "Smtp server port"
                            },
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.Notifications.SmptClient.Login",
                                ValueType   = ModuleSetting.TypeString,
                                Title       = "Smtp server login",
                                Description = "Smtp server login"
                            },
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.Notifications.SmptClient.Password",
                                ValueType   = ModuleSetting.TypeSecureString,
                                Title       = "Smtp server password",
                                Description = "Smtp server password"
                            },
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.Notifications.SmptClient.UseSsl",
                                ValueType   = ModuleSetting.TypeBoolean,
                                Title       = "Use SSL",
                                Description = "Use secure connection"
                            },
                        }
                    },
                    new ModuleSettingsGroup
                    {
                        Name     = "Platform|Security",
                        Settings = new []
                        {
                            new ModuleSetting
                            {
                                Name         = "VirtoCommerce.Platform.Security.AccountTypes",
                                ValueType    = ModuleSetting.TypeString,
                                Title        = "Account types",
                                Description  = "Dictionary for possible account types",
                                IsArray      = true,
                                ArrayValues  = Enum.GetNames(typeof(AccountType)),
                                DefaultValue = AccountType.Manager.ToString()
                            }
                        }
                    },
                    new ModuleSettingsGroup
                    {
                        Name     = "Platform|User Profile",
                        Settings = new[]
                        {
                            new ModuleSetting
                            {
                                Name      = "VirtoCommerce.Platform.UI.MainMenu.State",
                                ValueType = ModuleSetting.TypeJson,
                                Title     = "Persisted state of main menu"
                            },
                            new ModuleSetting
                            {
                                Name         = "VirtoCommerce.Platform.UI.Language",
                                ValueType    = ModuleSetting.TypeString,
                                Title        = "Language",
                                Description  = "Default language (two letter code from ISO 639-1)",
                                DefaultValue = "en"
                            }
                        }
                    },
                    new ModuleSettingsGroup
                    {
                        Name     = "Platform|User Interface",
                        Settings = new[]
                        {
                            new ModuleSetting
                            {
                                Name         = "VirtoCommerce.Platform.UI.Customization",
                                ValueType    = ModuleSetting.TypeJson,
                                Title        = "Customization",
                                Description  = "JSON contains personalization settings of manager UI",
                                DefaultValue = "{\n" +
                                               "  \"title\": \"Virto Commerce\",\n" +
                                               "  \"logo\": \"Content/themes/main/images/logo.png\",\n" +
                                               "  \"contrast_logo\": \"Content/themes/main/images/contrast-logo.png\"\n" +
                                               "}"
                            }
                        }
                    }
                }
            };

            var settingsManager = new SettingsManager(moduleCatalog, platformRepositoryFactory, cacheManager, new[] { new ManifestModuleInfo(platformModuleManifest) });
            container.RegisterInstance <ISettingsManager>(settingsManager);

            #endregion

            #region Dynamic Properties

            container.RegisterType <IDynamicPropertyService, DynamicPropertyService>(new ContainerControlledLifetimeManager());

            #endregion

            #region Notifications

            var hubSignalR = GlobalHost.ConnectionManager.GetHubContext <ClientPushHub>();
            var notifier   = new InMemoryPushNotificationManager(hubSignalR);
            container.RegisterInstance <IPushNotificationManager>(notifier);

            var resolver = new LiquidNotificationTemplateResolver();
            container.RegisterInstance <INotificationTemplateResolver>(resolver);

            var notificationTemplateService = new NotificationTemplateServiceImpl(platformRepositoryFactory);
            container.RegisterInstance <INotificationTemplateService>(notificationTemplateService);

            var notificationManager = new NotificationManager(resolver, platformRepositoryFactory, notificationTemplateService);
            container.RegisterInstance <INotificationManager>(notificationManager);

            IEmailNotificationSendingGateway emailNotificationSendingGateway = null;

            var emailNotificationSendingGatewayName = ConfigurationManager.AppSettings.GetValue("VirtoCommerce:Notifications:Gateway", "Default");

            if (string.Equals(emailNotificationSendingGatewayName, "Default", StringComparison.OrdinalIgnoreCase))
            {
                emailNotificationSendingGateway = new DefaultSmtpEmailNotificationSendingGateway(settingsManager);
            }
            else if (string.Equals(emailNotificationSendingGatewayName, "SendGrid", StringComparison.OrdinalIgnoreCase))
            {
                emailNotificationSendingGateway = new SendGridEmailNotificationSendingGateway(settingsManager);
            }

            if (emailNotificationSendingGateway != null)
            {
                container.RegisterInstance(emailNotificationSendingGateway);
            }

            var defaultSmsNotificationSendingGateway = new DefaultSmsNotificationSendingGateway();
            container.RegisterInstance <ISmsNotificationSendingGateway>(defaultSmsNotificationSendingGateway);

            #endregion

            #region Assets

            var blobConnectionString = BlobConnectionString.Parse(ConfigurationManager.ConnectionStrings["AssetsConnectionString"].ConnectionString);

            if (string.Equals(blobConnectionString.Provider, FileSystemBlobProvider.ProviderName, StringComparison.OrdinalIgnoreCase))
            {
                var fileSystemBlobProvider = new FileSystemBlobProvider(NormalizePath(blobConnectionString.RootPath), blobConnectionString.PublicUrl);

                container.RegisterInstance <IBlobStorageProvider>(fileSystemBlobProvider);
                container.RegisterInstance <IBlobUrlResolver>(fileSystemBlobProvider);
            }
            else if (string.Equals(blobConnectionString.Provider, AzureBlobProvider.ProviderName, StringComparison.OrdinalIgnoreCase))
            {
                var azureBlobProvider = new AzureBlobProvider(blobConnectionString.ConnectionString);
                container.RegisterInstance <IBlobStorageProvider>(azureBlobProvider);
                container.RegisterInstance <IBlobUrlResolver>(azureBlobProvider);
            }


            #endregion

            #region Modularity

            var modulesDataSources    = ConfigurationManager.AppSettings.SplitStringValue("VirtoCommerce:ModulesDataSources");
            var externalModuleCatalog = new ExternalManifestModuleCatalog(moduleCatalog.Modules, modulesDataSources, container.Resolve <ILog>());
            container.RegisterType <ModulesController>(new InjectionConstructor(externalModuleCatalog, new ModuleInstaller(modulesPath, externalModuleCatalog), notifier, container.Resolve <IUserNameResolver>(), settingsManager));

            #endregion

            #region ChangeLogging

            var changeLogService = new ChangeLogService(platformRepositoryFactory);
            container.RegisterInstance <IChangeLogService>(changeLogService);

            #endregion

            #region Security
            container.RegisterInstance <IPermissionScopeService>(new PermissionScopeService());
            container.RegisterType <IRoleManagementService, RoleManagementService>(new ContainerControlledLifetimeManager());

            var apiAccountProvider = new ApiAccountProvider(platformRepositoryFactory, cacheManager);
            container.RegisterInstance <IApiAccountProvider>(apiAccountProvider);

            container.RegisterType <IClaimsIdentityProvider, ApplicationClaimsIdentityProvider>(new ContainerControlledLifetimeManager());

            container.RegisterInstance(app.GetDataProtectionProvider());
            container.RegisterType <SecurityDbContext>(new InjectionConstructor(connectionStringName));
            container.RegisterType <IUserStore <ApplicationUser>, ApplicationUserStore>();
            container.RegisterType <IAuthenticationManager>(new InjectionFactory(c => HttpContext.Current.GetOwinContext().Authentication));
            container.RegisterType <ApplicationUserManager>();
            container.RegisterType <ApplicationSignInManager>();

            var nonEditableUsers = ConfigurationManager.AppSettings.GetValue("VirtoCommerce:NonEditableUsers", string.Empty);
            container.RegisterInstance <ISecurityOptions>(new SecurityOptions(nonEditableUsers));

            container.RegisterType <ISecurityService, SecurityService>();

            #endregion

            #region ExportImport
            container.RegisterType <IPlatformExportImportManager, PlatformExportImportManager>();
            #endregion

            #region Serialization

            container.RegisterType <IExpressionSerializer, XmlExpressionSerializer>();

            #endregion
        }
 public PlatformManager()
 {
     platformRepository = new PlatformRepository();
 }
Example #31
0
        private static void InitializePlatform(
            IAppBuilder app,
            IUnityContainer container,
            IPathMapper pathMapper,
            string connectionString,
            HangfireLauncher hangfireLauncher,
            string modulesPath,
            ModuleInitializerOptions moduleInitializerOptions)
        {
            container.RegisterType <ICurrentUser, CurrentUser>(new HttpContextLifetimeManager());
            container.RegisterType <IUserNameResolver, UserNameResolver>();

            #region Setup database

            using (var db = new SecurityDbContext(connectionString))
            {
                new IdentityDatabaseInitializer().InitializeDatabase(db);
            }

            using (var context = new PlatformRepository(connectionString, container.Resolve <AuditableInterceptor>(), new EntityPrimaryKeyGeneratorInterceptor()))
            {
                new PlatformDatabaseInitializer().InitializeDatabase(context);
            }

            hangfireLauncher.ConfigureDatabase();

            #endregion

            Func <IPlatformRepository> platformRepositoryFactory = () => new PlatformRepository(connectionString, container.Resolve <AuditableInterceptor>(), new EntityPrimaryKeyGeneratorInterceptor());
            container.RegisterType <IPlatformRepository>(new InjectionFactory(c => platformRepositoryFactory()));
            container.RegisterInstance(platformRepositoryFactory);
            var moduleCatalog = container.Resolve <IModuleCatalog>();

            #region Caching

            //Cure for System.Runtime.Caching.MemoryCache freezing
            //https://www.zpqrtbnk.net/posts/appdomains-threads-cultureinfos-and-paracetamol
            app.SanitizeThreadCulture();
            ICacheManager <object> cacheManager = null;

            var redisConnectionString = ConfigurationHelper.GetConnectionStringValue("RedisConnectionString");

            //Try to load cache configuration from web.config first
            //Should be aware to using Web cache cache handle because it not worked in native threads. (Hangfire jobs)
            if (ConfigurationManager.GetSection(CacheManagerSection.DefaultSectionName) is CacheManagerSection cacheManagerSection)
            {
                CacheManagerConfiguration configuration = null;

                var defaultCacheManager = cacheManagerSection.CacheManagers.FirstOrDefault(p => p.Name.EqualsInvariant("platformCache"));
                if (defaultCacheManager != null)
                {
                    configuration = ConfigurationBuilder.LoadConfiguration(defaultCacheManager.Name);
                }

                var redisCacheManager = cacheManagerSection.CacheManagers.FirstOrDefault(p => p.Name.EqualsInvariant("redisPlatformCache"));
                if (redisConnectionString != null && redisCacheManager != null)
                {
                    configuration = ConfigurationBuilder.LoadConfiguration(redisCacheManager.Name);
                }

                if (configuration != null)
                {
                    configuration.LoggerFactoryType          = typeof(CacheManagerLoggerFactory);
                    configuration.LoggerFactoryTypeArguments = new object[] { container.Resolve <ILog>() };
                    cacheManager = CacheFactory.FromConfiguration <object>(configuration);
                }
            }

            // Create a default cache manager if there is no any others
            if (cacheManager == null)
            {
                cacheManager = CacheFactory.Build("platformCache", settings =>
                {
                    settings.WithUpdateMode(CacheUpdateMode.Up)
                    .WithSystemRuntimeCacheHandle("memCacheHandle")
                    .WithExpiration(ExpirationMode.Sliding, TimeSpan.FromMinutes(5));
                });
            }

            container.RegisterInstance(cacheManager);

            #endregion

            #region Settings

            var platformModuleManifest = new ModuleManifest
            {
                Id              = "VirtoCommerce.Platform",
                Version         = PlatformVersion.CurrentVersion.ToString(),
                PlatformVersion = PlatformVersion.CurrentVersion.ToString(),
                Settings        = new[]
                {
                    new ModuleSettingsGroup
                    {
                        Name     = "Platform|Notifications|SendGrid",
                        Settings = new []
                        {
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.Notifications.SendGrid.ApiKey",
                                ValueType   = ModuleSetting.TypeSecureString,
                                Title       = "SendGrid API key",
                                Description = "Your SendGrid API key"
                            }
                        }
                    },
                    new ModuleSettingsGroup
                    {
                        Name     = "Platform|Notifications|SendingJob",
                        Settings = new []
                        {
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.Notifications.SendingJob.TakeCount",
                                ValueType   = ModuleSetting.TypeInteger,
                                Title       = "Job Take Count",
                                Description = "Take count for sending job"
                            }
                        }
                    },
                    new ModuleSettingsGroup
                    {
                        Name     = "Platform|Notifications|SmtpClient",
                        Settings = new []
                        {
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.Notifications.SmptClient.Host",
                                ValueType   = ModuleSetting.TypeString,
                                Title       = "Smtp server host",
                                Description = "Smtp server host"
                            },
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.Notifications.SmptClient.Port",
                                ValueType   = ModuleSetting.TypeInteger,
                                Title       = "Smtp server port",
                                Description = "Smtp server port"
                            },
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.Notifications.SmptClient.Login",
                                ValueType   = ModuleSetting.TypeString,
                                Title       = "Smtp server login",
                                Description = "Smtp server login"
                            },
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.Notifications.SmptClient.Password",
                                ValueType   = ModuleSetting.TypeSecureString,
                                Title       = "Smtp server password",
                                Description = "Smtp server password"
                            },
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.Notifications.SmptClient.UseSsl",
                                ValueType   = ModuleSetting.TypeBoolean,
                                Title       = "Use SSL",
                                Description = "Use secure connection"
                            },
                        }
                    },
                    new ModuleSettingsGroup
                    {
                        Name     = "Platform|Security",
                        Settings = new []
                        {
                            new ModuleSetting
                            {
                                Name         = "VirtoCommerce.Platform.Security.AccountTypes",
                                ValueType    = ModuleSetting.TypeString,
                                Title        = "Account types",
                                Description  = "Dictionary for possible account types",
                                IsArray      = true,
                                ArrayValues  = Enum.GetNames(typeof(AccountType)),
                                DefaultValue = AccountType.Manager.ToString()
                            }
                        }
                    },
                    new ModuleSettingsGroup
                    {
                        Name     = "Platform|User Profile",
                        Settings = new[]
                        {
                            new ModuleSetting
                            {
                                Name      = "VirtoCommerce.Platform.UI.MainMenu.State",
                                ValueType = ModuleSetting.TypeJson,
                                Title     = "Persisted state of main menu"
                            },
                            new ModuleSetting
                            {
                                Name         = "VirtoCommerce.Platform.UI.Language",
                                ValueType    = ModuleSetting.TypeString,
                                Title        = "Language",
                                Description  = "Default language (two letter code from ISO 639-1, case-insensitive). Example: en, de",
                                DefaultValue = "en"
                            },
                            new ModuleSetting
                            {
                                Name         = "VirtoCommerce.Platform.UI.RegionalFormat",
                                ValueType    = ModuleSetting.TypeString,
                                Title        = "Regional format",
                                Description  = "Default regional format (CLDR locale code, with dash or underscore as delemiter, case-insensitive). Example: en, en_US, sr_Cyrl, sr_Cyrl_RS",
                                DefaultValue = "en"
                            },
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.UI.TimeZone",
                                ValueType   = ModuleSetting.TypeString,
                                Title       = "Time zone",
                                Description = "Default time zone (IANA time zone name [tz database], exactly as in database, case-sensitive). Examples: America/New_York, Europe/Moscow"
                            },
                            new ModuleSetting
                            {
                                Name         = "VirtoCommerce.Platform.UI.ShowMeridian",
                                ValueType    = ModuleSetting.TypeBoolean,
                                Title        = "Meridian labels based on user preferences",
                                Description  = "When set to true (by default), system will display time in format like '12 hour format' when possible",
                                DefaultValue = true.ToString()
                            },
                            new ModuleSetting
                            {
                                Name         = "VirtoCommerce.Platform.UI.UseTimeAgo",
                                ValueType    = ModuleSetting.TypeBoolean,
                                Title        = "Use time ago format when is possible",
                                Description  = "When set to true (by default), system will display date in format like 'a few seconds ago' when possible",
                                DefaultValue = true.ToString()
                            },
                            new ModuleSetting
                            {
                                Name        = "VirtoCommerce.Platform.UI.FullDateThreshold",
                                ValueType   = ModuleSetting.TypeInteger,
                                Title       = "Full date threshold",
                                Description = "Number of units after time ago format will be switched to full date format"
                            },
                            new ModuleSetting
                            {
                                Name          = "VirtoCommerce.Platform.UI.FullDateThresholdUnit",
                                ValueType     = ModuleSetting.TypeString,
                                Title         = "Full date threshold unit",
                                Description   = "Unit of full date threshold",
                                DefaultValue  = "Never",
                                AllowedValues = new[]
                                {
                                    "Never",
                                    "Seconds",
                                    "Minutes",
                                    "Hours",
                                    "Days",
                                    "Weeks",
                                    "Months",
                                    "Quarters",
                                    "Years"
                                }
                            },
                            new ModuleSetting
                            {
                                Name         = "VirtoCommerce.Platform.UI.FourDecimalsInMoney",
                                ValueType    = ModuleSetting.TypeBoolean,
                                Title        = "Show 4 decimal digits for money",
                                Description  = "Set to true to show 4 decimal digits for money. By default - false, 2 decimal digits are shown.",
                                DefaultValue = "false",
                            },
                        }
                    },
                    new ModuleSettingsGroup
                    {
                        Name     = "Platform|User Interface",
                        Settings = new[]
                        {
                            new ModuleSetting
                            {
                                Name         = "VirtoCommerce.Platform.UI.Customization",
                                ValueType    = ModuleSetting.TypeJson,
                                Title        = "Customization",
                                Description  = "JSON contains personalization settings of manager UI",
                                DefaultValue = "{\n" +
                                               "  \"title\": \"Virto Commerce\",\n" +
                                               "  \"logo\": \"Content/themes/main/images/logo.png\",\n" +
                                               "  \"contrast_logo\": \"Content/themes/main/images/contrast-logo.png\",\n" +
                                               "  \"favicon\": \"favicon.ico\"\n" +
                                               "}"
                            }
                        }
                    }
                }
            };

            var settingsManager = new SettingsManager(moduleCatalog, platformRepositoryFactory, cacheManager, new[] { new ManifestModuleInfo(platformModuleManifest) });
            container.RegisterInstance <ISettingsManager>(settingsManager);

            #endregion

            #region Dynamic Properties

            container.RegisterType <IDynamicPropertyService, DynamicPropertyService>(new ContainerControlledLifetimeManager());

            #endregion

            #region Notifications

            // Redis
            if (!string.IsNullOrEmpty(redisConnectionString))
            {
                // Cache
                RedisConfigurations.AddConfiguration(new RedisConfiguration("redisConnectionString", redisConnectionString));

                // SignalR
                // https://stackoverflow.com/questions/29885470/signalr-scaleout-on-azure-rediscache-connection-issues
                GlobalHost.DependencyResolver.UseRedis(new RedisScaleoutConfiguration(redisConnectionString, "VirtoCommerce.Platform.SignalR"));
            }

            // SignalR
            var tempCounterManager = new TempPerformanceCounterManager();
            GlobalHost.DependencyResolver.Register(typeof(IPerformanceCounterManager), () => tempCounterManager);
            var hubConfiguration = new HubConfiguration {
                EnableJavaScriptProxies = false
            };
            app.MapSignalR("/" + moduleInitializerOptions.RoutePrefix + "signalr", hubConfiguration);

            var hubSignalR = GlobalHost.ConnectionManager.GetHubContext <ClientPushHub>();
            var notifier   = new InMemoryPushNotificationManager(hubSignalR);
            container.RegisterInstance <IPushNotificationManager>(notifier);

            var resolver = new LiquidNotificationTemplateResolver();
            container.RegisterInstance <INotificationTemplateResolver>(resolver);

            var notificationTemplateService = new NotificationTemplateServiceImpl(platformRepositoryFactory);
            container.RegisterInstance <INotificationTemplateService>(notificationTemplateService);

            var notificationManager = new NotificationManager(resolver, platformRepositoryFactory, notificationTemplateService);
            container.RegisterInstance <INotificationManager>(notificationManager);

            IEmailNotificationSendingGateway emailNotificationSendingGateway = null;

            var emailNotificationSendingGatewayName = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Notifications:Gateway", "Default");

            if (string.Equals(emailNotificationSendingGatewayName, "Default", StringComparison.OrdinalIgnoreCase))
            {
                emailNotificationSendingGateway = new DefaultSmtpEmailNotificationSendingGateway(settingsManager);
            }
            else if (string.Equals(emailNotificationSendingGatewayName, "SendGrid", StringComparison.OrdinalIgnoreCase))
            {
                emailNotificationSendingGateway = new SendGridEmailNotificationSendingGateway(settingsManager);
            }

            if (emailNotificationSendingGateway != null)
            {
                container.RegisterInstance(emailNotificationSendingGateway);
            }

            ISmsNotificationSendingGateway smsNotificationSendingGateway = null;
            var smsNotificationSendingGatewayName = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Notifications:SmsGateway", "Default");

            if (smsNotificationSendingGatewayName.EqualsInvariant("Default"))
            {
                smsNotificationSendingGateway = new DefaultSmsNotificationSendingGateway();
            }
            else if (smsNotificationSendingGatewayName.EqualsInvariant("Twilio"))
            {
                smsNotificationSendingGateway = new TwilioSmsNotificationSendingGateway(new TwilioSmsGatewayOptions
                {
                    AccountId       = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Notifications:SmsGateway:AccountId"),
                    AccountPassword = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Notifications:SmsGateway:AccountPassword"),
                    Sender          = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Notifications:SmsGateway:Sender"),
                });
            }
            else if (smsNotificationSendingGatewayName.EqualsInvariant("ASPSMS"))
            {
                smsNotificationSendingGateway = new AspsmsSmsNotificationSendingGateway(new AspsmsSmsGatewayOptions
                {
                    AccountId       = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Notifications:SmsGateway:AccountId"),
                    AccountPassword = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Notifications:SmsGateway:AccountPassword"),
                    Sender          = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Notifications:SmsGateway:Sender"),
                    JsonApiUri      = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:Notifications:SmsGateway:ASPSMS:JsonApiUri"),
                });
            }

            if (smsNotificationSendingGateway != null)
            {
                container.RegisterInstance(smsNotificationSendingGateway);
            }

            #endregion

            #region Assets

            var blobConnectionString = BlobConnectionString.Parse(ConfigurationHelper.GetConnectionStringValue("AssetsConnectionString"));

            if (string.Equals(blobConnectionString.Provider, FileSystemBlobProvider.ProviderName, StringComparison.OrdinalIgnoreCase))
            {
                var fileSystemBlobProvider = new FileSystemBlobProvider(NormalizePath(pathMapper, blobConnectionString.RootPath), blobConnectionString.PublicUrl);

                container.RegisterInstance <IBlobStorageProvider>(fileSystemBlobProvider);
                container.RegisterInstance <IBlobUrlResolver>(fileSystemBlobProvider);
            }
            else if (string.Equals(blobConnectionString.Provider, AzureBlobProvider.ProviderName, StringComparison.OrdinalIgnoreCase))
            {
                var azureBlobProvider = new AzureBlobProvider(blobConnectionString.ConnectionString, blobConnectionString.CdnUrl);
                container.RegisterInstance <IBlobStorageProvider>(azureBlobProvider);
                container.RegisterInstance <IBlobUrlResolver>(azureBlobProvider);
            }

            container.RegisterType <IAssetEntryService, AssetEntryService>(new ContainerControlledLifetimeManager());
            container.RegisterType <IAssetEntrySearchService, AssetEntryService>(new ContainerControlledLifetimeManager());

            #endregion

            #region Modularity

            var modulesDataSources    = ConfigurationHelper.SplitAppSettingsStringValue("VirtoCommerce:ModulesDataSources");
            var externalModuleCatalog = new ExternalManifestModuleCatalog(moduleCatalog.Modules, modulesDataSources, container.Resolve <ILog>());
            container.RegisterType <ModulesController>(new InjectionConstructor(externalModuleCatalog, new ModuleInstaller(modulesPath, externalModuleCatalog), notifier, container.Resolve <IUserNameResolver>(), settingsManager));

            #endregion

            #region ChangeLogging

            var changeLogService = new ChangeLogService(platformRepositoryFactory);
            container.RegisterInstance <IChangeLogService>(changeLogService);

            #endregion

            #region Security
            container.RegisterInstance <IPermissionScopeService>(new PermissionScopeService());
            container.RegisterType <IRoleManagementService, RoleManagementService>(new ContainerControlledLifetimeManager());

            var apiAccountProvider = new ApiAccountProvider(platformRepositoryFactory, cacheManager);
            container.RegisterInstance <IApiAccountProvider>(apiAccountProvider);

            container.RegisterType <IClaimsIdentityProvider, ApplicationClaimsIdentityProvider>(new ContainerControlledLifetimeManager());

            container.RegisterInstance(app.GetDataProtectionProvider());
            container.RegisterType <SecurityDbContext>(new InjectionConstructor(connectionString));
            container.RegisterType <IUserStore <ApplicationUser>, ApplicationUserStore>();
            container.RegisterType <IAuthenticationManager>(new InjectionFactory(c => HttpContext.Current.GetOwinContext().Authentication));
            container.RegisterType <ApplicationUserManager>();
            container.RegisterType <ApplicationSignInManager>();

            var nonEditableUsers = ConfigurationHelper.GetAppSettingsValue("VirtoCommerce:NonEditableUsers", string.Empty);
            container.RegisterInstance <ISecurityOptions>(new SecurityOptions(nonEditableUsers));

            container.RegisterType <ISecurityService, SecurityService>();

            container.RegisterType <IPasswordCheckService, PasswordCheckService>();

            #endregion

            #region ExportImport
            container.RegisterType <IPlatformExportImportManager, PlatformExportImportManager>();
            #endregion

            #region Serialization

            container.RegisterType <IExpressionSerializer, XmlExpressionSerializer>();

            #endregion

            #region Events
            var inProcessBus = new InProcessBus();
            container.RegisterInstance <IHandlerRegistrar>(inProcessBus);
            container.RegisterInstance <IEventPublisher>(inProcessBus);

            inProcessBus.RegisterHandler <UserChangedEvent>(async(message, token) => await container.Resolve <LogChangesUserChangedEventHandler>().Handle(message));
            inProcessBus.RegisterHandler <UserPasswordChangedEvent>(async(message, token) => await container.Resolve <LogChangesUserChangedEventHandler>().Handle(message));
            inProcessBus.RegisterHandler <UserResetPasswordEvent>(async(message, token) => await container.Resolve <LogChangesUserChangedEventHandler>().Handle(message));
            #endregion
        }
        public PlatformManager(UnitOfWorkManager uofMgr)
        {
            platformRepository = new PlatformRepository();

            uowManager = uofMgr;
        }
Example #33
0
        private static void InitializePlatform(IAppBuilder app, IUnityContainer container, string connectionStringName)
        {
            container.RegisterType <ICurrentUser, CurrentUser>(new HttpContextLifetimeManager());
            container.RegisterType <IUserNameResolver, UserNameResolver>();

            #region Setup database

            using (var db = new SecurityDbContext(connectionStringName))
            {
                new IdentityDatabaseInitializer().InitializeDatabase(db);
            }

            using (var context = new PlatformRepository(connectionStringName, container.Resolve <AuditableInterceptor>(), new EntityPrimaryKeyGeneratorInterceptor()))
            {
                new PlatformDatabaseInitializer().InitializeDatabase(context);
            }

            // Create Hangfire tables
            new SqlServerStorage(connectionStringName);

            #endregion


            Func <IPlatformRepository> platformRepositoryFactory = () => new PlatformRepository(connectionStringName, container.Resolve <AuditableInterceptor>(), new EntityPrimaryKeyGeneratorInterceptor());
            container.RegisterType <IPlatformRepository>(new InjectionFactory(c => platformRepositoryFactory()));
            container.RegisterInstance(platformRepositoryFactory);
            var moduleCatalog    = container.Resolve <IModuleCatalog>();
            var manifestProvider = container.Resolve <IModuleManifestProvider>();

            #region Caching
            var cacheManager = CacheFactory.Build("platformCache", settings =>
            {
                //Should be aware to using Web cache cache handle because it not worked in native threads. (Hangfire jobs)
                settings
                .WithUpdateMode(CacheUpdateMode.Up)
                .WithSystemRuntimeCacheHandle("memCacheHandle")
                .WithExpiration(ExpirationMode.Absolute, TimeSpan.FromDays(1));
            });
            container.RegisterInstance(cacheManager);
            #endregion

            #region Settings

            var platformSettings = new[]
            {
                new ModuleManifest
                {
                    Settings = new[]
                    {
                        new ModuleSettingsGroup
                        {
                            Name     = "Platform|Notifications|SendGrid",
                            Settings = new []
                            {
                                new ModuleSetting
                                {
                                    Name        = "VirtoCommerce.Platform.Notifications.SendGrid.UserName",
                                    ValueType   = ModuleSetting.TypeString,
                                    Title       = "SendGrid UserName",
                                    Description = "Your SendGrid account username"
                                },
                                new ModuleSetting
                                {
                                    Name        = "VirtoCommerce.Platform.Notifications.SendGrid.Secret",
                                    ValueType   = ModuleSetting.TypeString,
                                    Title       = "SendGrid Password",
                                    Description = "Your SendGrid account password"
                                }
                            }
                        },

                        new ModuleSettingsGroup
                        {
                            Name     = "Platform|Notifications|SendingJob",
                            Settings = new []
                            {
                                new ModuleSetting
                                {
                                    Name        = "VirtoCommerce.Platform.Notifications.SendingJob.TakeCount",
                                    ValueType   = ModuleSetting.TypeInteger,
                                    Title       = "Job Take Count",
                                    Description = "Take count for sending job"
                                }
                            }
                        },

                        new ModuleSettingsGroup
                        {
                            Name     = "Platform|Notifications|SmtpClient",
                            Settings = new []
                            {
                                new ModuleSetting
                                {
                                    Name        = "VirtoCommerce.Platform.Notifications.SmptClient.Host",
                                    ValueType   = ModuleSetting.TypeString,
                                    Title       = "Smtp server host",
                                    Description = "Smtp server host"
                                },
                                new ModuleSetting
                                {
                                    Name        = "VirtoCommerce.Platform.Notifications.SmptClient.Port",
                                    ValueType   = ModuleSetting.TypeInteger,
                                    Title       = "Smtp server port",
                                    Description = "Smtp server port"
                                },
                                new ModuleSetting
                                {
                                    Name        = "VirtoCommerce.Platform.Notifications.SmptClient.Login",
                                    ValueType   = ModuleSetting.TypeString,
                                    Title       = "Smtp server login",
                                    Description = "Smtp server login"
                                },
                                new ModuleSetting
                                {
                                    Name        = "VirtoCommerce.Platform.Notifications.SmptClient.Password",
                                    ValueType   = ModuleSetting.TypeString,
                                    Title       = "Smtp server password",
                                    Description = "Smtp server password"
                                }
                            }
                        },

                        new ModuleSettingsGroup
                        {
                            Name     = "Platform|Security",
                            Settings = new []
                            {
                                new ModuleSetting
                                {
                                    Name         = "VirtoCommerce.Platform.Security.AccountTypes",
                                    ValueType    = ModuleSetting.TypeString,
                                    Title        = "Account types",
                                    Description  = "Dictionary for possible account types",
                                    IsArray      = true,
                                    ArrayValues  = Enum.GetNames(typeof(AccountType)),
                                    DefaultValue = AccountType.Manager.ToString()
                                }
                            }
                        }
                    }
                }
            };

            var settingsManager = new SettingsManager(manifestProvider, platformRepositoryFactory, cacheManager, platformSettings);
            container.RegisterInstance <ISettingsManager>(settingsManager);

            #endregion

            #region Dynamic Properties

            container.RegisterType <IDynamicPropertyService, DynamicPropertyService>();

            #endregion

            #region Notifications

            var hubSignalR = GlobalHost.ConnectionManager.GetHubContext <ClientPushHub>();
            var notifier   = new InMemoryPushNotificationManager(hubSignalR);
            container.RegisterInstance <IPushNotificationManager>(notifier);

            var resolver = new LiquidNotificationTemplateResolver();
            var notificationTemplateService = new NotificationTemplateServiceImpl(platformRepositoryFactory);
            var notificationManager         = new NotificationManager(resolver, platformRepositoryFactory, notificationTemplateService);

            //var emailNotificationSendingGateway = new DefaultEmailNotificationSendingGateway(settingsManager);
            var emailNotificationSendingGateway = new DefaultSmtpEmailNotificationSendingGateway(settingsManager);

            var defaultSmsNotificationSendingGateway = new DefaultSmsNotificationSendingGateway();

            container.RegisterInstance <INotificationTemplateService>(notificationTemplateService);
            container.RegisterInstance <INotificationManager>(notificationManager);
            container.RegisterInstance <INotificationTemplateResolver>(resolver);
            container.RegisterInstance <IEmailNotificationSendingGateway>(emailNotificationSendingGateway);
            container.RegisterInstance <ISmsNotificationSendingGateway>(defaultSmsNotificationSendingGateway);


            #endregion

            #region Assets

            var assetsConnection = ConfigurationManager.ConnectionStrings["AssetsConnectionString"];

            if (assetsConnection != null)
            {
                var properties             = assetsConnection.ConnectionString.ToDictionary(";", "=");
                var provider               = properties["provider"];
                var assetsConnectionString = properties.ToString(";", "=", "provider");

                if (string.Equals(provider, FileSystemBlobProvider.ProviderName, StringComparison.OrdinalIgnoreCase))
                {
                    var storagePath            = HostingEnvironment.MapPath(properties["rootPath"]);
                    var publicUrl              = properties["publicUrl"];
                    var fileSystemBlobProvider = new FileSystemBlobProvider(storagePath, publicUrl);

                    container.RegisterInstance <IBlobStorageProvider>(fileSystemBlobProvider);
                    container.RegisterInstance <IBlobUrlResolver>(fileSystemBlobProvider);
                }
                else if (string.Equals(provider, AzureBlobProvider.ProviderName, StringComparison.OrdinalIgnoreCase))
                {
                    var azureBlobProvider = new AzureBlobProvider(assetsConnectionString);

                    container.RegisterInstance <IBlobStorageProvider>(azureBlobProvider);
                    container.RegisterInstance <IBlobUrlResolver>(azureBlobProvider);
                }
            }

            #endregion

            #region Packaging

            var packagesPath   = HostingEnvironment.MapPath(VirtualRoot + "/App_Data/InstalledPackages");
            var packageService = new ZipPackageService(moduleCatalog, manifestProvider, packagesPath);
            container.RegisterInstance <IPackageService>(packageService);

            var uploadsPath = HostingEnvironment.MapPath(VirtualRoot + "/App_Data/Uploads");
            container.RegisterType <ModulesController>(new InjectionConstructor(packageService, uploadsPath, notifier, container.Resolve <IUserNameResolver>()));

            #endregion

            #region ChangeLogging

            var changeLogService = new ChangeLogService(platformRepositoryFactory);
            container.RegisterInstance <IChangeLogService>(changeLogService);

            #endregion

            #region Security
            container.RegisterInstance <IPermissionScopeService>(new PermissionScopeService());
            container.RegisterType <IRoleManagementService, RoleManagementService>(new ContainerControlledLifetimeManager());

            var apiAccountProvider = new ApiAccountProvider(platformRepositoryFactory, cacheManager);
            container.RegisterInstance <IApiAccountProvider>(apiAccountProvider);

            container.RegisterType <IClaimsIdentityProvider, ApplicationClaimsIdentityProvider>(new ContainerControlledLifetimeManager());

            container.RegisterInstance(app.GetDataProtectionProvider());
            container.RegisterType <SecurityDbContext>(new InjectionConstructor(connectionStringName));
            container.RegisterType <IUserStore <ApplicationUser>, ApplicationUserStore>();
            container.RegisterType <IAuthenticationManager>(new InjectionFactory(c => HttpContext.Current.GetOwinContext().Authentication));
            container.RegisterType <ApplicationUserManager>();
            container.RegisterType <ApplicationSignInManager>();

            var nonEditableUsers = ConfigurationManager.AppSettings.GetValue("VirtoCommerce:NonEditableUsers", string.Empty);
            container.RegisterInstance <ISecurityOptions>(new SecurityOptions(nonEditableUsers));

            container.RegisterType <ISecurityService, SecurityService>();

            #endregion

            #region ExportImport
            container.RegisterType <IPlatformExportImportManager, PlatformExportImportManager>();
            #endregion
        }
Example #34
0
        public void TesteSheet()
        {
            #region setup
            UserCredential credential;

            using (var stream =
                       new FileStream("client_secret.json", FileMode.Open, FileAccess.Read)) {
                string credPath = System.Environment.GetFolderPath(
                    System.Environment.SpecialFolder.Personal);
                credPath = Path.Combine(credPath, ".credentials/games.json");

                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
            }

            // Create Google Sheets API service.
            SheetsService sheetsService = new SheetsService(new BaseClientService.Initializer {
                HttpClientInitializer = credential,
                ApplicationName       = "Google-SheetsSample/0.1",
            });

            string id = "1k7Reqz1ZqGXwr8lTy5Y5r6bX53hxWv4kJSWTs3ptAuc";

            List <GameView> lista_mock = new List <GameView>();
            lista_mock.Add(new GameView {
                Name = "teste"
            });
            lista_mock.Add(new GameView {
                Name = "teste"
            });
            lista_mock.Add(new GameView {
                Name = "teste"
            });
            lista_mock.Add(new GameView {
                Name = "teste"
            });
            lista_mock.Add(new GameView {
                Name = "teste teste teste teste teste teste teste"
            });

            GameRepository     game       = new GameRepository();
            PlatformRepository plataforma = new PlatformRepository();
            #endregion

            #region limpar, preencher e formatar abas
            SpreadsheetsResource.GetRequest get = sheetsService.Spreadsheets.Get(id);
            Spreadsheet planilhas = get.Execute();

            SpreadsheetsResource.ValuesResource.UpdateRequest.ValueInputOptionEnum valueInputOption = (SpreadsheetsResource.ValuesResource.UpdateRequest.ValueInputOptionEnum) 2;

            foreach (Sheet planilha in planilhas.Sheets)
            {
                var aba = planilha.Properties.Title;

                ClearValuesRequest clearRequest = new ClearValuesRequest();
                SpreadsheetsResource.ValuesResource.ClearRequest request = sheetsService.Spreadsheets.Values.Clear(clearRequest, id, aba + "!A1:Z1000");
                ClearValuesResponse response = request.Execute();

                List <GameView> lista     = new List <GameView>();
                List <int>      plat      = new List <int>();
                List <object>   cabecalho = null;

                switch (aba)
                {
                case "Wishlist":
                    lista = game.ListarJogosWishlist(new List <int> {
                        0
                    });
                    cabecalho = new List <object>()
                    {
                        "", "Título", "Lançamento", "Plataformas"
                    };
                    break;

                case "Watchlist":
                    lista = game.ListarJogos(new List <int> {
                        0
                    }, 3);
                    cabecalho = new List <object>()
                    {
                        "", "Título", "Lançamento", "Plataformas"
                    };
                    break;

                default:
                    int?plataformas = plataforma.GetIdBySigla(aba);
                    plat = new List <int> {
                        plataformas.Value
                    };
                    lista     = game.ListarJogos(plat, 1);
                    cabecalho = new List <object>()
                    {
                        "", "Título"
                    };
                    break;
                }

                string range = aba + "!A1:D" + lista.Count + 1;

                List <IList <object> > dados = new List <IList <object> >();
                dados.Add(cabecalho);

                foreach (GameView jogo in lista)
                {
                    if (cabecalho.Count == 2)
                    {
                        dados.Add(new List <object>()
                        {
                            "=IMAGE(\"https://images.igdb.com/igdb/image/upload/t_micro/" + jogo.CloudnaryId + ".jpg\")", jogo.Name
                        });
                    }
                    else
                    {
                        string data = null;
                        if (jogo.ReleaseDate != null)
                        {
                            data = jogo.ReleaseDate.Value.ToShortDateString();
                        }
                        dados.Add(new List <object>()
                        {
                            "=IMAGE(\"https://images.igdb.com/igdb/image/upload/t_micro/" + jogo.CloudnaryId + ".jpg\")", jogo.Name, data, String.Join(", ", jogo.Plataformas)
                        });
                    }
                }

                ValueRange valueRange = new ValueRange();
                valueRange.Values = dados;

                SpreadsheetsResource.ValuesResource.UpdateRequest updateRequest = sheetsService.Spreadsheets.Values.Update(valueRange, id, range);
                updateRequest.ValueInputOption = valueInputOption;

                UpdateValuesResponse resposta = updateRequest.Execute();

                Request alignLeftRequest = new Request();
                alignLeftRequest.RepeatCell        = new RepeatCellRequest();
                alignLeftRequest.RepeatCell.Fields = "userEnteredFormat(HorizontalAlignment)";
                alignLeftRequest.RepeatCell.Range  = new GridRange {
                    SheetId = planilha.Properties.SheetId, StartColumnIndex = 2, EndColumnIndex = 3
                };
                alignLeftRequest.RepeatCell.Cell = new CellData {
                    UserEnteredFormat = new CellFormat {
                        HorizontalAlignment = "LEFT"
                    }
                };

                Request alignCenterRequest = new Request();
                alignCenterRequest.RepeatCell        = new RepeatCellRequest();
                alignCenterRequest.RepeatCell.Fields = "userEnteredFormat(HorizontalAlignment)";
                alignCenterRequest.RepeatCell.Range  = new GridRange {
                    SheetId = planilha.Properties.SheetId, StartColumnIndex = 0, EndColumnIndex = 1
                };
                alignCenterRequest.RepeatCell.Cell = new CellData {
                    UserEnteredFormat = new CellFormat {
                        HorizontalAlignment = "Center"
                    }
                };

                Request resizeRequest = new Request();
                resizeRequest.AutoResizeDimensions            = new AutoResizeDimensionsRequest();
                resizeRequest.AutoResizeDimensions.Dimensions = new DimensionRange {
                    SheetId = planilha.Properties.SheetId, Dimension = "COLUMNS", StartIndex = 1, EndIndex = cabecalho.Count
                };

                BatchUpdateSpreadsheetRequest batch = new BatchUpdateSpreadsheetRequest();
                batch.Requests = new List <Request>();
                batch.Requests.Add(alignLeftRequest);
                batch.Requests.Add(alignCenterRequest);
                batch.Requests.Add(resizeRequest);

                SpreadsheetsResource.BatchUpdateRequest u = sheetsService.Spreadsheets.BatchUpdate(batch, id);
                BatchUpdateSpreadsheetResponse          responseResize = u.Execute();
            }
            #endregion

            #region deletar aba
            // A list of updates to apply to the spreadsheet.
            // Requests will be applied in the order they are specified.
            // If any request is not valid, no requests will be applied.

            /*List<Request> requests = new List<Request>();  // TODO: Update placeholder value.
             * var a = new DeleteSheetRequest();
             * a.SheetId = 0;
             *
             * var t = new Request();
             * t.DeleteSheet = a;
             *
             * requests.Add(t);
             *
             * // TODO: Assign values to desired properties of `requestBody`:
             * BatchUpdateSpreadsheetRequest requestBody = new BatchUpdateSpreadsheetRequest();
             * requestBody.Requests = requests;
             *
             * SpreadsheetsResource.BatchUpdateRequest req = sheetsService.Spreadsheets.BatchUpdate(requestBody, id);
             *
             * // To execute asynchronously in an async method, replace `request.Execute()` as shown:
             * BatchUpdateSpreadsheetResponse response = req.Execute();*/
            #endregion

            #region criar planilha
            // TODO: Assign values to desired properties of `requestBody`:

            /*Spreadsheet requestBody3 = new Spreadsheet();
             * var propriedades = new SpreadsheetProperties();
             * propriedades.Title = "Games";
             * requestBody3.Properties = propriedades;
             *
             * SpreadsheetsResource.CreateRequest request3 = sheetsService.Spreadsheets.Create(requestBody3);
             *
             * // To execute asynchronously in an async method, replace `request.Execute()` as shown:
             * Spreadsheet response3 = request3.Execute();
             * // Data.Spreadsheet response = await request.ExecuteAsync();
             *
             * // TODO: Change code below to process the `response` object:
             * Console.WriteLine(response3);*/
            #endregion
        }