public async Task PostInvalidInstanceAssetPair(AlgoInstanceType algoInstanceType)
        {
            WalletDTO walletDTO = null;

            if (algoInstanceType == AlgoInstanceType.Live)
            {
                walletDTO = await GetExistingWallet();
            }

            // Create algo
            var algoData = await CreateAlgo();

            // Build days offset
            DaysOffsetDTO daysOffsetDTO = BuildDaysOffsetByInstanceType(algoInstanceType);
            // Build InstanceParameters
            InstanceParameters instanceParameters = InstanceConfig.InvalidInstanceAssetPair;

            // Build instance request payload
            var instanceForAlgo = InstanceDataBuilder.BuildInstanceData(algoData, walletDTO, algoInstanceType, instanceParameters, daysOffsetDTO);

            var url = algoInstanceType == AlgoInstanceType.Live ? ApiPaths.ALGO_STORE_SAVE_ALGO_INSTANCE : ApiPaths.ALGO_STORE_FAKE_TRADING_INSTANCE_DATA;

            var postInstanceDataResponse = await Consumer.ExecuteRequest(url, Helpers.EmptyDictionary, JsonUtils.SerializeObject(instanceForAlgo), Method.POST);

            AlgoErrorDTO postInstanceDataResponseDTO = JsonUtils.DeserializeJson <AlgoErrorDTO>(postInstanceDataResponse.ResponseJson);

            Assert.That(postInstanceDataResponse.Status, Is.EqualTo(HttpStatusCode.InternalServerError), "responce should equals internal server erorr");

            Assert.That(postInstanceDataResponseDTO.ErrorMessage, Does.Contain("NotFound from asset service calling AssetPairGetWithHttpMessagesAsync"), "we should receive erorr for not found asset pair");
        }
        public async Task PostInvalidInstanceTradedAsset(AlgoInstanceType algoInstanceType)
        {
            WalletDTO walletDTO = null;

            if (algoInstanceType == AlgoInstanceType.Live)
            {
                walletDTO = await GetExistingWallet();
            }

            // Create algo
            var algoData = await CreateAlgo();

            // Build days offset
            DaysOffsetDTO daysOffsetDTO = BuildDaysOffsetByInstanceType(algoInstanceType);
            // Build InstanceParameters
            InstanceParameters instanceParameters = InstanceConfig.InvalidInstanceTradedAsset;

            // Build instance request payload
            var instanceForAlgo = InstanceDataBuilder.BuildInstanceData(algoData, walletDTO, algoInstanceType, instanceParameters, daysOffsetDTO);

            var url = algoInstanceType == AlgoInstanceType.Live ? ApiPaths.ALGO_STORE_SAVE_ALGO_INSTANCE : ApiPaths.ALGO_STORE_FAKE_TRADING_INSTANCE_DATA;

            var postInstanceDataResponse = await Consumer.ExecuteRequest(url, Helpers.EmptyDictionary, JsonUtils.SerializeObject(instanceForAlgo), Method.POST);

            AlgoErrorDTO postInstanceDataResponseDTO = JsonUtils.DeserializeJson <AlgoErrorDTO>(postInstanceDataResponse.ResponseJson);

            Assert.That(postInstanceDataResponse.Status, Is.EqualTo(HttpStatusCode.BadRequest), "should be bad response erorr code");

            Assert.That(postInstanceDataResponseDTO.ErrorMessage, Does.Contain("ValidationError Message:Asset <USD> is not valid for asset pair <BTCEUR>"), "we should receive erorr for the invalid traded asset");
        }
Example #3
0
        public void ParametersThrowsExceptionWhenInstanceIsDisposed()
        {
            var instance = new Instance("disposed2");

            instance.Dispose();
            InstanceParameters x = instance.Parameters;
        }
Example #4
0
 public void Initialize()
 {
     GranularWriter.Tracer.TraceDebug <string>((long)this.GetHashCode(), "Initialize({0})", this.DatabaseName);
     this.m_lowestClosedGeneration = 0L;
     this.m_currentGeneration      = 0L;
     this.m_currentGenerationState = GranularWriter.GranularLogState.Unknown;
     this.DiscardLogs();
     try
     {
         string name = this.m_config.DatabaseName + "_PassiveInBlockMode";
         Api.JetCreateInstance(out this.m_jetConsumer, name);
         string             paramString        = null;
         InstanceParameters instanceParameters = new InstanceParameters(this.m_jetConsumer);
         instanceParameters.BaseName           = this.m_config.LogFilePrefix;
         instanceParameters.LogFileDirectory   = this.m_config.LogInspectorPath;
         instanceParameters.SystemDirectory    = this.m_config.DestinationSystemPath;
         instanceParameters.NoInformationEvent = true;
         instanceParameters.Recovery           = false;
         instanceParameters.LogFileSize        = 1024;
         instanceParameters.MaxTemporaryTables = 0;
         if (!RegistryParameters.DisableJetFailureItemPublish)
         {
             Api.JetSetSystemParameter(this.m_jetConsumer, JET_SESID.Nil, (JET_param)168, 1, paramString);
         }
         Api.JetInit(ref this.m_jetConsumer);
         this.m_jetConsumerInitialized = true;
         this.m_jetConsumerHealthy     = true;
     }
     catch (EsentErrorException ex)
     {
         GranularWriter.Tracer.TraceError <string, EsentErrorException>((long)this.GetHashCode(), "Initialize({0}) failed:{1}", this.DatabaseName, ex);
         throw new GranularReplicationInitFailedException(ex.Message, ex);
     }
 }
