/// <summary>
 /// Metodo statico per ottenere un'istanza di un repository di un tipo specificato.
 /// Se tutto va a buon fine il metodo ritornerà un oggetto delle classe Persistence.RepositoryImpl.TipoRepository derivata
 /// dalla classe astratta Persistence.Repository.
 /// Se viene richiesto un tipo di repository non disponibile verrà sollevata un'eccezione; è quindi preferibile, nel caso in 
 /// cui non si sia sicuri della disponibilità di un tipo di repository, usare il metodo IsValidRepositoryType della Factory.
 /// </summary>
 /// <example>
 /// Persistence.Repository repo=Persistence.RepositoryFactory("raven");
 /// Console.Writeline(repo.RepositoryType); //raven
 /// </example>
 /// <param name="repType">Stringa rappresentante il tipo di repository richiesto.</param>
 /// <returns>Un'istanza del repository del tipo richiesto.</returns>
 /// <exception cref="System.TypeLoadException">Eccezione sollevata nel caso ci siano errori nel caricamento della classe 
 /// del repository o nell'invocazione del suo costruttore di default.</exception>
 /// <exception cref="System.ArgumentException">Eccezione sollevata nel caso in cui la stringa contenente il tipo di repository
 /// richiesto risulti vuota</exception>
 /// <exception cref="System.ArgumentNullException">Eccezione sollevata nel caso in cui la stringa contenente il tipo di
 /// repository richiesto risulti essere nulla</exception>
 public static Repository GetRepositoryInstance(String repType,RepositoryConfiguration config)
 {
     if (repType != null)
     {
         if (repType.Length != 0)
         {
             String className = _generateRepositoryClassName(repType);
             try
             {
                 Type reflectedRepository = Type.GetType(className, true, true);
                 Type[] args = new Type[1] {config.GetType()};
                 Object[] param = new Object[1] { config };
                 object rep = reflectedRepository.GetConstructor(args).Invoke(param);
                 Repository inst=rep as Repository;
                 if (inst.RepositoryType.Equals(repType)) {
                     return inst;
                 } else {
                     throw new TypeLoadException("Type "+inst.RepositoryType+" is different from the expected "+repType+"!");
                 }
             }
             catch (Exception ex)
             {
                 throw new TypeLoadException("Unable to load repository class " + className, ex);
             }
         }
         else
         {
             throw new ArgumentException("Repository Type Name must not be Empty!");
         }
     }
     else
     {
         throw new ArgumentNullException("Repository Type Name must not be NULL!");
     }
 }
        private SearchIssuesRequest CreateQuery(RepositoryConfiguration repoInfo)
        {
            // Find all open issues
            //  That are marked as customer reported

            SearchIssuesRequest requestOptions = new SearchIssuesRequest()
            {
                Repos  = new RepositoryCollection(),
                Labels = new string[] { Constants.Labels.CustomerReported },
                State  = ItemState.Open
            };

            requestOptions.Repos.Add(repoInfo.Owner, repoInfo.Name);

            return(requestOptions);
        }
        public RepositoryVM(IRepository repository, RepositoryConfiguration config)
        {
            this.Repository    = repository;
            this.Configuration = config;

            _client = repository as LocalGameClient;
            if (_client != null)
            {
                this.ClientPaths = new ViewModelMap <string, PathVM>(_client.ClientPaths,
                                                                     p => new PathVM(p, _client));

                this.SetAsModDirectoryCommand = new RelayCommand <PathVM>(this.SetAsModDirectory, this.CanSetAsModDirectory);
                this.AddClientPathCommand     = new RelayCommand(this.AddClientPath);
                this.RemoveClientPathsCommand = new RelayCommand <IList>(this.RemoveClientPaths, this.CanRemoveClientPaths);
            }
        }
Exemple #4
0
        private SearchIssuesRequest CreateQuery(RepositoryConfiguration repoInfo, string label)
        {
            // Find all open issues
            //  That are marked with 'label'

            SearchIssuesRequest requestOptions = new SearchIssuesRequest()
            {
                Repos  = new RepositoryCollection(),
                Labels = new string[] { label },
                State  = ItemState.Open
            };

            requestOptions.Repos.Add(repoInfo.Owner, repoInfo.Name);

            return(requestOptions);
        }
        /// <summary>
        /// Access method that will be executed by <c>ProgrammingExamples</c> and runs all the example method of the set.
        /// </summary>
        public static void RunExamples()
        {
            ExampleHelper.ExampleSetPrint("Kademlia Repository Examples", typeof(KademliaRepositoryExamples));
            RepositoryConfiguration conf = new RepositoryConfiguration(new { data_dir = @"..\..\Resource\Database" });

            _repository = new KademliaRepository("Raven", conf);
            CleanTagExample();
            StoreExample();
            PutExample();
            GetAllExample();
            MiscGetAndContainsExample();
            SearchExample();
            RefreshExample();
            ExpireExample();
            //DeleteExample();
        }
