Exemple #1
0
        private void InitializeDataSource()
        {
            var entityRegistry = ConfigManager.GetService <IEntityRegistry>();

            var database = (Database)((EntityRegistry)entityRegistry).Storage;

            if (database == null)
            {
                return;
            }

            var conStr = new DbConnectionStringBuilder
            {
                ConnectionString = database.ConnectionString
            };

            var dbFile = (string)conStr.Cast <KeyValuePair <string, object> >().ToDictionary(StringComparer.InvariantCultureIgnoreCase).TryGetValue("Data Source");

            if (dbFile == null)
            {
                return;
            }

            dbFile = dbFile.Replace("%Documents%", Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));

            conStr["Data Source"]     = dbFile;
            database.ConnectionString = conStr.ToString();

            dbFile.CreateDirIfNotExists();

            if (!File.Exists(dbFile))
            {
                Properties.Resources.StockSharp.Save(dbFile);
            }
        }
Exemple #2
0
        private void TryUpdateDatabaseVersion()
        {
            var versionField  = new VoidField <string>("Version");
            var getVersionCmd = ((Database)Storage).GetCommand(Query.Select(versionField).From("Settings"), null, new FieldList(), new FieldList());

            var dbVersion = getVersionCmd.ExecuteScalar <Version>(new SerializationItemCollection());

            if (dbVersion.CompareTo(LatestVersion) == 0)
            {
                return;
            }

            ConfigManager
            .GetService <LogManager>()
            .Application
            .AddInfoLog(LocalizedStrings.Str3628Params.Put(dbVersion, TypeHelper.ApplicationName, LatestVersion));

            var database      = (Database)Storage;
            var conStrBuilder = new DbConnectionStringBuilder {
                ConnectionString = database.ConnectionString
            };

            try
            {
                var path = (string)conStrBuilder.Cast <KeyValuePair <string, object> >().ToDictionary(StringComparer.InvariantCultureIgnoreCase).TryGetValue("Data Source");

                if (path == null)
                {
                    throw new InvalidOperationException(LocalizedStrings.Str2895);
                }

                var targetPath = "{0}.bak.{1:yyyyMMdd}".Put(path, DateTime.Now);

                if (File.Exists(targetPath))
                {
                    File.Delete(targetPath);
                }

                File.Move(path, targetPath);
                Resources.StockSharp.Save(path);

                UpdateDatabaseVersion();
            }
            catch (Exception ex)
            {
                ex.LogError(LocalizedStrings.Str3629Params);

                GuiDispatcher.GlobalDispatcher.AddSyncAction(() =>
                {
                    new MessageBoxBuilder()
                    .Text(LocalizedStrings.Str3630Params.Put(Environment.NewLine, ex.Message))
                    .Warning()
                    .Show();

                    Application.Current.Shutdown(-1);
                });
            }
        }
Exemple #3
0
        /// <summary>
        /// Builds a connection string dictionary that is parsed from a string.
        /// </summary>
        /// <remarks>
        /// The format of the string must follow the format that is understood by the <see cref="DbConnectionStringBuilder"/> class.
        /// </remarks>
        /// <param name="connectionString"></param>
        /// <returns></returns>
        public static IDictionary <string, string> ToDictionary(this string connectionString)
        {
            var builder = new DbConnectionStringBuilder {
                ConnectionString = connectionString
            };
            var connection = builder.Cast <KeyValuePair <string, object> >().ToDictionary(pair => pair.Key, pair => pair.Value.ToString());

            return(new Dictionary <string, string>(connection, StringComparer.OrdinalIgnoreCase));
        }
        /// <summary>
        /// Converts a ; separated string into a dictionary
        /// </summary>
        /// <param name="connectionString">String to parse</param>
        /// <returns>Dictionary of properties from the connection string</returns>
        public static IDictionary <string, string> ToDictionary(this string connectionString)
        {
            try
            {
                DbConnectionStringBuilder source = new DbConnectionStringBuilder
                {
                    ConnectionString = connectionString
                };

                Dictionary <string, string> dictionary = source.Cast <KeyValuePair <string, object> >().
                                                         ToDictionary((KeyValuePair <string, object> pair) => pair.Key,
                                                                      (KeyValuePair <string, object> pair) => pair.Value != null ? pair.Value.ToString() : string.Empty);
                return(new Dictionary <string, string>(dictionary, StringComparer.OrdinalIgnoreCase));
            }
            catch
            {
                //ignore
            }
            return(new Dictionary <string, string>());
        }