Example #5
0
        public LogChecksummer(string basename)
        {
            bool flag = false;

            EseHelper.GlobalInit();
            this.m_disposeTracker = this.GetDisposeTracker();
            this.m_instanceName   = string.Format("LogChecksummer {0} {1}", basename, this.GetHashCode());
            Api.JetCreateInstance(out this.m_instance, this.m_instanceName);
            this.m_basename = basename;
            bool jettermNeeded = true;

            try
            {
                InstanceParameters instanceParameters = new InstanceParameters(this.Instance);
                instanceParameters.Recovery           = false;
                instanceParameters.MaxTemporaryTables = 0;
                instanceParameters.NoInformationEvent = true;
                instanceParameters.BaseName           = basename;
                jettermNeeded = false;
                Api.JetInit(ref this.m_instance);
                jettermNeeded = true;
                Api.JetBeginSession(this.Instance, out this.m_sesid, null, null);
                this.AssertNotTerminated();
                flag = true;
                LogChecksummer.Tracer.TraceDebug <string, int>((long)this.GetHashCode(), "LogChecksummer created: {0}. DispTracker=0x{1:X}", this.m_instanceName, this.m_disposeTracker.GetHashCode());
            }
            finally
            {
                if (!flag)
                {
                    this.Term(jettermNeeded);
                }
            }
        }
        public async Task PostInvalidAlgoId(AlgoInstanceType algoInstanceType)
        {
            WalletDTO walletDTO = null;

            if (algoInstanceType == AlgoInstanceType.Live)
            {
                walletDTO = await GetExistingWallet();
            }

            // Create algo
            var algoData = await CreateAlgo();

            // Build days offset
            DaysOffsetDTO daysOffsetDTO = BuildDaysOffsetByInstanceType(algoInstanceType);
            // Build InstanceParameters
            InstanceParameters instanceParameters = InstanceConfig.UseInvalidAlgoId;

            // Build instance request payload
            var instanceForAlgo = InstanceDataBuilder.BuildInstanceData(algoData, walletDTO, algoInstanceType, instanceParameters, daysOffsetDTO);

            var url = algoInstanceType == AlgoInstanceType.Live ? ApiPaths.ALGO_STORE_SAVE_ALGO_INSTANCE : ApiPaths.ALGO_STORE_FAKE_TRADING_INSTANCE_DATA;

            var postInstanceDataResponse = await Consumer.ExecuteRequest(url, Helpers.EmptyDictionary, JsonUtils.SerializeObject(instanceForAlgo), Method.POST);

            Assert.That(postInstanceDataResponse.Status, Is.EqualTo(HttpStatusCode.NotFound), "we should receive not found response code");
        }
        public void CreateResizeAndTrimDatabase()
        {
            if (!EsentVersion.SupportsWindows81Features)
            {
                return;
            }

            string       dir      = SetupHelper.CreateRandomDirectory();
            JET_INSTANCE instance = SetupHelper.CreateNewInstance(dir);

            Api.JetSetSystemParameter(instance, JET_SESID.Nil, JET_param.MaxTemporaryTables, 0, null);

            InstanceParameters instanceParameters = new InstanceParameters(instance);

            instanceParameters.EnableShrinkDatabase = ShrinkDatabaseGrbit.On;
            Api.JetInit(ref instance);
            try
            {
                string database = Path.Combine(dir, "CreateAndResizeDatabase.db");

                JET_SESID sesid;
                JET_DBID  dbid;
                Api.JetBeginSession(instance, out sesid, string.Empty, string.Empty);

                Api.JetSetSystemParameter(instance, JET_SESID.Nil, JET_param.DbExtensionSize, 256, null);
                Api.JetCreateDatabase(sesid, database, string.Empty, out dbid, CreateDatabaseGrbit.None);

                Api.JetSetSystemParameter(instance, JET_SESID.Nil, JET_param.DbExtensionSize, 1, null);

                int databaseSpaceOwned;
                Api.JetGetDatabaseInfo(sesid, dbid, out databaseSpaceOwned, JET_DbInfo.SpaceOwned);

                // We have to take into account the reserved pages in the database as per the API to get the actual
                // space.
                databaseSpaceOwned += ReservedPages;

                int actualPages;
                Windows8Api.JetResizeDatabase(sesid, dbid, databaseSpaceOwned + 100, out actualPages, ResizeDatabaseGrbit.None);
                EseInteropTestHelper.ConsoleWriteLine("actualPages is {0}.", actualPages);

                Assert.IsTrue(actualPages >= databaseSpaceOwned + 100, "Database didn't grow enough!");

                int actualPagesAfterTrim = 0;
                Windows8Api.JetResizeDatabase(sesid, dbid, 0, out actualPagesAfterTrim, ResizeDatabaseGrbit.None);
                EseInteropTestHelper.ConsoleWriteLine("actualPagesAfterTrim is {0}.", actualPagesAfterTrim);

                Assert.IsTrue(actualPagesAfterTrim < actualPages, "Database didn't shrink!");

                int databaseSizeOnDiskInPages;
                Api.JetGetDatabaseInfo(sesid, dbid, out databaseSizeOnDiskInPages, Windows81DbInfo.FilesizeOnDisk);
                EseInteropTestHelper.ConsoleWriteLine("databaseSizeOnDiskInPages is {0}.", databaseSizeOnDiskInPages);
                Assert.AreEqual(actualPagesAfterTrim, databaseSizeOnDiskInPages);
            }
            finally
            {
                Api.JetTerm(instance);
                Cleanup.DeleteDirectoryWithRetry(dir);
            }
        }
        /// <summary>
        /// Set the instance path parameters for the given database.
        /// </summary>
        /// <param name="instance">The instance to set the parameters on.</param>
        /// <param name="database">The database the instance will be using or creating.</param>
        private static void SetPathParameters(Instance instance, string database)
        {
            var    parameters = new InstanceParameters(instance);
            string directory  = Path.GetDirectoryName(Path.GetFullPath(database));

            parameters.SystemDirectory  = directory;
            parameters.TempDirectory    = directory;
            parameters.LogFileDirectory = directory;
        }
        public InstanceParameters ConfigureInstance(JET_INSTANCE jetInstance, string path)
        {
            path = Path.GetFullPath(path);
            var logsPath           = path;
            var configuredLogsPath = Configuration.Storage.Esent.JournalsStoragePath;

            if (string.IsNullOrEmpty(configuredLogsPath) == false)
            {
                logsPath = configuredLogsPath.ToFullPath();
            }
            var circularLog     = GetValueFromConfiguration(Constants.Esent.CircularLog, true);
            var logFileSizeInMb = GetValueFromConfiguration(Constants.Esent.LogFileSize, 64);

            logFileSizeInMb = Math.Max(1, logFileSizeInMb / 4);
            var maxVerPages = GetValueFromConfiguration(Constants.Esent.MaxVerPages, 512);

            var maxVerPagesResult = TranslateToSizeInVersionPages(maxVerPages, 1024 * 1024);

            ConfigureInstanceInternal(maxVerPages);

            var instanceParameters = new InstanceParameters(jetInstance)
            {
                CircularLog          = circularLog,
                Recovery             = true,
                NoInformationEvent   = false,
                CreatePathIfNotExist = true,
                EnableIndexChecking  = true,
                TempDirectory        = Path.Combine(logsPath, "temp"),
                SystemDirectory      = Path.Combine(logsPath, "system"),
                LogFileDirectory     = Path.Combine(logsPath, "logs"),
                MaxVerPages          = maxVerPagesResult,
                PreferredVerPages    = TranslateToSizeInVersionPages(GetValueFromConfiguration(Constants.Esent.PreferredVerPages, (int)(maxVerPagesResult * 0.85)), 1024 * 1024),
                BaseName             = BaseName,
                EventSource          = EventSource,
                LogBuffers           = TranslateToSizeInDatabasePages(GetValueFromConfiguration(Constants.Esent.LogBuffers, 8192), 1024),
                LogFileSize          = (logFileSizeInMb * 1024),
                MaxSessions          = MaxSessions,
                MaxCursors           = GetValueFromConfiguration(Constants.Esent.MaxCursors, 2048),
                DbExtensionSize      = TranslateToSizeInDatabasePages(GetValueFromConfiguration(Constants.Esent.DbExtensionSize, 8), 1024 * 1024),
                AlternateDatabaseRecoveryDirectory = path
            };

            if (Environment.OSVersion.Version >= new Version(5, 2))
            {
                // JET_paramEnableIndexCleanup is not supported on WindowsXP
                const int JET_paramEnableIndexCleanup = 54;
                Api.JetSetSystemParameter(jetInstance, JET_SESID.Nil, (JET_param)JET_paramEnableIndexCleanup, 1, null);
            }

            Log.Info(@"Esent Settings:
  MaxVerPages      = {0}
  CacheSizeMax     = {1}
  DatabasePageSize = {2}", instanceParameters.MaxVerPages, SystemParameters.CacheSizeMax,
                     SystemParameters.DatabasePageSize);

            return(instanceParameters);
        }
        public void SetJetParameterAsInteger()
        {
            var jetparam = new JetParameter(JET_param.MaxVerPages, 3000);

            jetparam.SetParameter(this.instance);

            var parameters = new InstanceParameters(this.instance);

            Assert.AreEqual(3000, parameters.MaxVerPages);
        }
        public void SetJetParameterAsString()
        {
            var jetparam = new JetParameter(JET_param.BaseName, "abc");

            jetparam.SetParameter(this.instance);

            var parameters = new InstanceParameters(this.instance);

            Assert.AreEqual("abc", parameters.BaseName);
        }