Exemple #6
0
        private static IServiceProvider ServicesConfiguration()
        {
            var builder = new ServiceCollection();

            var appsettings     = JObject.Parse(System.IO.File.ReadAllText("appsettings.json"));
            var worksheetConfig = appsettings["ConsultationsParsers"].ToDictionary(
                k => (k as JProperty).Name,
                v => (v as JProperty).Value.ToObject <WorksheetConfig>()
                );
            var repoConfig = new RepositoryConfiguration(
                credentialsFile: "googleCredentials.json",
                tokensTempFile: "tokens.json",
                googleSheetId: appsettings.Value <string>("GoogleSheetId"),
                worksheetConfig: worksheetConfig);

            builder.AddSingleton(repoConfig);
            builder.AddSingleton <IParserResolver, ParserResolver>();
            builder.AddSingleton <ConsultationRepository>();
            builder.AddSingleton <IConsultationRepository, CachingRepository>();

            builder.AddSingleton(new DbContextFactory(appsettings.Value <string>("DatabaseConnectionString")));

            string tempFolderPath = appsettings.Value <string>("VoiceTempFolder");

            builder.AddSingleton <IOggToWavConverter, OggToWavConverter>();
            builder.AddSingleton <ISpeechTranscriptor, GoogleSpeechToText>();
            builder.AddSingleton <IConsultationSearcher, ConsultationSearcher>();
            builder.AddSingleton <ConsultationPageMessageBuilderFactory>();
            builder.AddSingleton <SearchResultMessageBuilderFactory>();
            builder.AddSingleton <PagesListGenerator>();
            builder.AddSingleton <SearchQueryNormalizer>();
            builder.AddSingleton <SearchResultHandler>();

            string telegramBotId = JObject.Parse(
                System.IO.File.ReadAllText("credentials.json"))["TelegramBotId"].Value <string>();

            builder.AddSingleton <ITelegramBotClient>(new TelegramBotClient(telegramBotId));

            // Add controllers
            Router.GetControllerClasses().ToList().ForEach(c => builder.AddSingleton(c));

            return(builder.BuildServiceProvider(
                       new ServiceProviderOptions {
                ValidateOnBuild = true, ValidateScopes = false
            }
                       ));
        }
Exemple #7
0
        private void CreateOrUpdateCommunityVirtualRepo(string repo, string path)
        {
            string prefix = FindPrefixFromOrigin();

            foreach (var community in Communities)
            {
                string virtualRepoKey         = string.Format("{0}-co-{1}", prefix, community.Identifier);
                string virtualRepoDescription = string.Format("Community shares {0} in {1}", community.Identifier, Origin);

                RepositoryConfiguration repositoryConfiguration = storeBaseUrl.Repositories().RepositoryConfiguration(virtualRepoKey);

                if (repositoryConfiguration != null)
                {
                    if (!(repositoryConfiguration is VirtualRepositoryConfiguration))
                    {
                        log.ErrorFormat("Repo already exists on artifactory but not as virtual : {0}. Please contact the administrator.", virtualRepoKey);
                        continue;
                    }
                    else
                    {
                        VirtualRepositoryConfiguration vrepositoryConfiguration = repositoryConfiguration as VirtualRepositoryConfiguration;
                        if (vrepositoryConfiguration.packageType != RepositoryConfiguration.PackageType.generic ||
                            !vrepositoryConfiguration.Repositories.Contains(repo))
                        {
                            log.DebugFormat("Updating already existing virtual repo on artifactory : {0}", virtualRepoKey);
                            vrepositoryConfiguration.Repositories.Add(repo);
                            storeBaseUrl.Repositories().UpdateRepositoryConfiguration(repositoryConfiguration);
                        }
                    }
                }
                else
                {
                    repositoryConfiguration = new VirtualRepositoryConfiguration()
                    {
                        Key          = virtualRepoKey,
                        Description  = virtualRepoDescription,
                        packageType  = RepositoryConfiguration.PackageType.generic,
                        Repositories = new System.Collections.Generic.List <string>()
                        {
                            repo
                        }
                    };
                    storeBaseUrl.Repositories().CreateRepository(repositoryConfiguration);
                }
            }
        }