Exemple #5
0
        /// <summary>
        /// First time database initialization.
        /// </summary>
        /// <param name="database">The database.</param>
        /// <param name="databaseRaw">Raw bytes of database file.</param>
        /// <param name="init">Initialization callback.</param>
        /// <returns>Path to the database file.</returns>
        public static string FirstTimeInit(this Database database, byte[] databaseRaw, Action <Database> init = null)
        {
            if (database == null)
            {
                throw new ArgumentNullException(nameof(database));
            }

            if (databaseRaw == null)
            {
                throw new ArgumentNullException(nameof(databaseRaw));
            }

            var conStr = new DbConnectionStringBuilder
            {
                ConnectionString = database.ConnectionString
            };

            var dbFile = (string)conStr.Cast <KeyValuePair <string, object> >().ToDictionary(StringComparer.InvariantCultureIgnoreCase).TryGetValue("Data Source");

            if (dbFile == null)
            {
                return(null);
            }

            dbFile = dbFile.ToFullPathIfNeed();

            conStr["Data Source"]     = dbFile;
            database.ConnectionString = conStr.ToString();

            dbFile.CreateDirIfNotExists();

            if (!File.Exists(dbFile))
            {
                databaseRaw.Save(dbFile);
                UpdateDatabaseWalMode(database);

                init?.Invoke(database);
            }

            return(dbFile);
        }
        private void CheckDatabase()
        {
            if (_entityRegistry.Version.Compare(HydraEntityRegistry.LatestVersion) == 0)
            {
                return;
            }

            var database = (Database)_entityRegistry.Storage;

            var conStrBuilder = new DbConnectionStringBuilder {
                ConnectionString = database.ConnectionString
            };

            var path = (string)conStrBuilder.Cast <KeyValuePair <string, object> >().ToDictionary(StringComparer.InvariantCultureIgnoreCase).TryGetValue("Data Source");

            if (path == null)
            {
                throw new InvalidOperationException(LocalizedStrings.Str2895);
            }

            File.Copy(path, "{0}.bak.{1:yyyyMMdd}".Put(path, DateTime.Now), true);

            if (_entityRegistry.Version.Compare(new Version(2, 5)) == 0)
            {
                var schema = typeof(Security).GetSchema();

                var binaryOptType = Query
                                    .AlterTable(schema)
                                    .AddColumn(schema.Fields["BinaryOptionType"]);

                Execute(binaryOptType, schema);

                var multiplier = Query
                                 .AlterTable(schema)
                                 .AddColumn(schema.Fields["Multiplier"]);

                Execute(multiplier, schema);

                var update = Query
                             .Update(schema)
                             .Set(new SetPart("Multiplier", "VolumeStep"));

                Execute(update, schema);

                _entityRegistry.Version = new Version(2, 6);
            }

            if (_entityRegistry.Version.Compare(new Version(2, 6)) == 0)
            {
                var schema = typeof(News).GetSchema();

                var localTime = Query
                                .AlterTable(schema)
                                .AddColumn(schema.Fields["LocalTime"]);

                Execute(localTime, schema);

                var serverTime = Query
                                 .AlterTable(schema)
                                 .AddColumn(schema.Fields["ServerTime"]);

                Execute(serverTime, schema);

                _entityRegistry.Version = new Version(2, 7);
            }

            if (_entityRegistry.Version.Compare(new Version(2, 7)) == 0)
            {
                Execute(@"
					update HydraTaskSecurity
					set
						[Security] = 'ALL@ALL'
					where
						[Security] LIKE 'ALL@%'"                        );

                _entityRegistry.Version = new Version(2, 8);
            }

            if (_entityRegistry.Version.Compare(new Version(2, 8)) == 0)
            {
                Execute(@"
					update HydraTaskSecurity
					set
						[CandleSeries] = replace([CandleSeries], '<From>01/01/0001 00:00:00</From>', '<From>01/01/0001 00:00:00 +00:00</From>')"                        );

                Execute(@"
					update HydraTaskSecurity
					set
						[CandleSeries] = replace([CandleSeries], '<To>9999-12-31T23:59:59.9999999</To>', '<To>12/31/9999 23:59:59 +00:00</To>')"                        );

                _entityRegistry.Version = new Version(2, 9);
            }

            if (_entityRegistry.Version.Compare(new Version(2, 9)) == 0)
            {
                Execute(@"
					update HydraTaskSettings
					set
						[ExtensionInfo] = replace([ExtensionInfo], '<From>01/01/0001 00:00:00</From>', '<From>01/01/0001 00:00:00 +00:00</From>')"                        );

                _entityRegistry.Version = new Version(2, 10);
            }

            if (_entityRegistry.Version.Compare(new Version(2, 10)) == 0)
            {
                Execute(@"
					alter table [Security] RENAME TO tmp;
					create table [Security] (
						[Id] varchar NOT NULL, [Name] varchar, [Code] varchar NOT NULL, [Class] varchar, [ShortName] varchar,
						[PriceStep] real NOT NULL, [VolumeStep] real NOT NULL, [Multiplier] real NOT NULL, [Decimals] integer NOT NULL,
						[Type] integer, [ExpiryDate] varchar, [SettlementDate] varchar, [ExtensionInfo] text,
						[Currency] integer, [Board] varchar NOT NULL, [UnderlyingSecurityId] varchar, [Strike] real,
						[OptionType] integer, [BinaryOptionType] varchar, [Bloomberg] varchar, [Cusip] varchar,
						[Isin] varchar, [IQfeed] varchar, [Ric] varchar, [Sedol] varchar, [InteractiveBrokers] integer,
						[Plaza] varchar);
					insert into [Security] select * from tmp;
					drop table tmp;"                    );

                _entityRegistry.Version = new Version(2, 11);
            }

            if (_entityRegistry.Version.Compare(new Version(2, 11)) == 0)
            {
                UpdateDatabaseWalMode();

                _entityRegistry.Version = new Version(2, 12);
            }

            if (_entityRegistry.Version.Compare(new Version(2, 12)) == 0)
            {
                Execute(@"
						alter table [HydraTaskSecurity] add column ExecutionCount integer;
						alter table [HydraTaskSecurity] add column ExecutionLastTime time;"                        );

                _entityRegistry.Version = new Version(2, 13);
            }

            if (_entityRegistry.Version.Compare(new Version(2, 13)) == 0)
            {
                Execute("update [HydraTaskSecurity] set ExecutionCount = 0 where ExecutionCount is null");
                Execute("update [HydraTaskSecurity] set CandleCount = 0 where CandleCount is null");

                _entityRegistry.Version = new Version(2, 14);
            }

            if (_entityRegistry.Version.Compare(new Version(2, 14)) == 0)
            {
                Execute(@"
					alter table [Security] RENAME TO tmp;
					create table [Security] (
						[Id] varchar NOT NULL, [Name] varchar, [Code] varchar NOT NULL, [Class] varchar, [ShortName] varchar,
						[PriceStep] real, [VolumeStep] real, [Multiplier] real, [Decimals] integer,
						[Type] integer, [ExpiryDate] varchar, [SettlementDate] varchar, [ExtensionInfo] text,
						[Currency] integer, [Board] varchar NOT NULL, [UnderlyingSecurityId] varchar, [Strike] real,
						[OptionType] integer, [BinaryOptionType] varchar, [Bloomberg] varchar, [Cusip] varchar,
						[Isin] varchar, [IQfeed] varchar, [Ric] varchar, [Sedol] varchar, [InteractiveBrokers] integer,
						[Plaza] varchar);
					insert into [Security] select * from tmp;
					drop table tmp;"                    );

                _entityRegistry.Version = new Version(2, 15);
            }

            if (_entityRegistry.Version.Compare(new Version(2, 15)) == 0)
            {
                Execute(@"
					alter table [ExchangeBoard] add column TimeZone varchar;
					update [ExchangeBoard]
					set
						TimeZone = (select [TimeZoneInfo] from [Exchange] where [Name] = [ExchangeBoard].[Exchange])"                        );

                _entityRegistry.Version = new Version(2, 16);
            }

            if (_entityRegistry.Version.Compare(new Version(2, 16)) == 0)
            {
                Execute(@"
					alter table [HydraTaskSecurity] RENAME TO tmp;
					CREATE TABLE HydraTaskSecurity (Id integer NOT NULL PRIMARY KEY AUTOINCREMENT,
						Security varchar NOT NULL,DataTypes varchar NOT NULL,
						CandleSeries text NULL,Settings binary NOT NULL,
						TradeCount integer NOT NULL,TradeLastTime time,
						DepthCount integer NOT NULL,DepthLastTime time,
						OrderLogCount integer NOT NULL,OrderLogLastTime time,
						Level1Count integer NOT NULL,Level1LastTime time,
						CandleCount integer NOT NULL,CandleLastTime time,
						ExecutionCount integer NOT NULL,ExecutionLastTime time);
					insert into [HydraTaskSecurity] select * from tmp;
					drop table tmp;

					update HydraTaskSecurity set DataTypes = '<DataTypeArray />'"                    );

                _entityRegistry.Version = new Version(2, 17);
                return;
            }

            GuiDispatcher.GlobalDispatcher.AddSyncAction(() =>
            {
                Mouse.OverrideCursor = null;

                new MessageBoxBuilder()
                .Text(LocalizedStrings.Str3628Params.Put(_entityRegistry.Version, TypeHelper.ApplicationName, HydraEntityRegistry.LatestVersion))
                .Warning()
                .Owner(this)
                .Show();
            });

            try
            {
                File.WriteAllBytes(path, Properties.Resources.StockSharp);

                // обнуляем настройки, так как БД перезаписана на новую
                _entityRegistry.Settings = new HydraSettingsRegistry();
                _entityRegistry.Version  = HydraEntityRegistry.LatestVersion;
            }
            catch (Exception ex)
            {
                ex.LogError();

                GuiDispatcher.GlobalDispatcher.AddSyncAction(() =>
                {
                    new MessageBoxBuilder()
                    .Text(LocalizedStrings.Str2896)
                    .Warning()
                    .Owner(this)
                    .Show();

                    Close();
                });
            }
        }
Exemple #7
0
        internal static string GetProviderInvariantNameByConnectionString(string connectionString, IConfiguration config, out string cleanConnectionString)
        {
            cleanConnectionString = connectionString;

            if (connectionString == null)
            {
                return(null);
            }

            var builder = new DbConnectionStringBuilder {
                ConnectionString = connectionString
            };

            if (builder.TryGetValue("provider", out object providerValue))
            {
                builder.Remove("provider");

                cleanConnectionString = builder.ConnectionString;

                return(providerValue.ToString());
            }

            var persistSecurityInfo = false;

            if (builder.TryGetValue("persist security info", out object persistSecurityInfoValue))
            {
                persistSecurityInfo = Convert.ToBoolean(persistSecurityInfoValue);
            }

            var lostPassword = !persistSecurityInfo && !builder.ContainsKey("pwd") && !builder.ContainsKey("password");

            if (!lostPassword)
            {
#if NETSTANDARD
                dynamic connectionStrings = (config ?? ConfigurationFactory.DefaultConfiguration).SystemConfiguration?.ConnectionStrings();

                if (connectionStrings == null)
                {
                    connectionStrings = ConfigurationManager.ConnectionStrings;
                }
#else
                var connectionStrings = ConfigurationManager.ConnectionStrings;
#endif
                for (var i = 0; i < connectionStrings.Count; i++)
                {
                    var connectionStringsSettings = connectionStrings[i];
                    if (string.Equals(connectionStringsSettings.ConnectionString, connectionString, StringComparison.OrdinalIgnoreCase))
                    {
                        return(connectionStringsSettings.ProviderName);
                    }
                }
            }
            else
            {
                if (builder.TryGetValue("uid", out object uid))
                {
                    builder.Remove("uid");
                    builder["user id"] = uid;
                }

#if NETSTANDARD
                dynamic connectionStrings = (config ?? ConfigurationFactory.DefaultConfiguration).SystemConfiguration?.ConnectionStrings();

                if (connectionStrings == null)
                {
                    connectionStrings = ConfigurationManager.ConnectionStrings;
                }
#else
                var connectionStrings = ConfigurationManager.ConnectionStrings;
#endif
                for (var i = 0; i < connectionStrings.Count; i++)
                {
                    var connectionStringsSettings = connectionStrings[i];

                    var otherBuilder = new DbConnectionStringBuilder {
                        ConnectionString = connectionStringsSettings.ConnectionString
                    };
                    otherBuilder.Remove("pwd");
                    otherBuilder.Remove("password");

                    if (otherBuilder.TryGetValue("uid", out object otherUid))
                    {
                        otherBuilder.Remove("uid");
                        otherBuilder["user id"] = otherUid;
                    }

                    if (otherBuilder.Count != builder.Count)
                    {
                        continue;
                    }

                    var equivalenCount = builder.Cast <KeyValuePair <string, object> >()
                                         .Select(p => otherBuilder.TryGetValue(p.Key, out var value) && string.Equals(Convert.ToString(value), Convert.ToString(p.Value), StringComparison.OrdinalIgnoreCase) ? 1 : 0)
                                         .Sum();

                    if (equivalenCount == builder.Count)
                    {
                        return(connectionStringsSettings.ProviderName);
                    }
                }
            }

            return(null);
        }
Exemple #8
0
        private void InitializeDataSource()
        {
            _storageRegistry = new StorageRegistry();
            ConfigManager.RegisterService(_storageRegistry);

            _entityRegistry = (HydraEntityRegistry)ConfigManager.GetService <IEntityRegistry>();
            _entityRegistry.TasksSettings.Recycle = false;
            ((SecurityList)_entityRegistry.Securities).BulkLoad = true;

            var database = (Database)_entityRegistry.Storage;

            if (database != null)
            {
                var conStr = new DbConnectionStringBuilder
                {
                    ConnectionString = database.ConnectionString
                };

                _dbFile = (string)conStr.Cast <KeyValuePair <string, object> >().ToDictionary(StringComparer.InvariantCultureIgnoreCase).TryGetValue("Data Source");

                if (_dbFile != null)
                {
                    _dbFile = _dbFile.Replace("%Documents%", Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));

                    conStr["Data Source"]     = _dbFile;
                    database.ConnectionString = conStr.ToString();

                    _dbFile.CreateDirIfNotExists();

                    if (!File.Exists(_dbFile))
                    {
                        Properties.Resources.StockSharp.Save(_dbFile);
                        _entityRegistry.Version = HydraEntityRegistry.LatestVersion;

                        UpdateDatabaseWalMode();
                    }
                }
            }

            CheckDatabase();

            ConfigManager.RegisterService <IExchangeInfoProvider>(new ExchangeInfoProvider(_entityRegistry));

            var allSec = _entityRegistry.Securities.GetAllSecurity();

            if (allSec != null)
            {
                return;
            }

            _entityRegistry.Securities.Add(new Security
            {
                Id   = Core.Extensions.AllSecurityId,
                Code = "ALL",
                //Class = task.GetDisplayName(),
                Name          = LocalizedStrings.Str2835,
                Board         = ExchangeBoard.Associated,
                ExtensionInfo = new Dictionary <object, object>(),
            });
            _entityRegistry.Securities.DelayAction.WaitFlush();
        }
Exemple #9
0
        public static string GetProviderInvariantNameByConnectionString(string connectionString)
        {
            if (connectionString == null)
            {
                return(null);
            }

            var builder = new DbConnectionStringBuilder {
                ConnectionString = connectionString
            };

            object providerValue;

            if (builder.TryGetValue("provider", out providerValue))
            {
                return(providerValue.ToString());
            }

            var    persistSecurityInfo = false;
            object persistSecurityInfoValue;

            if (builder.TryGetValue("persist security info", out persistSecurityInfoValue))
            {
                persistSecurityInfo = Convert.ToBoolean(persistSecurityInfoValue);
            }

            var lostPassword = !persistSecurityInfo && !builder.ContainsKey("pwd") && !builder.ContainsKey("password");

            if (!lostPassword)
            {
                for (var i = 0; i < ConfigurationManager.ConnectionStrings.Count; i++)
                {
                    var config = ConfigurationManager.ConnectionStrings[i];
                    if (string.Equals(config.ConnectionString, connectionString, StringComparison.OrdinalIgnoreCase))
                    {
                        return(config.ProviderName);
                    }
                }
            }
            else
            {
                object uid;
                if (builder.TryGetValue("uid", out uid))
                {
                    builder.Remove("uid");
                    builder["user id"] = uid;
                }

                for (var i = 0; i < ConfigurationManager.ConnectionStrings.Count; i++)
                {
                    var config = ConfigurationManager.ConnectionStrings[i];

                    var otherBuilder = new DbConnectionStringBuilder {
                        ConnectionString = config.ConnectionString
                    };
                    otherBuilder.Remove("pwd");
                    otherBuilder.Remove("password");

                    object otherUid;
                    if (otherBuilder.TryGetValue("uid", out otherUid))
                    {
                        otherBuilder.Remove("uid");
                        otherBuilder["user id"] = otherUid;
                    }

                    if (otherBuilder.Count != builder.Count)
                    {
                        continue;
                    }

                    var equivalenCount = builder.Cast <KeyValuePair <string, object> >().Select(p =>
                    {
                        object value;
                        return(otherBuilder.TryGetValue(p.Key, out value) && string.Equals(Convert.ToString(value), Convert.ToString(p.Value), StringComparison.OrdinalIgnoreCase) ? 1 : 0);
                    }).Sum();

                    if (equivalenCount == builder.Count)
                    {
                        return(config.ProviderName);
                    }
                }
            }

            return(null);
        }