Example #12
0
        public bool Initialize(IUuidGenerator uuidGenerator, OrderedPartCollection <AbstractDocumentCodec> documentCodecs)
        {
            try
            {
                DocumentCodecs = documentCodecs;
                generator      = uuidGenerator;
                var instanceParameters = new TransactionalStorageConfigurator(configuration).ConfigureInstance(instance, path);

                if (configuration.RunInUnreliableYetFastModeThatIsNotSuitableForProduction)
                {
                    instanceParameters = new InstanceParameters(instance)
                    {
                        CircularLog          = true,
                        Recovery             = false,
                        NoInformationEvent   = false,
                        CreatePathIfNotExist = true,
                        TempDirectory        = Path.Combine(path, "temp"),
                        SystemDirectory      = Path.Combine(path, "system"),
                        LogFileDirectory     = Path.Combine(path, "logs"),
                        MaxVerPages          = 256,
                        BaseName             = "RVN",
                        EventSource          = "Raven",
                        LogBuffers           = 8192,
                        LogFileSize          = 256,
                        MaxSessions          = TransactionalStorageConfigurator.MaxSessions,
                        MaxCursors           = 1024,
                        DbExtensionSize      = 128,
                        AlternateDatabaseRecoveryDirectory = path
                    };
                }

                log.Info(@"Esent Settings:
  MaxVerPages      = {0}
  CacheSizeMax     = {1}
  DatabasePageSize = {2}", instanceParameters.MaxVerPages, SystemParameters.CacheSizeMax, SystemParameters.DatabasePageSize);

                Api.JetInit(ref instance);

                var newDb = EnsureDatabaseIsCreatedAndAttachToDatabase();

                SetIdFromDb();

                tableColumnsCache.InitColumDictionaries(instance, database);

                return(newDb);
            }
            catch (Exception e)
            {
                Dispose();
                throw new InvalidOperationException("Could not open transactional storage: " + database, e);
            }
        }
Example #13
0
        public InstanceParameters ConfigureInstance(JET_INSTANCE jetInstance, string path)
        {
            path = Path.GetFullPath(path);
            var logsPath           = path;
            var configuredLogsPath = configuration.Settings["Raven/Esent/LogsPath"] ?? configuration.Settings[Constants.RavenTxJournalPath] ?? configuration.JournalsStoragePath;

            if (string.IsNullOrEmpty(configuredLogsPath) == false)
            {
                logsPath = configuredLogsPath.ToFullPath();
            }
            var circularLog     = GetValueFromConfiguration("Raven/Esent/CircularLog", true);
            var logFileSizeInMb = GetValueFromConfiguration("Raven/Esent/LogFileSize", 64);

            logFileSizeInMb = Math.Max(1, logFileSizeInMb / 4);
            var maxVerPages = GetValueFromConfiguration("Raven/Esent/MaxVerPages", 512);

            if (transactionalStorage != null)
            {
                transactionalStorage.MaxVerPagesValueInBytes = maxVerPages * 1024 * 1024;
            }
            var maxVerPagesResult  = TranslateToSizeInVersionPages(maxVerPages, 1024 * 1024);
            var instanceParameters = new InstanceParameters(jetInstance)
            {
                CircularLog          = circularLog,
                Recovery             = true,
                NoInformationEvent   = false,
                CreatePathIfNotExist = true,
                EnableIndexChecking  = true,
                TempDirectory        = Path.Combine(logsPath, "temp"),
                SystemDirectory      = Path.Combine(logsPath, "system"),
                LogFileDirectory     = Path.Combine(logsPath, "logs"),
                MaxVerPages          = maxVerPagesResult,
                PreferredVerPages    = TranslateToSizeInVersionPages(GetValueFromConfiguration("Raven/Esent/PreferredVerPages", (int)(maxVerPagesResult * 0.85)), 1024 * 1024),
                BaseName             = "RVN",
                EventSource          = "Raven",
                LogBuffers           = TranslateToSizeInDatabasePages(GetValueFromConfiguration("Raven/Esent/LogBuffers", 8192), 1024),
                LogFileSize          = (logFileSizeInMb * 1024),
                MaxSessions          = MaxSessions,
                MaxCursors           = GetValueFromConfiguration("Raven/Esent/MaxCursors", 2048),
                DbExtensionSize      = TranslateToSizeInDatabasePages(GetValueFromConfiguration("Raven/Esent/DbExtensionSize", 8), 1024 * 1024),
                AlternateDatabaseRecoveryDirectory = path
            };

            if (Environment.OSVersion.Version >= new Version(5, 2))
            {
                // JET_paramEnableIndexCleanup is not supported on WindowsXP
                const int JET_paramEnableIndexCleanup = 54;
                Api.JetSetSystemParameter(jetInstance, JET_SESID.Nil, (JET_param)JET_paramEnableIndexCleanup, 1, null);
            }

            return(instanceParameters);
        }
Example #14
0
 private void ConfigureInstance(JET_INSTANCE jetInstance)
 {
     var parameters = new InstanceParameters(jetInstance)
     {
         CircularLog          = true,
         Recovery             = true,
         CreatePathIfNotExist = true,
         TempDirectory        = Path.Combine(path, "temp"),
         SystemDirectory      = Path.Combine(path, "system"),
         LogFileDirectory     = Path.Combine(path, "logs"),
         MaxVerPages          = 8192,
         MaxTemporaryTables   = 8192,
     };
 }
        public async Task BackTestWithLongFunctionPeriod(AlgoInstanceType algoInstanceType)
        {
            WalletDTO walletDTO = null;

            if (algoInstanceType == AlgoInstanceType.Live)
            {
                walletDTO = await GetExistingWallet();
            }

            // Create algo
            var algoData = await CreateAlgo();

            // Build days offset
            DaysOffsetDTO daysOffsetDTO = BuildDaysOffsetByInstanceType(algoInstanceType);

            // Set Instance start date to be three years ago and end date to be 10 days ago
            int start = 365 * -3;
            int end   = -10;

            daysOffsetDTO.AlgoStartOffset     = start;
            daysOffsetDTO.AlgoEndOffset       = end;
            daysOffsetDTO.SmaShortStartOffset = start;
            daysOffsetDTO.SmaShortEndOffset   = end;
            daysOffsetDTO.SmaShortStartOffset = start;
            daysOffsetDTO.SmaLongEndOffset    = end;

            // Build InstanceParameters
            InstanceParameters instanceParameters = InstanceConfig.ValidMetaData;

            // Build instance request payload
            var instanceForAlgo = InstanceDataBuilder.BuildInstanceData(algoData, walletDTO, algoInstanceType, instanceParameters, daysOffsetDTO);

            // Build save instance url
            var url = algoInstanceType == AlgoInstanceType.Live ? ApiPaths.ALGO_STORE_SAVE_ALGO_INSTANCE : ApiPaths.ALGO_STORE_FAKE_TRADING_INSTANCE_DATA;

            var postInstanceDataResponse = await Consumer.ExecuteRequest(url, Helpers.EmptyDictionary, JsonUtils.SerializeObject(instanceForAlgo), Method.POST);

            AlgoErrorDTO postInstanceDataResponseDTO = JsonUtils.DeserializeJson <AlgoErrorDTO>(postInstanceDataResponse.ResponseJson);

            // Get instance data from DB
            ClientInstanceEntity instanceDataFromDB = await ClientInstanceRepository.TryGetAsync(t => t.AlgoId == algoData.Id) as ClientInstanceEntity;

            Assert.Multiple(() =>
            {
                Assert.That(postInstanceDataResponse.Status, Is.EqualTo(HttpStatusCode.InternalServerError));
                Assert.That(postInstanceDataResponseDTO.ErrorMessage, Does.StartWith("Code:511-InitialWalletBalanceNotCalculated Message:Initial wallet balance could not be calculated. Could not get history price for"));
                // Verify intance is not created in DB
                Assert.That(instanceDataFromDB, Is.Null);
            });
        }
Example #16
0
        public void InitializeInstanceWithJetInit2()
        {
            JET_INSTANCE instance;

            Api.JetCreateInstance2(out instance, Guid.NewGuid().ToString(), "Instance Display Name", CreateInstanceGrbit.None);

            var systemParameters = new InstanceParameters(instance);

            systemParameters.MaxTemporaryTables = 0;
            systemParameters.Recovery           = false;
            systemParameters.NoInformationEvent = true;

            Api.JetInit2(ref instance, InitGrbit.None);
            Api.JetTerm(instance);
        }
        public async Task <InstanceDataDTO> SaveInstance(AlgoDataDTO algoData, AlgoInstanceType instanceType, bool useExistingWallet = true)
        {
            if (instanceType == AlgoInstanceType.Live)
            {
                walletDTO = useExistingWallet == true ? await GetExistingWallet() : await CreateTestWallet();
            }

            // Build days offset
            DaysOffsetDTO daysOffsetDTO = BuildDaysOffsetByInstanceType(instanceType);

            // Build InstanceParameters
            instanceParameters = new InstanceParameters()
            {
                AssetPair                   = "BTCUSD",
                TradedAsset                 = "USD",
                InstanceTradeVolume         = 4,
                InstanceCandleInterval      = CandleTimeInterval.Minute,
                FunctionCandleInterval      = CandleTimeInterval.Day,
                FunctionCandleOperationMode = CandleOperationMode.CLOSE,
                FunctionCapacity            = 4,
                InstanceFunctions           = new List <FunctionType>()
                {
                    FunctionType.SMA_Short, FunctionType.SMA_Long
                }
            };

            // Build instance request payload
            var instanceForAlgo = InstanceDataBuilder.BuildInstanceData(algoData, walletDTO, instanceType, instanceParameters, daysOffsetDTO);

            // Build save instance url
            var url = instanceType == AlgoInstanceType.Live ? ApiPaths.ALGO_STORE_SAVE_ALGO_INSTANCE : ApiPaths.ALGO_STORE_FAKE_TRADING_INSTANCE_DATA;

            string requestBody          = JsonUtils.SerializeObject(instanceForAlgo);
            var    saveInstanceResponse = await Consumer.ExecuteRequest(url, Helpers.EmptyDictionary, requestBody, Method.POST);

            message = $"POST {url} returned status: {saveInstanceResponse.Status} and response: {saveInstanceResponse.ResponseJson}. Expected: {HttpStatusCode.OK}";
            Assert.That(saveInstanceResponse.Status, Is.EqualTo(HttpStatusCode.OK), message);

            var instanceData = JsonUtils.DeserializeJson <InstanceDataDTO>(saveInstanceResponse.ResponseJson);

            // Add Instance to the list so that it can be deleted in the the TearDown
            instancesList.Add(instanceData);

            return(instanceData);
        }
Example #18
0
        public async Task PostInvalidInstanceTradedAsset(AlgoInstanceType algoInstanceType)
        {
            WalletDTO walletDTO = null;

            if (algoInstanceType == AlgoInstanceType.Live)
            {
                walletDTO = await GetExistingWallet();
            }

            // Create algo
            var algoData = await CreateAlgo();

            // Build days offset
            DaysOffsetDTO daysOffsetDTO = BuildDaysOffsetByInstanceType(algoInstanceType);
            // Build InstanceParameters
            InstanceParameters instanceParameters = new InstanceParameters()
            {
                AssetPair                   = "BTCUSD",
                TradedAsset                 = "EUR",
                InstanceTradeVolume         = 2,
                InstanceCandleInterval      = CandleTimeInterval.Minute,
                FunctionCandleInterval      = CandleTimeInterval.Day,
                FunctionCandleOperationMode = CandleOperationMode.CLOSE,
                FunctionCapacity            = 4,
                InstanceFunctions           = new List <FunctionType>()
                {
                    FunctionType.SMA_Short, FunctionType.SMA_Long
                }
            };

            // Build instance request payload
            var instanceForAlgo = InstanceDataBuilder.BuildInstanceData(algoData, walletDTO, algoInstanceType, instanceParameters, daysOffsetDTO);

            string url = ApiPaths.ALGO_STORE_ALGO_INSTANCE_DATA;

            var postInstanceDataResponse = await Consumer.ExecuteRequest(url, Helpers.EmptyDictionary, JsonUtils.SerializeObject(instanceForAlgo), Method.POST);

            AlgoErrorDTO postInstanceDataResponseDTO = JsonUtils.DeserializeJson <AlgoErrorDTO>(postInstanceDataResponse.ResponseJson);

            Assert.That(postInstanceDataResponse.Status, Is.EqualTo(HttpStatusCode.BadRequest), "should be bad response erorr code");

            Assert.That(postInstanceDataResponseDTO.ErrorMessage, Does.Contain("ValidationError Message:Asset <USD> is not valid for asset pair <BTCEUR>"), "we should receive erorr for the invalid traded asset");
        }
Example #19
0
        private LogVerifier(string basename, bool ignored)
        {
            bool flag = false;

            EseHelper.GlobalInit();
            this.m_instanceName = string.Concat(new object[]
            {
                "Log Verifier ",
                basename,
                " ",
                this.GetHashCode()
            });
            Api.JetCreateInstance(out this.m_instance, this.m_instanceName);
            this.m_basename = basename;
            bool jettermNeeded = true;

            try
            {
                InstanceParameters instanceParameters = new InstanceParameters(this.Instance);
                instanceParameters.Recovery           = false;
                instanceParameters.MaxTemporaryTables = 0;
                instanceParameters.NoInformationEvent = true;
                instanceParameters.EventLoggingLevel  = EventLoggingLevels.Min;
                instanceParameters.BaseName           = basename;
                jettermNeeded = false;
                Api.JetInit(ref this.m_instance);
                jettermNeeded = true;
                Api.JetBeginSession(this.Instance, out this.m_sesid, null, null);
                this.m_dbutil       = new JET_DBUTIL();
                this.m_dbutil.sesid = this.Sesid;
                this.m_dbutil.op    = DBUTIL_OP.DumpLogfile;
                this.AssertNotTerminated();
                flag = true;
            }
            finally
            {
                if (!flag)
                {
                    this.Term(jettermNeeded);
                }
            }
        }
Example #20
0
        public void InitializeInstanceWithJetInit3AndRstinfo()
        {
            if (!EsentVersion.SupportsVistaFeatures)
            {
                return;
            }

            JET_INSTANCE instance;

            Api.JetCreateInstance2(out instance, Guid.NewGuid().ToString(), "Instance Display Name", CreateInstanceGrbit.None);

            var systemParameters = new InstanceParameters(instance);

            systemParameters.MaxTemporaryTables = 0;
            systemParameters.Recovery           = false;
            systemParameters.NoInformationEvent = true;

            VistaApi.JetInit3(ref instance, new JET_RSTINFO(), InitGrbit.None);
            Api.JetTerm(instance);
        }
Example #21
0
        public InstanceParameters ConfigureInstance(JET_INSTANCE jetInstance, string path)
        {
            path = Path.GetFullPath(path);
            var logsPath        = path;
            var circularLog     = true;
            var logFileSizeInMb = 64;

            logFileSizeInMb = Math.Max(1, logFileSizeInMb / 4);
            var maxVerPages        = 512;
            var maxVerPagesResult  = TranslateToSizeInVersionPages(maxVerPages, 1024 * 1024);
            var instanceParameters = new InstanceParameters(jetInstance)
            {
                CircularLog          = circularLog,
                Recovery             = true,
                NoInformationEvent   = false,
                CreatePathIfNotExist = true,
                EnableIndexChecking  = true,
                TempDirectory        = Path.Combine(logsPath, "temp"),
                SystemDirectory      = Path.Combine(logsPath, "system"),
                LogFileDirectory     = Path.Combine(logsPath, "logs"),
                MaxVerPages          = maxVerPagesResult,
                PreferredVerPages    = TranslateToSizeInVersionPages((int)(maxVerPagesResult * 0.85), 1024 * 1024),
                BaseName             = "RVN",
                EventSource          = "EsentTest",
                LogBuffers           = TranslateToSizeInDatabasePages(8192, 1024),
                LogFileSize          = (logFileSizeInMb * 1024),
                MaxSessions          = MaxSessions,
                MaxCursors           = 2048,
                DbExtensionSize      = TranslateToSizeInDatabasePages(8, 1024 * 1024),
                AlternateDatabaseRecoveryDirectory = path
            };

            if (Environment.OSVersion.Version >= new Version(5, 2))
            {
                // JET_paramEnableIndexCleanup is not supported on WindowsXP
                const int JET_paramEnableIndexCleanup = 54;
                Api.JetSetSystemParameter(jetInstance, JET_SESID.Nil, (JET_param)JET_paramEnableIndexCleanup, 1, null);
            }

            return(instanceParameters);
        }
Example #22
0
        public void ConfigureInstance(JET_INSTANCE jetInstance, string path)
        {
            path = Path.GetFullPath(path);

            var logsPath = path;

            if (string.IsNullOrEmpty(settings["Raven/Esent/LogsPath"]) == false)
            {
                logsPath = settings["Raven/Esent/LogsPath"].ToFullPath();
            }

            var instanceParameters = new InstanceParameters(jetInstance)
            {
                CircularLog          = GetValueFromConfiguration("Raven/Esent/CircularLog", true),
                Recovery             = true,
                NoInformationEvent   = false,
                CreatePathIfNotExist = true,
                TempDirectory        = Path.Combine(logsPath, "temp"),
                SystemDirectory      = Path.Combine(logsPath, "system"),
                LogFileDirectory     = Path.Combine(logsPath, "logs"),
                MaxVerPages          =
                    TranslateToSizeInDatabasePages(GetValueFromConfiguration("Raven/Esent/MaxVerPages", 128)),
                BaseName    = "RFS",
                EventSource = "RavenFS",
                LogBuffers  =
                    TranslateToSizeInDatabasePages(GetValueFromConfiguration("Raven/Esent/LogBuffers", 16)) / 2,
                LogFileSize     = GetValueFromConfiguration("Raven/Esent/LogFileSize", 1) * 1024,
                MaxSessions     = MaxSessions,
                MaxCursors      = GetValueFromConfiguration("Raven/Esent/MaxCursors", 2048),
                DbExtensionSize =
                    TranslateToSizeInDatabasePages(GetValueFromConfiguration("Raven/Esent/DbExtensionSize",
                                                                             16)),
                AlternateDatabaseRecoveryDirectory = path
            };

            log.Info(@"Esent Settings:
  MaxVerPages      = {0}
  CacheSizeMax     = {1}
  DatabasePageSize = {2}", instanceParameters.MaxVerPages, SystemParameters.CacheSizeMax,
                     SystemParameters.DatabasePageSize);
        }
Example #23
0
        public void VerifyJetVersionIsNotZero()
        {
            JET_INSTANCE instance;
            JET_SESID    sesid;
            uint         version;

            Api.JetCreateInstance(out instance, "JetGetVersion");

            var parameters = new InstanceParameters(instance);

            parameters.Recovery           = false;
            parameters.MaxTemporaryTables = 0;
            parameters.NoInformationEvent = true;

            Api.JetInit(ref instance);
            Api.JetBeginSession(instance, out sesid, string.Empty, string.Empty);
            Api.JetGetVersion(sesid, out version);
            Api.JetTerm(instance);

            Assert.AreNotEqual(0, version);
            Console.WriteLine("Version = 0x{0:X}", version);
        }
Example #24
0
        public async Task PostInvalidAlgoId(AlgoInstanceType algoInstanceType)
        {
            WalletDTO walletDTO = null;

            if (algoInstanceType == AlgoInstanceType.Live)
            {
                walletDTO = await GetExistingWallet();
            }

            // Create algo
            var algoData = await CreateAlgo();

            // Build days offset
            DaysOffsetDTO daysOffsetDTO = BuildDaysOffsetByInstanceType(algoInstanceType);
            // Build InstanceParameters
            InstanceParameters instanceParameters = new InstanceParameters()
            {
                AssetPair                   = "BTCUSD",
                TradedAsset                 = "EUR",
                InstanceTradeVolume         = 2,
                InstanceCandleInterval      = CandleTimeInterval.Minute,
                FunctionCandleInterval      = CandleTimeInterval.Day,
                FunctionCandleOperationMode = CandleOperationMode.CLOSE,
                FunctionCapacity            = 4,
                InstanceFunctions           = new List <FunctionType>()
                {
                    FunctionType.SMA_Short, FunctionType.SMA_Long
                }
            };

            // Build instance request payload
            var instanceForAlgo = InstanceDataBuilder.BuildInstanceData(algoData, walletDTO, algoInstanceType, instanceParameters, daysOffsetDTO, true);

            string url = ApiPaths.ALGO_STORE_ALGO_INSTANCE_DATA;

            var postInstanceDataResponse = await Consumer.ExecuteRequest(url, Helpers.EmptyDictionary, JsonUtils.SerializeObject(instanceForAlgo), Method.POST);

            Assert.That(postInstanceDataResponse.Status, Is.EqualTo(HttpStatusCode.NotFound), "we should receive not found response code");
        }
Example #25
0
        void SetupInstanceParams(EsentDatabase.Settings settings, JET_INSTANCE i, string strFolder, int cursorsPerSession)
        {
            InstanceParameters Parameters = new InstanceParameters(i);

            var adv = settings.advanced;

            m_pathDatabase = Path.Combine(strFolder, adv.FileName);

            // Mostly copy-pasted from Microsoft.Isam.Esent.Collections.Generic.PersistentDictionary<>.__ctor()
            Parameters.SystemDirectory  = strFolder;
            Parameters.LogFileDirectory = strFolder;
            Parameters.TempDirectory    = strFolder;
            Parameters.AlternateDatabaseRecoveryDirectory = strFolder;
            Parameters.CreatePathIfNotExist = true;
            Parameters.BaseName             = adv.BaseName;
            Parameters.EnableIndexChecking  = false;
            Parameters.CircularLog          = true;
            Parameters.CheckpointDepthMax   = 0x4010000;
            Parameters.PageTempDBMin        = 0;
            Parameters.MaxVerPages          = adv.MaxVerPages;

            Parameters.LogFileSize = adv.kbLogFileSize;
            Parameters.LogBuffers  = adv.LogBuffers.Value;

            Parameters.MaxSessions = settings.maxConcurrentSessions;

            if (cursorsPerSession > 0)
            {
#if !NETFX_CORE
                // On desktop and servers user can duplicate cursors, that's why we need to increase that limit.
                cursorsPerSession = Math.Max(cursorsPerSession * 2, cursorsPerSession + 8);
#endif
                // Both esent.dll ant this library use internal tables, e.g. for schema. Hence that 16 extra cursors.
                Parameters.MaxCursors = cursorsPerSession * settings.maxConcurrentSessions + 16;
            }

            // Ext. parameters
            Api.JetSetSystemParameter(i, JET_SESID.Nil, Ext.JET_paramIndexTuplesLengthMin, adv.IndexTuplesLengthMin, null);
        }
Example #26
0
        public InstanceParameters ConfigureInstance(JET_INSTANCE jetInstance, string path)
        {
            path = Path.GetFullPath(path);
            var logsPath = path;

            if (string.IsNullOrEmpty(configuration.Settings["Raven/Esent/LogsPath"]) == false)
            {
                logsPath = configuration.Settings["Raven/Esent/LogsPath"].ToFullPath();
            }
            var circularLog     = GetValueFromConfiguration("Raven/Esent/CircularLog", true);
            var logFileSizeInMb = GetValueFromConfiguration("Raven/Esent/LogFileSize", 64);

            logFileSizeInMb = Math.Max(1, logFileSizeInMb / 4);
            var instanceParameters = new InstanceParameters(jetInstance)
            {
                CircularLog          = circularLog,
                Recovery             = true,
                NoInformationEvent   = false,
                CreatePathIfNotExist = true,
                EnableIndexChecking  = true,
                TempDirectory        = Path.Combine(logsPath, "temp"),
                SystemDirectory      = Path.Combine(logsPath, "system"),
                LogFileDirectory     = Path.Combine(logsPath, "logs"),
                MaxVerPages          = TranslateToSizeInVersionPages(GetValueFromConfiguration("Raven/Esent/MaxVerPages", 512), 1024 * 1024),
                PreferredVerPages    = TranslateToSizeInVersionPages(GetValueFromConfiguration("Raven/Esent/PreferredVerPages", 472), 1024 * 1024),
                BaseName             = "RVN",
                EventSource          = "Raven",
                LogBuffers           = TranslateToSizeInDatabasePages(GetValueFromConfiguration("Raven/Esent/LogBuffers", 8192), 1024),
                LogFileSize          = (logFileSizeInMb * 1024),
                MaxSessions          = MaxSessions,
                MaxCursors           = GetValueFromConfiguration("Raven/Esent/MaxCursors", 2048),
                DbExtensionSize      = TranslateToSizeInDatabasePages(GetValueFromConfiguration("Raven/Esent/DbExtensionSize", 8), 1024 * 1024),
                AlternateDatabaseRecoveryDirectory = path
            };

            return(instanceParameters);
        }
Example #27
0
        private void GetParameters()
        {
            // get instance parameters
            List <Parameter> instanceParameters = new List <Parameter>();

            foreach (Parameter parameter in NestedFamilyInstance.Parameters)
            {
                if (NestedFamilyInstance.Document.FamilyManager.CanElementParameterBeAssociated(parameter))
                {
                    instanceParameters.Add(parameter);
                }
            }

            instanceParameters.Sort((p1, p2) => string.Compare(p1.Definition.Name, p2.Definition.Name, StringComparison.Ordinal));
            instanceParameters.ForEach(parameter =>
            {
                InstanceParameters.Add(new NestedFamilyParameterModel(parameter, this, true, _mainViewModel));
            });

            // get type parameters
            List <Parameter> typeParameters = new List <Parameter>();

            foreach (Parameter parameter in NestedFamilyInstance.Symbol.Parameters)
            {
                if (NestedFamilyInstance.Document.FamilyManager.CanElementParameterBeAssociated(parameter))
                {
                    typeParameters.Add(parameter);
                }
            }

            typeParameters.Sort((p1, p2) => string.Compare(p1.Definition.Name, p2.Definition.Name, StringComparison.Ordinal));
            typeParameters.ForEach(parameter =>
            {
                TypeParameters.Add(new NestedFamilyParameterModel(parameter, this, false, _mainViewModel));
            });
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="DurableCommitCallback"/> class. 
        /// The constructor.
        /// </summary>
        /// <param name="instance">
        /// The instance with which to associate the callback.
        /// </param>
        /// <param name="wrappedCallback">
        /// The managed code callback to call.
        /// </param>
        public DurableCommitCallback(
            JET_INSTANCE instance,
            JET_PFNDURABLECOMMITCALLBACK wrappedCallback)
        {
            this.instance = instance;
            this.wrappedCallback = wrappedCallback;
            this.wrapperCallback = this.NativeDurableCommitCallback;

            #if !MANAGEDESENT_ON_WSA // RuntimeHelpers works differently in Windows Store Apps.
            if (this.wrappedCallback != null)
            {
                RuntimeHelpers.PrepareMethod(this.wrappedCallback.Method.MethodHandle);
            }

            RuntimeHelpers.PrepareMethod(typeof(DurableCommitCallback).GetMethod("NativeDurableCommitCallback", BindingFlags.NonPublic | BindingFlags.Instance).MethodHandle);
            #endif

            InstanceParameters instanceParameters = new InstanceParameters(this.instance);

            // This might be null.
            instanceParameters.SetDurableCommitCallback(this.wrapperCallback);

            this.ResourceWasAllocated();
        }
Example #29
0
        public void VerifyJetVersionOverride()
        {
            JET_INSTANCE instance;
            JET_SESID    sesid;
            uint         version;

            IJetApi savedImpl = Api.Impl;

            try
            {
                Api.Impl = new JetApi(Constants.VistaVersion);

                Api.JetCreateInstance(out instance, "JetGetVersionOverride");

                var parameters = new InstanceParameters(instance);
                parameters.Recovery           = false;
                parameters.MaxTemporaryTables = 0;
                parameters.NoInformationEvent = true;

                Api.JetInit(ref instance);
                Api.JetBeginSession(instance, out sesid, string.Empty, string.Empty);
#if MANAGEDESENT_ON_WSA // Not exposed in MSDK
                version = Constants.VistaVersion;
#else
                Api.JetGetVersion(sesid, out version);
#endif
                Api.JetTerm(instance);

                Assert.AreEqual(Constants.VistaVersion, version);
                EseInteropTestHelper.ConsoleWriteLine("Version = 0x{0:X}", version);
            }
            finally
            {
                Api.Impl = savedImpl;
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="DurableCommitCallback"/> class.
        /// The constructor.
        /// </summary>
        /// <param name="instance">
        /// The instance with which to associate the callback.
        /// </param>
        /// <param name="wrappedCallback">
        /// The managed code callback to call.
        /// </param>
        public DurableCommitCallback(
            JET_INSTANCE instance,
            JET_PFNDURABLECOMMITCALLBACK wrappedCallback)
        {
            this.instance        = instance;
            this.wrappedCallback = wrappedCallback;
            this.wrapperCallback = this.NativeDurableCommitCallback;

#if !MANAGEDESENT_ON_WSA // RuntimeHelpers works differently in Windows Store Apps.
            if (this.wrappedCallback != null)
            {
                RuntimeHelpers.PrepareMethod(this.wrappedCallback.Method.MethodHandle);
            }

            RuntimeHelpers.PrepareMethod(typeof(DurableCommitCallback).GetMethod("NativeDurableCommitCallback", BindingFlags.NonPublic | BindingFlags.Instance).MethodHandle);
#endif

            InstanceParameters instanceParameters = new InstanceParameters(this.instance);

            // This might be null.
            instanceParameters.SetDurableCommitCallback(this.wrapperCallback);

            this.ResourceWasAllocated();
        }
Example #31
0
 public void PutInstanceParameter(InstanceParameter instanceParameter)
 {
     InstanceParameters.Add(instanceParameter);
 }