Exemple #8
0
        public static void RegisterServices(IServiceCollection services)
        {
            ContextConfiguration.Register(services);
            BusConfiguration.Register(services);
            EventConfiguration.Register(services);
            ValidationConfiguration.Register(services);
            HandlerConfiguration.Register(services);
            ServiceConfiguration.Register(services);
            RepositoryConfiguration.Register(services);

            // Infra - Identity Services
            //services.AddTransient<IEmailSender, AuthEmailMessageSender>();
            //services.AddTransient<ISmsSender, AuthSMSMessageSender>();

            // Infra - Identity
            //services.AddScoped<IUser, AspNetUser>();
        }
        private SearchIssuesRequest CreateQueryForNeedsAttentionItems(RepositoryConfiguration repoInfo)
        {
            // Find all open issues
            //  That are marked with 'needs-attention'

            SearchIssuesRequest requestOptions = new SearchIssuesRequest()
            {
                Repos  = new RepositoryCollection(),
                Labels = new string[] { Constants.Labels.NeedsAttention },
                Is     = new[] { IssueIsQualifier.Issue },
                State  = ItemState.Open
            };

            requestOptions.Repos.Add(repoInfo.Owner, repoInfo.Name);

            return(requestOptions);
        }
Exemple #10
0
        private static void RunSend(RepositoryConfiguration repositoryConfig, string nodeUrl)
        {
            var repoFactory = new VakapayRepositoryMysqlPersistenceFactory(repositoryConfig);

            var business   = new VakacoinBusiness.VakacoinBusiness(repoFactory);
            var connection = repoFactory.GetOldConnection() ?? repoFactory.GetDbConnection();

            if (nodeUrl == null)
            {
                Console.WriteLine("node url null");
                return;
            }

            try
            {
                while (true)
                {
                    try
                    {
                        var rpc = new VakacoinRpc(nodeUrl);

                        business.SetAccountRepositoryForRpc(rpc);

                        Console.WriteLine("Start Send Vakacoin...");
                        using (var repo = repoFactory.GetVakacoinWithdrawTransactionRepository(connection))
                        {
                            var resultSend = business.SendTransactionAsync(repo, rpc);
                            Console.WriteLine(JsonHelper.SerializeObject(resultSend.Result));

                            Console.WriteLine("Send Vakacoin End...");
                            Thread.Sleep(100);
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }
                }
            }
            catch (Exception e)
            {
                connection.Close();
                Console.WriteLine(e.ToString());
            }
        }
        private static void Main(string[] args)
        {
            try
            {
                var repositoryConfig = new RepositoryConfiguration
                {
                    ConnectionString = AppSettingHelper.GetDbConnection()
                };

                _persistenceFactory = new VakapayRepositoryMysqlPersistenceFactory(repositoryConfig);

                var btcBusiness = new BitcoinBusiness.BitcoinBusiness(_persistenceFactory);
                var rpc         = new BitcoinRpc(AppSettingHelper.GetBitcoinNode(),
                                                 AppSettingHelper.GetBitcoinRpcAuthentication());

                var transaction = rpc.FindTransactionByHash(args[0]);
                Logger.Debug("BitcoinNotify =>> BTCTransactionModel: " + transaction.Data);
                var transactionModel = BtcTransactionModel.FromJson(transaction.Data);
                if (transactionModel.BtcTransactionDetailsModel != null &&
                    transactionModel.BtcTransactionDetailsModel.Length > 0)
                {
                    foreach (var transactionModelDetail in transactionModel.BtcTransactionDetailsModel)
                    {
                        _walletBusiness = new WalletBusiness.WalletBusiness(_persistenceFactory);
                        if (transactionModelDetail.Category.Equals("receive"))
                        {
                            HandleNotifyDataReceiver(transactionModel, transactionModelDetail, btcBusiness);
                        }
                        else if (transactionModelDetail.Category.Equals("send"))
                        {
                            // if isExist(by address and transactionId) then update, else insert
                            HandleNotifyDataSend(transactionModel, transactionModelDetail, btcBusiness);
                        }
                    }
                }
                else
                {
                    Logger.Debug("BitcoinNotify BtcTransactionDetailsModel is not exist");
                }
            }
            catch (Exception e)
            {
                Logger.Error(e, "BitcoinNotify exception");
            }
        }
Exemple #12
0
        public void FakeWalletID()
        {
            var repositoryConfig = new RepositoryConfiguration
            {
                ConnectionString = AppSettingHelper.GetDbConnection()
            };

            var persistenceFactory = new VakapayRepositoryMysqlPersistenceFactory(repositoryConfig);
            var walletBusiness     = new WalletBusiness.WalletBusiness(persistenceFactory);
            var user = new User
            {
                Id = CommonHelper.GenerateUuid(),
            };
            var result = walletBusiness.CreateNewWallet(user, CryptoCurrency.ETH);

            Console.WriteLine(JsonHelper.SerializeObject(result));
            Assert.IsNotNull(result);
        }
        public FileLoggedInCharacterRepository(IAuthenticationNotificationService authenticationNotificationService)
        {
            _authenticationNotificationService = authenticationNotificationService;

            RepositoryConfiguration
            .Persist <List <Character> >()
            .WithTypeAlias("LoggedInCharactersWithTokens")
            .FileSystemRepository(new JsonSerializer())
            .UsePlainFileNames("xml")
            .WithStoragePath($"{Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)}/EveHQ NG/Settings");

            _repository = new Repository();

            lock (_loggedInCharactersSyncRoot)
            {
                _characters = _repository.Read <List <Character> >(LoggedInCharacterListEntityId) ?? new List <Character>();
            }
        }
Exemple #14
0
        private SearchIssuesRequest CreateQuery(RepositoryConfiguration repoInfo, Milestone milestone)
        {
            // Find all open issues
            //  That are marked with 'Client
            //  In the specified milestone

            SearchIssuesRequest requestOptions = new SearchIssuesRequest()
            {
                Repos     = new RepositoryCollection(),
                Labels    = new string[] { },
                State     = ItemState.Open,
                Milestone = milestone.Title
            };

            requestOptions.Repos.Add(repoInfo.Owner, repoInfo.Name);

            return(requestOptions);
        }
        private SearchIssuesRequest CreateQueryForNewItems(RepositoryConfiguration repoInfo, IssueIsQualifier issueType)
        {
            DateTime to = DateTime.UtcNow;
            DateTime fromTwoDaysBack = DateTime.UtcNow.AddDays(-2);

            SearchIssuesRequest requestOptions = new SearchIssuesRequest()
            {
#pragma warning disable CS0618 // Type or member is obsolete
                Created = DateRange.Between(fromTwoDaysBack, to),
#pragma warning restore CS0618 // Type or member is obsolete
                Order = SortDirection.Descending,
                Is    = new[] { IssueIsQualifier.Open, issueType },
                Repos = new RepositoryCollection()
            };

            requestOptions.Repos.Add(repoInfo.Owner, repoInfo.Name);

            return(requestOptions);
        }
        public void MarshallerIsCalled()
        {
            using (var mocks = new Mocks())
            {
                var marshal = mocks.Create<IMarshal>();
                var configuration = new RepositoryConfiguration
                                        {
                                            Marshal = marshal.Object
                                        };
                using (var repo = new Repository<Model>(configuration, new ModelFactory<Model>(() => new Model())))
                {
                    marshal.Setup(m => m.MarshalQueryResult("result")).Returns("marshal result");

                    var marshalledResult = repo.Query(m => "result");

                    Assert.That(marshalledResult, Is.EqualTo("marshal result"));
                }
            }
        }
        public ConsultationRepository(RepositoryConfiguration config, IParserResolver parserResolver)
        {
            using var credStream = new FileStream(config.CredentialsFile, FileMode.Open, FileAccess.Read);
            var creds = GoogleWebAuthorizationBroker.AuthorizeAsync(
                clientSecrets: GoogleClientSecrets.Load(credStream).Secrets,
                scopes: new[] { SheetsService.Scope.SpreadsheetsReadonly },
                user: "******",
                taskCancellationToken: CancellationToken.None,
                dataStore: new FileDataStore(config.TokensTempFile, true)
                ).Result;

            this.sheets = new SheetsService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = creds,
                ApplicationName       = nameof(NureSEConsultations)
            });

            this.config         = config;
            this.parserResolver = parserResolver;
        }
        private SearchIssuesRequest CreateQuery(RepositoryConfiguration repoInfo)
        {
            // Find all open PRs
            //  That were created more than 3 months ago

            SearchIssuesRequest requestOptions = new SearchIssuesRequest()
            {
                Repos = new RepositoryCollection(),
                State = ItemState.Open,
#pragma warning disable CS0618 // Type or member is obsolete
                Created = DateRange.LessThanOrEquals(DateTime.Now.AddMonths(-3)),
#pragma warning restore CS0618 // Type or member is obsolete
                Order = SortDirection.Ascending,
                Is    = new[] { IssueIsQualifier.PullRequest }
            };

            requestOptions.Repos.Add(repoInfo.Owner, repoInfo.Name);

            return(requestOptions);
        }
Exemple #19
0
        private static void Main(string[] args)
        {
            try
            {
                var repositoryConfig = new RepositoryConfiguration
                {
                    ConnectionString = AppSettingHelper.GetDbConnection()
                };

                for (var i = 0; i < 10; i++)
                {
                    var ts = new Thread(() => RunScan(repositoryConfig));
                    ts.Start();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
Exemple #20
0
        private static void RunScan(RepositoryConfiguration repositoryConfig)
        {
            var repoFactory = new VakapayRepositoryMysqlPersistenceFactory(repositoryConfig);

            var ethereumBusiness = new EthereumBusiness.EthereumBusiness(repoFactory);
            var walletBusiness   = new WalletBusiness.WalletBusiness(repoFactory);
            var connection       = repoFactory.GetOldConnection() ?? repoFactory.GetDbConnection();

            try
            {
                while (true)
                {
                    Console.WriteLine("==========Start Scan Ethereum==========");

                    var rpc = new EthereumRpc(AppSettingHelper.GetEthereumNode());

                    using (var ethereumRepo = repoFactory.GetEthereumWithdrawTransactionRepository(connection))
                    {
                        using (var ethereumDepoRepo = repoFactory.GetEthereumDepositeTransactionRepository(connection))
                        {
                            var resultSend =
                                ethereumBusiness
                                .ScanBlockAsync <EthereumWithdrawTransaction, EthereumDepositTransaction,
                                                 EthereumBlockResponse, EthereumTransactionResponse>(CryptoCurrency.ETH, walletBusiness,
                                                                                                     ethereumRepo, ethereumDepoRepo, rpc);
                            Console.WriteLine(JsonHelper.SerializeObject(resultSend.Result));


                            Console.WriteLine("==========Scan Ethereum End==========");
                            Console.WriteLine("==========Wait for next scan==========");
                            Thread.Sleep(5000);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                connection.Close();
                Console.WriteLine(e.ToString());
            }
        }
        public static IServiceCollection RegisterServices(this IServiceCollection services, IConfiguration configuration)
        {
            #region DB Congfig
            services.AddDbContext <FacilitDbContext>(options => options.UseSqlServer(configuration.GetConnectionString("DbConnection")));
            //services.AddDbContext<FacilitDbContext>(options => options.UseSqlServer(configuration.GetConnectionString("Server=172.20.1.177;Database=FacilitTest;User ID=dev;Password=B1ost@rR3@der;Trusted_Connection=False;")));
            #endregion

            #region Services

            ServiceConfiguration.Configure(services);

            #endregion

            #region Repositories

            RepositoryConfiguration.ConfigureRepositories(services);

            #endregion

            return(services);
        }
        public async System.Threading.Tasks.Task CreateNewAddressAsync()
        {
            Console.WriteLine("start");
            var repositoryConfig = new RepositoryConfiguration
            {
                ConnectionString = AppSettingHelper.GetDbConnection()
            };

            Console.WriteLine("New Address");
            PersistenceFactory = new VakapayRepositoryMysqlPersistenceFactory(repositoryConfig);
            var connection = PersistenceFactory.GetDbConnection();

            _btcBus = new Vakapay.BitcoinBusiness.BitcoinBusiness(PersistenceFactory);
            var    bitcoinRepo   = PersistenceFactory.GetBitcoinAddressRepository(connection);
            string walletId      = CommonHelper.RandomString(15);
            var    resultCreated =
                await _btcBus.CreateAddressAsync <BitcoinAddress>(bitcoinRepo, RpcClass, walletId);

            Console.WriteLine(JsonHelper.SerializeObject(resultCreated));
            Assert.IsNotNull(resultCreated);
        }
Exemple #23
0
        public LocalGameClientNodeVM(GameClientExplorerVM owner, LocalGameClient client)
            : base(null, client.Name, LoadChildenStrategy.Manual)
        {
            this.Configuration = RepositoryManager.Instance.GetConfiguration(client);
            this.Name          = this.Configuration.Alias;
            this.Configuration.PropertyChanged += Configuration_PropertyChanged;

            this.FileExplorer = owner;
            this.Model        = client;

            this.VehiclesNode = new VehiclesFolderVM(this, this.Model);
            this.InternalChildren.Add(this.VehiclesNode);

            this.DataNode = new DataFolderVM(this, this.Model);
            this.InternalChildren.Add(this.DataNode);

            this.FilesNode = new RootFolderVM(this, this.Model);
            this.InternalChildren.Add(this.FilesNode);

            this.ShowPropertiesCommand = new RelayCommand(this.ShowProperties);
        }
Exemple #24
0
        public static void Main(string[] args)
        {
            var repositoryConfig = new RepositoryConfiguration
            {
                ConnectionString = AppSettingHelper.GetDbConnection(),
            };
            var persistenceFactory = new VakapayRepositoryMysqlPersistenceFactory(repositoryConfig);

            var helper = new VakacoinChainHelper(
                int.Parse(AppSettingHelper.GetVakacoinBlockInterval()),
                new VakacoinRpc(AppSettingHelper.GetVakacoinNode()),
                new VakacoinBusiness.VakacoinBusiness(persistenceFactory),
                new WalletBusiness.WalletBusiness(persistenceFactory),
                new SendMailBusiness.SendMailBusiness(persistenceFactory)
                );

            foreach (GetBlockResponse block in helper.StreamBlock())
            {
                helper.ParseTransaction(block);
            }
        }
        public void UserInfo()
        {
            Console.WriteLine("start");
            var repositoryConfig = new RepositoryConfiguration
            {
                ConnectionString = AppSettingHelper.GetDbConnection()
            };

            Console.WriteLine("New Address");
            PersistenceFactory = new VakapayRepositoryMysqlPersistenceFactory(repositoryConfig);
            var userBus = new UserBusiness.UserBusiness(PersistenceFactory);

            var search =
                new Dictionary <string, string>
            {
                { "Email", "" }
            };
            var resultCreated = userBus.GetUserInfo(search);

            Console.WriteLine(JsonHelper.SerializeObject(resultCreated));
        }
Exemple #26
0
        public static RepositoryConfiguration Create(string entry)
        {
            // the entry looks like:
            // repo\owner\to:alias,alias#cc:alias

            // normalize the slashes.

            entry = entry.Replace('/', '\\');

            string[] entries = entry.Split('\\');


            // parse the emails.
            string[] emails = entries[2].Split("#");

            string to = string.Empty, cc = string.Empty;

            for (int i = 0; i < emails.Length; i++)
            {
                if (emails[i].StartsWith("to"))
                {
                    to += emails[i];
                }
                else if (emails[i].StartsWith("cc"))
                {
                    cc += emails[i];
                }
            }

            RepositoryConfiguration config = new RepositoryConfiguration
            {
                Owner   = entries[0],
                Name    = entries[1],
                ToEmail = ParseEmails(to),
                CcEmail = ParseEmails(cc)
            };

            return(config);
        }
Exemple #27
0
            //private DocumentStore _store;
            /// <summary>
            /// Constructor of the repository.
            /// The directory where the database will be located in the path indicated in the Configuration Field named <c>data_dir</c>. If
            /// no data directory is specified a temporary path will be used.
            /// </summary>
            /// <param name="config">Configuration used to initialize the Repository</param>
            public RavenRepository(RepositoryConfiguration config = null)
            {
                log.Info("Trying to load RavenRepository class...");
                this.RepositoryType = "Raven";
                string dataDir = System.IO.Path.GetTempPath() + "/p2p-player-db";

                if (config != null)
                {
                    string tdd = config.GetConfig("data_dir");
                    if (!tdd.Equals(""))
                    {
                        dataDir = tdd;
                    }
                }
                log.Debug("Start opening and initializing RavenDB");
                _store = new EmbeddableDocumentStore {
                    DataDirectory = dataDir
                };
                //_store = new DocumentStore { Url = "http://localhost:8080" };
                _store.Initialize();
                log.Info("RavenDB initialized at " + dataDir);
            }
Exemple #28
0
        static void Main(string[] args)
        {
            var repositoryConfig = new RepositoryConfiguration
            {
                ConnectionString = AppSettingHelper.GetDbConnection()
            };


            var persistenceFactory = new VakapayRepositoryMysqlPersistenceFactory(repositoryConfig);
            var ethereumWithdrawTransactionRepository =
                persistenceFactory.GetEthereumWithdrawTransactionRepository(persistenceFactory.GetDbConnection());

            try
            {
                for (var i = 0; i < 20; i++)
                {
                    var trans = new EthereumWithdrawTransaction
                    {
                        Amount       = 1,
                        Fee          = 0,
                        BlockNumber  = 0,
                        FromAddress  = null,
                        Hash         = null,
                        IsProcessing = 0,
//                        NetworkName = "ETH",
                        Status    = Status.STATUS_PENDING,
                        Version   = 0,
                        ToAddress = "0x13f022d72158410433cbd66f5dd8bf6d2d129924"
                    };
                    var resultInsert = ethereumWithdrawTransactionRepository.Insert(trans);
                    Console.WriteLine(JsonHelper.SerializeObject(resultInsert));
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
Exemple #29
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //Automapper Configuration
            var config = new AutoMapper.MapperConfiguration(cfg =>
            {
                cfg.AddProfile(new MappingProfile());
            });
            var mapper = config.CreateMapper();

            services.AddSingleton(mapper);

            //Application Services and Repositories
            RepositoryConfiguration.Configure(services);
            ServiceConfigurations.Configure(services);

            services.AddDbContext <AllianzDBContext>(options =>
                                                     options.UseSqlServer(
                                                         Configuration.GetConnectionString("DefaultConnection")));
            services.AddIdentity <IdentityUser, IdentityRole>(options => options.SignIn.RequireConfirmedAccount = true)
            .AddEntityFrameworkStores <AllianzDBContext>();
            services.AddControllersWithViews();
            services.AddRazorPages();
        }
        private static VersionConfiguration GetBranchConfiguration(RepositoryConfiguration config, string branchName)
        {
            if (string.IsNullOrWhiteSpace(branchName) || branchName == _noBranchCheckedOut)
            {
                throw new GitException(Resources.Exception_CouldNotIdentifyBranchName);
            }

            var match = config
                        .Branches
                        .Overrides
                        .FirstOrDefault(x => Regex.IsMatch(branchName, x.Match, RegexOptions.IgnoreCase));

            if (match != null)
            {
                var label = ApplyParts(
                    match.Label ?? config.Label,
                    match.PrefixLabel,
                    match.PostfixLabel,
                    match.InsertLabel);

                var meta = ApplyParts(
                    match.Metadata ?? config.Metadata,
                    match.PrefixMetadata,
                    match.PostfixMetadata,
                    match.InsertMetadata);

                return(new VersionConfiguration
                {
                    Version = config.Version,
                    OffSet = config.OffSet,
                    Label = label,
                    Metadata = meta
                });
            }

            return(config);
        }
        public void GetResult_Malformed_Json_Committed_Counts_As_No_Change()
        {
            // Arrange
            using var fixture = new SimpleVersionRepositoryFixture(_serializer);
            fixture.MakeACommit();
            fixture.MakeACommit();
            fixture.MakeACommit();

            // Write the version file (with parsing errors)
            var file = Path.Combine(fixture.RepositoryPath, Constants.ConfigurationFileName);

            using (var writer = File.AppendText(file))
            {
                writer.WriteLine("This will not parse");
                writer.Flush();
            }

            fixture.Repository.Index.Add(Constants.ConfigurationFileName);
            fixture.Repository.Index.Write();
            fixture.MakeACommit(); // 5
            fixture.MakeACommit(); // 6
            fixture.MakeACommit(); // 7
            fixture.MakeACommit(); // 8

            var config = new RepositoryConfiguration {
                Version = "0.1.0"
            };

            fixture.SetConfig(config);

            var sut = new GitVersionRepository(fixture.RepositoryPath, _environment, _serializer, Enumerable.Empty <IVersionProcessor>());

            // Act
            var result = sut.GetResult();

            result.Height.Should().Be(9);
        }
Exemple #32
0
        public ModelViewConfiguration Update(string fileUpload, ModelViewConfiguration data, string path, int[] Usuarios)
        {
            string fileName = data.Url;

            if (File.Exists(fileUpload))
            {
                string combinePath = path + fileName;
                System.IO.File.Copy(fileUpload, combinePath, true);
                System.IO.File.Delete(fileUpload);
            }

            var objRepository    = new RepositoryConfiguration();
            var objRepositoryMsj = new RepositoryReceivers();
            var config           = objRepository.Get(data.ConfigurationID);

            config.Title      = data.Title;
            config.Message    = data.Message;
            config.Url        = File.Exists(fileUpload) ? GlobalConfiguration.urlRequest + "Content/Notification/" + data.Url: config.Url;
            config.ModifyDate = DateTime.UtcNow;
            objRepository.Update(config);
            List <int> IDS = objRepositoryMsj.GetByConfiguration(config.ConfigurationID).Select(a => a.UserID).ToList();

            objRepositoryMsj.Delete(IDS, config.ConfigurationID);
            foreach (var item in Usuarios)
            {
                EntityReceivers receivers = new EntityReceivers()
                {
                    ConfigurationID = config.ConfigurationID,
                    UserID          = item,
                    MessageCreate   = true,
                    CreateDate      = DateTime.Now,
                    ModifyDate      = DateTime.UtcNow
                };
                receivers = objRepositoryMsj.Insert(receivers);
            }
            return(data);
        }
 /// <summary>
 /// Repository Constructor that initializes the repository of the given type.
 /// </summary>
 /// <param name="repType">Name of the repository Type</param>
 /// <param name="conf">Configuration for the repository</param>
 public TrackRepository(string repType,RepositoryConfiguration conf)
 {
     this._repository = RepositoryFactory.GetRepositoryInstance(repType, conf);
 }
 /// <summary>
 /// Access method that will be executed by <c>ProgrammingExamples</c> and runs all the example method of the set.
 /// </summary>
 public static void RunExamples()
 {
     ExampleHelper.ExampleSetPrint("Kademlia Repository Examples", typeof(KademliaRepositoryExamples));
     RepositoryConfiguration conf=new RepositoryConfiguration(new {data_dir = @"..\..\Resource\Database"});
     _repository = new KademliaRepository("Raven", conf);
     CleanTagExample();
     StoreExample();
     PutExample();
     GetAllExample();
     MiscGetAndContainsExample();
     SearchExample();
     RefreshExample();
     ExpireExample();
     //DeleteExample();
 }
 /// <summary>
 /// Constructor for the Kademlia Repository. This begins with compiling regular expressions for whitespace and semanticless
 /// words and setting timespan sing the given values (if they are not passed, it uses the default). Then instantiates the 
 /// repository of the fiven type and creates two indexes over the instantiatied repository. The first index is used to 
 /// find keywords with an empty tag list; the second one is used to query keyword using tag identifier. Both indexes are 
 /// necessary in order to cleanly delete resources and keywords from the repository
 /// </summary>
 /// <param name="repType">Name of the repository type. The default repository type is RavenDB ("Raven")</param>
 /// <param name="conf">Repository Configureation</param>
 /// <param name="elementValidity">Validity period of a Dht Element. Default value is 24 hours (1 day). The validity must
 /// be expressed in timespan format as described in MSDN reference for this type.</param>
 /// <param name="semanticFilter">Regular expression that will be used to remove semanticless word.</param>
 public KademliaRepository(string repType="Raven",
     RepositoryConfiguration conf=null,
     string elementValidity = "1",
     string semanticFilter=KademliaRepository.DefaultSemanticFilterRegexString)
 {
     log.Debug("Semantic Filter Regex used is "+DefaultSemanticFilterRegexString);
     if (!(TimeSpan.TryParse(elementValidity, out this._elementValidity)))
     {
         this._elementValidity = new TimeSpan(24, 0, 0);
     }
     this._semanticRegex = new Regex(DefaultSemanticFilterRegexString, RegexOptions.Compiled | RegexOptions.IgnoreCase);
     this._whiteSpaceRegex = new Regex(@"[ ]{2,}", RegexOptions.Compiled);
     this._repository = RepositoryFactory.GetRepositoryInstance(repType, conf);
     this._repository.CreateIndex("KademliaKeywords/KeysByTag",
                                  "from key in docs.KademliaKeywords\nfrom tag in key.Tags\nselect new { Kid = key.Id , Tid = tag}");
     this._repository.CreateIndex("KademliaKeywords/EmptyKeys",
                                  "from key in docs.KademliaKeywords\nwhere key.Tags.Count() == 0\nselect new { key.Id }");
 }