Exemplo n.º 1
0
        //, Model.View.ViewPrefixes)
        public View(DatabaseTypes dalAssemblyName, ConnectionStringHelper connectionString)
            : base(dalAssemblyName, connectionString)
        {
            IView dal = DALFactory.DataAccess.CreateView(dalAssemblyName, ConnectionString);

            Model.View[] views = dal.GetViews();
            //InitiateAlias(views);
            InitialCreateFilters(views);

            _scriptObjects = new List<Model.View>(views);
        }
Exemplo n.º 2
0
        public void AddDatabase(string name, DatabaseTypes databaseType, ConnectionStringHelper connectionString, string[] tablePrefixes, string[] viewPrefixes, string[] storedProcedurePredixes)
        {
            Model.Table.TablePrefixes = new List<string>(tablePrefixes);
            Model.View.ViewPrefixes = new List<string>(viewPrefixes);
            Model.StoredProcedure.StoredProcedurePrefixes = new List<string>(storedProcedurePredixes);

            Table bllTable = new Table(databaseType, connectionString);
            View bllView = new View(databaseType, connectionString);
            StoredProcedure bllStoredProcedure = new StoredProcedure(databaseType, connectionString);

            Model.Database database = new Model.Database(name, connectionString, databaseType, bllTable.Tables, bllView.Views, bllStoredProcedure.StoredProcedures);
            AddDatabase(database);
        }
Exemplo n.º 3
0
        //, Model.Table.TablePrefixes)
        public Table(DatabaseTypes dalAssemblyName, ConnectionStringHelper connectionString)
            : base(dalAssemblyName, connectionString)
        {
            ITable dal = DALFactory.DataAccess.CreateTable(dalAssemblyName, ConnectionString);

            Model.Table[] tables = dal.GetTables();
            //InitiateAlias(tables);
            InitialUpdateIndexes(tables);
            InitialUpdateKeys(tables);
            InitialCreateFilters(tables);
            InitialUpdateRelationships(tables);
            // GFH: I don't think that we should automatically add MapColumns, because we don't know what makes sense in the user's
            // schema. Users get very confused as to why Mapped columns suddenly appear - causes more confusion than anything else.
            //InitialUpdateMapColumns(tables);

            _scriptObjects = new List<Model.Table>(tables);
        }
Exemplo n.º 4
0
        //, Model.StoredProcedure.StoredProcedurePrefixes)
        public StoredProcedure(DatabaseTypes dalAssemblyName, ConnectionStringHelper connectionString)
            : base(dalAssemblyName, connectionString)
        {
            IStoredProcedure dal = DALFactory.DataAccess.CreateStoredProcedure(DalAssemblyName, ConnectionString);

            Model.StoredProcedure[] storedProcedures = dal.GetStoredProcedures();
            //InitiateAlias(storedProcedures);
            //this.ErrorMessages.AddRange(dal.
            InitialCreateFilters(storedProcedures);

            foreach (Model.StoredProcedure sp in storedProcedures)
            {
                foreach (string error in sp.Errors)
                {
                    ErrorMessages.Add(error);
                }
            }
            _scriptObjects = new List<Model.StoredProcedure>(storedProcedures);
        }
Exemplo n.º 5
0
        public async Task TestEdgeHubConnection()
        {
            const string EdgeDeviceId                   = "testHubEdgeDevice1";
            var          twinMessageConverter           = new TwinMessageConverter();
            var          twinCollectionMessageConverter = new TwinCollectionMessageConverter();
            var          messageConverterProvider       = new MessageConverterProvider(
                new Dictionary <Type, IMessageConverter>()
            {
                { typeof(Message), new DeviceClientMessageConverter() },
                { typeof(Twin), twinMessageConverter },
                { typeof(TwinCollection), twinCollectionMessageConverter }
            });

            string iotHubConnectionString = await SecretsHelper.GetSecretFromConfigKey("iotHubConnStrKey");

            IotHubConnectionStringBuilder iotHubConnectionStringBuilder = IotHubConnectionStringBuilder.Create(iotHubConnectionString);
            RegistryManager registryManager = RegistryManager.CreateFromConnectionString(iotHubConnectionString);
            await registryManager.OpenAsync();

            string iothubHostName   = iotHubConnectionStringBuilder.HostName;
            var    identityProvider = new IdentityProvider(iothubHostName);
            var    identityFactory  = new ClientCredentialsFactory(identityProvider);

            (string edgeDeviceId, string deviceConnStr) = await RegistryManagerHelper.CreateDevice(EdgeDeviceId, iotHubConnectionString, registryManager, true, false);

            string edgeHubConnectionString = $"{deviceConnStr};ModuleId={EdgeHubModuleId}";

            IClientCredentials edgeHubCredentials = identityFactory.GetWithConnectionString(edgeHubConnectionString);
            string             sasKey             = ConnectionStringHelper.GetSharedAccessKey(deviceConnStr);
            var signatureProvider       = new SharedAccessKeySignatureProvider(sasKey);
            var credentialsCache        = Mock.Of <ICredentialsCache>();
            var cloudConnectionProvider = new CloudConnectionProvider(
                messageConverterProvider,
                1,
                new ClientProvider(),
                Option.None <UpstreamProtocol>(),
                new ClientTokenProvider(signatureProvider, iothubHostName, edgeDeviceId, TimeSpan.FromMinutes(60)),
                Mock.Of <IDeviceScopeIdentitiesCache>(),
                credentialsCache,
                edgeHubCredentials.Identity,
                TimeSpan.FromMinutes(60),
                true,
                TimeSpan.FromSeconds(20));
            var connectionManager = new ConnectionManager(cloudConnectionProvider, Mock.Of <ICredentialsCache>(), identityProvider);

            try
            {
                Mock.Get(credentialsCache)
                .Setup(c => c.Get(edgeHubCredentials.Identity))
                .ReturnsAsync(Option.Some(edgeHubCredentials));
                Assert.NotNull(edgeHubCredentials);
                Assert.NotNull(edgeHubCredentials.Identity);

                // Set Edge hub desired properties
                await this.SetDesiredProperties(registryManager, edgeDeviceId);

                var endpointFactory = new EndpointFactory(connectionManager, new RoutingMessageConverter(), edgeDeviceId);
                var routeFactory    = new EdgeRouteFactory(endpointFactory);

                var            dbStoreProvider            = new InMemoryDbStoreProvider();
                IStoreProvider storeProvider              = new StoreProvider(dbStoreProvider);
                IEntityStore <string, TwinInfo> twinStore = storeProvider.GetEntityStore <string, TwinInfo>("twins");
                var      twinManager             = new TwinManager(connectionManager, twinCollectionMessageConverter, twinMessageConverter, Option.Some(twinStore));
                var      routerConfig            = new RouterConfig(Enumerable.Empty <Route>());
                TimeSpan defaultTimeout          = TimeSpan.FromSeconds(60);
                var      endpointExecutorFactory = new SyncEndpointExecutorFactory(new EndpointExecutorConfig(defaultTimeout, new FixedInterval(0, TimeSpan.FromSeconds(1)), defaultTimeout, true));
                Router   router = await Router.CreateAsync(Guid.NewGuid().ToString(), iothubHostName, routerConfig, endpointExecutorFactory);

                IInvokeMethodHandler invokeMethodHandler = new InvokeMethodHandler(connectionManager);
                IEdgeHub             edgeHub             = new RoutingEdgeHub(router, new RoutingMessageConverter(), connectionManager, twinManager, edgeDeviceId, invokeMethodHandler, Mock.Of <IDeviceConnectivityManager>());
                cloudConnectionProvider.BindEdgeHub(edgeHub);

                var versionInfo = new VersionInfo("v1", "b1", "c1");

                // Create Edge Hub connection
                EdgeHubConnection edgeHubConnection = await EdgeHubConnection.Create(
                    edgeHubCredentials.Identity,
                    edgeHub,
                    twinManager,
                    connectionManager,
                    routeFactory,
                    twinCollectionMessageConverter,
                    twinMessageConverter,
                    versionInfo,
                    new NullDeviceScopeIdentitiesCache());

                await Task.Delay(TimeSpan.FromMinutes(1));

                // Get and Validate EdgeHubConfig
                Option <EdgeHubConfig> edgeHubConfigOption = await edgeHubConnection.GetConfig();

                Assert.True(edgeHubConfigOption.HasValue);
                EdgeHubConfig edgeHubConfig = edgeHubConfigOption.OrDefault();
                Assert.Equal("1.0", edgeHubConfig.SchemaVersion);
                Assert.NotNull(edgeHubConfig.Routes);
                Assert.NotNull(edgeHubConfig.StoreAndForwardConfiguration);
                Assert.Equal(20, edgeHubConfig.StoreAndForwardConfiguration.TimeToLiveSecs);

                List <(string Name, string Value, Route Route)> routes = edgeHubConfig.Routes.ToList();
                Assert.Equal(4, routes.Count);

                (string Name, string Value, Route Route)route1 = routes[0];
                Assert.NotNull(route1);
                Assert.True(route1.Route.Endpoints.First().GetType() == typeof(CloudEndpoint));
                Assert.Equal("route1", route1.Name);
                Assert.Equal("from /* INTO $upstream", route1.Value);

                (string Name, string Value, Route Route)route2 = routes[1];
                Assert.NotNull(route2);
                Endpoint endpoint = route2.Route.Endpoints.First();
                Assert.True(endpoint.GetType() == typeof(ModuleEndpoint));
                Assert.Equal($"{edgeDeviceId}/module2/input1", endpoint.Id);
                Assert.Equal("route2", route2.Name);
                Assert.Equal("from /modules/module1 INTO BrokeredEndpoint(\"/modules/module2/inputs/input1\")", route2.Value);

                (string Name, string Value, Route Route)route3 = routes[2];
                Assert.NotNull(route3);
                endpoint = route3.Route.Endpoints.First();
                Assert.True(endpoint.GetType() == typeof(ModuleEndpoint));
                Assert.Equal($"{edgeDeviceId}/module3/input1", endpoint.Id);
                Assert.Equal("route3", route3.Name);
                Assert.Equal("from /modules/module2 INTO BrokeredEndpoint(\"/modules/module3/inputs/input1\")", route3.Value);

                (string Name, string Value, Route Route)route4 = routes[3];
                Assert.NotNull(route4);
                endpoint = route4.Route.Endpoints.First();
                Assert.True(endpoint.GetType() == typeof(ModuleEndpoint));
                Assert.Equal($"{edgeDeviceId}/module4/input1", endpoint.Id);
                Assert.Equal("route4", route4.Name);
                Assert.Equal("from /modules/module3 INTO BrokeredEndpoint(\"/modules/module4/inputs/input1\")", route4.Value);

                // Make sure reported properties were updated appropriately
                EdgeHubConnection.ReportedProperties reportedProperties = await this.GetReportedProperties(registryManager, edgeDeviceId);

                Assert.Equal(200, reportedProperties.LastDesiredStatus.Code);
                Assert.NotNull(reportedProperties.Clients);
                Assert.Equal(0, reportedProperties.Clients.Count);
                Assert.Equal("1.0", reportedProperties.SchemaVersion);
                Assert.Equal(versionInfo, reportedProperties.VersionInfo);

                // Simulate a module and a downstream device that connects to Edge Hub.
                string             moduleId = "module1";
                string             sasToken = TokenHelper.CreateSasToken($"{iothubHostName}/devices/{edgeDeviceId}/modules/{moduleId}");
                string             moduleConnectionstring  = $"HostName={iothubHostName};DeviceId={edgeDeviceId};ModuleId={moduleId};SharedAccessSignature={sasToken}";
                IClientCredentials moduleClientCredentials = identityFactory.GetWithConnectionString(moduleConnectionstring);
                var moduleProxy = Mock.Of <IDeviceProxy>(d => d.IsActive);

                string downstreamDeviceId = "device1";
                sasToken = TokenHelper.CreateSasToken($"{iothubHostName}/devices/{downstreamDeviceId}");
                string             downstreamDeviceConnectionstring = $"HostName={iothubHostName};DeviceId={downstreamDeviceId};SharedAccessSignature={sasToken}";
                IClientCredentials downstreamDeviceCredentials      = identityFactory.GetWithConnectionString(downstreamDeviceConnectionstring);
                var downstreamDeviceProxy = Mock.Of <IDeviceProxy>(d => d.IsActive);

                // Connect the module and downstream device and make sure the reported properties are updated as expected.
                await connectionManager.AddDeviceConnection(moduleClientCredentials.Identity, moduleProxy);

                await connectionManager.AddDeviceConnection(downstreamDeviceCredentials.Identity, downstreamDeviceProxy);

                string moduleIdKey = $"{edgeDeviceId}/{moduleId}";
                await Task.Delay(TimeSpan.FromSeconds(10));

                reportedProperties = await this.GetReportedProperties(registryManager, edgeDeviceId);

                Assert.Equal(2, reportedProperties.Clients.Count);
                Assert.Equal(ConnectionStatus.Connected, reportedProperties.Clients[moduleIdKey].Status);
                Assert.NotNull(reportedProperties.Clients[moduleIdKey].LastConnectedTimeUtc);
                Assert.Null(reportedProperties.Clients[moduleIdKey].LastDisconnectTimeUtc);
                Assert.Equal(ConnectionStatus.Connected, reportedProperties.Clients[downstreamDeviceId].Status);
                Assert.NotNull(reportedProperties.Clients[downstreamDeviceId].LastConnectedTimeUtc);
                Assert.Null(reportedProperties.Clients[downstreamDeviceId].LastDisconnectTimeUtc);
                Assert.Equal(200, reportedProperties.LastDesiredStatus.Code);
                Assert.Equal("1.0", reportedProperties.SchemaVersion);
                Assert.Equal(versionInfo, reportedProperties.VersionInfo);

                // Update desired propertied and make sure callback is called with valid values
                bool callbackCalled = false;

                Task ConfigUpdatedCallback(EdgeHubConfig updatedConfig)
                {
                    Assert.NotNull(updatedConfig);
                    Assert.NotNull(updatedConfig.StoreAndForwardConfiguration);
                    Assert.NotNull(updatedConfig.Routes);

                    routes = updatedConfig.Routes.ToList();
                    Assert.Equal(4, routes.Count);

                    route1 = routes[0];
                    Assert.NotNull(route1);
                    Assert.True(route1.Route.Endpoints.First().GetType() == typeof(CloudEndpoint));
                    Assert.Equal("route1", route1.Name);
                    Assert.Equal("from /* INTO $upstream", route1.Value);

                    route2 = routes[1];
                    Assert.NotNull(route2);
                    endpoint = route2.Route.Endpoints.First();
                    Assert.True(endpoint.GetType() == typeof(ModuleEndpoint));
                    Assert.Equal($"{edgeDeviceId}/module2/input1", endpoint.Id);
                    Assert.Equal("route2", route2.Name);
                    Assert.Equal("from /modules/module1 INTO BrokeredEndpoint(\"/modules/module2/inputs/input1\")", route2.Value);

                    route3 = routes[2];
                    Assert.NotNull(route3);
                    endpoint = route3.Route.Endpoints.First();
                    Assert.True(endpoint.GetType() == typeof(ModuleEndpoint));
                    Assert.Equal($"{edgeDeviceId}/module5/input1", endpoint.Id);
                    Assert.Equal("route4", route3.Name);
                    Assert.Equal("from /modules/module3 INTO BrokeredEndpoint(\"/modules/module5/inputs/input1\")", route3.Value);

                    route4 = routes[3];
                    Assert.NotNull(route4);
                    endpoint = route4.Route.Endpoints.First();
                    Assert.True(endpoint.GetType() == typeof(ModuleEndpoint));
                    Assert.Equal($"{edgeDeviceId}/module6/input1", endpoint.Id);
                    Assert.Equal("route5", route4.Name);
                    Assert.Equal("from /modules/module5 INTO BrokeredEndpoint(\"/modules/module6/inputs/input1\")", route4.Value);

                    callbackCalled = true;
                    return(Task.CompletedTask);
                }

                edgeHubConnection.SetConfigUpdatedCallback(ConfigUpdatedCallback);
                await this.UpdateDesiredProperties(registryManager, edgeDeviceId);

                await Task.Delay(TimeSpan.FromSeconds(5));

                Assert.True(callbackCalled);

                reportedProperties = await this.GetReportedProperties(registryManager, edgeDeviceId);

                Assert.Equal(200, reportedProperties.LastDesiredStatus.Code);
                Assert.NotNull(reportedProperties.Clients);
                Assert.Equal(2, reportedProperties.Clients.Count);
                Assert.Equal("1.0", reportedProperties.SchemaVersion);
                Assert.Equal(versionInfo, reportedProperties.VersionInfo);

                // Disconnect the downstream device and make sure the reported properties are updated as expected.
                await connectionManager.RemoveDeviceConnection(moduleIdKey);

                await connectionManager.RemoveDeviceConnection(downstreamDeviceId);

                await Task.Delay(TimeSpan.FromSeconds(10));

                reportedProperties = await this.GetReportedProperties(registryManager, edgeDeviceId);

                Assert.Equal(1, reportedProperties.Clients.Count);
                Assert.True(reportedProperties.Clients.ContainsKey(moduleIdKey));
                Assert.False(reportedProperties.Clients.ContainsKey(downstreamDeviceId));
                Assert.Equal(ConnectionStatus.Disconnected, reportedProperties.Clients[moduleIdKey].Status);
                Assert.NotNull(reportedProperties.Clients[moduleIdKey].LastConnectedTimeUtc);
                Assert.NotNull(reportedProperties.Clients[moduleIdKey].LastDisconnectTimeUtc);
                Assert.Equal(200, reportedProperties.LastDesiredStatus.Code);
                Assert.Equal("1.0", reportedProperties.SchemaVersion);
                Assert.Equal(versionInfo, reportedProperties.VersionInfo);

                // If the edge hub restarts, clear out the connected devices in the reported properties.
                await EdgeHubConnection.Create(
                    edgeHubCredentials.Identity,
                    edgeHub,
                    twinManager,
                    connectionManager,
                    routeFactory,
                    twinCollectionMessageConverter,
                    twinMessageConverter,
                    versionInfo,
                    new NullDeviceScopeIdentitiesCache());

                await Task.Delay(TimeSpan.FromMinutes(1));

                reportedProperties = await this.GetReportedProperties(registryManager, edgeDeviceId);

                Assert.Null(reportedProperties.Clients);
                Assert.Equal("1.0", reportedProperties.SchemaVersion);
                Assert.Equal(versionInfo, reportedProperties.VersionInfo);
            }
            finally
            {
                try
                {
                    await RegistryManagerHelper.RemoveDevice(edgeDeviceId, registryManager);
                }
                catch (Exception)
                {
                    // ignored
                }
            }
        }
Exemplo n.º 6
0
 public LoginView()
 {
     InitializeComponent();
     DataContext = this;
     db          = new DataBase(ConnectionStringHelper.GetConnectionString(DBType.Internet));
 }
Exemplo n.º 7
0
 public async Task <SurowiecCenyModel> PobierzSurowiecZIdAsync(int?idSurowca)
 {
     using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(ConnectionStringHelper.GetConnectionString()))
     {
         return(await connection.QuerySingleAsync <SurowiecCenyModel>(SqlPobierzSurowceWrazZCenami(idSurowca)));
     }
 }
        public bool Run(bool skipConnVerification)
        {
            var hostConnStr = CensorConnectionString(_connectionStringResolver.GetNameOrConnectionString(new ConnectionStringResolveArgs(MultiTenancySides.Host)));

            if (hostConnStr.IsNullOrWhiteSpace())
            {
                _log.Write("Configuration file should contain a connection string named 'Default'");
                return(false);
            }

            _log.Write("Host database: " + ConnectionStringHelper.GetConnectionString(hostConnStr));
            if (!skipConnVerification)
            {
                _log.Write("Continue to migration for this host database and all tenants..? (Y/N): ");
                var command = Console.ReadLine();
                if (!command.IsIn("Y", "y"))
                {
                    _log.Write("Migration canceled.");
                    return(false);
                }
            }

            _log.Write("HOST database migration started...");

            try
            {
                _migrator.CreateOrMigrateForHost(SeedHelper.SeedHostDb);
            }
            catch (Exception ex)
            {
                _log.Write("An error occured during migration of host database:");
                _log.Write(ex.ToString());
                _log.Write("Canceled migrations.");
                return(false);
            }

            _log.Write("HOST database migration completed.");
            _log.Write("--------------------------------------------------------");

            var migratedDatabases = new HashSet <string>();
            var tenants           = _tenantRepository.GetAllList(t => t.ConnectionString != null && t.ConnectionString != "");

            for (var i = 0; i < tenants.Count; i++)
            {
                var tenant = tenants[i];
                _log.Write(string.Format("Tenant database migration started... ({0} / {1})", (i + 1), tenants.Count));
                _log.Write("Name              : " + tenant.Name);
                _log.Write("TenancyName       : " + tenant.TenancyName);
                _log.Write("Tenant Id         : " + tenant.Id);
                _log.Write("Connection string : " + SimpleStringCipher.Instance.Decrypt(tenant.ConnectionString));

                if (!migratedDatabases.Contains(tenant.ConnectionString))
                {
                    try
                    {
                        _migrator.CreateOrMigrateForTenant(tenant);
                    }
                    catch (Exception ex)
                    {
                        _log.Write("An error occured during migration of tenant database:");
                        _log.Write(ex.ToString());
                        _log.Write("Skipped this tenant and will continue for others...");
                    }

                    migratedDatabases.Add(tenant.ConnectionString);
                }
                else
                {
                    _log.Write("This database has already migrated before (you have more than one tenant in same database). Skipping it....");
                }

                _log.Write(string.Format("Tenant database migration completed. ({0} / {1})", (i + 1), tenants.Count));
                _log.Write("--------------------------------------------------------");
            }

            _log.Write("All databases have been migrated.");

            return(true);
        }
Exemplo n.º 9
0
        internal void ProcessFile(bool insert)
        {
            var ImportId = this.Id;

            string fileName = System.IO.Path.Combine(System.IO.Path.GetTempPath(), ImportId.ToString());

            var csvConf = new CsvHelper.Configuration.CsvConfiguration()
            {
                IsStrictMode     = false,
                IsCaseSensitive  = false,
                SkipEmptyRecords = true
            };

            if (insert)
            {
                csvConf.ClassMapping <ClientCsvMap>();
            }
            else
            {
                csvConf.ClassMapping <ExistingClientCsvMap>();
            }


            var updatedAt = DateTime.Now;
            var updatedBy = this.Permissions.User.Id;

            using (var csvReader = new CsvHelper.CsvReader(new System.IO.StreamReader(File.InputStream), csvConf))
            {
                var csvChunkSize = 10000;
                var recordIndex  = 1;

                using (var db = new ccEntities())
                {
                    db.Imports.AddObject(new CC.Data.Import()
                    {
                        Id        = ImportId,
                        StartedAt = DateTime.Now,
                        UserId    = this.Permissions.User.Id
                    });
                    db.SaveChanges();
                }

                foreach (var csvChunk in csvReader.GetRecords <ImportClient>().Split(csvChunkSize))
                {
                    string connectionString = ConnectionStringHelper.GetProviderConnectionString();

                    using (var sqlBulk = new System.Data.SqlClient.SqlBulkCopy(connectionString, SqlBulkCopyOptions.KeepNulls))
                    {
                        foreach (var record in csvChunk)
                        {
                            record.RowIndex    = recordIndex++;
                            record.ImportId    = ImportId;
                            record.UpdatedAt   = updatedAt;
                            record.UpdatedById = updatedBy;
                            if (this.Permissions.User.RoleId != (int)FixedRoles.Admin)
                            {
                                using (var db = new ccEntities())
                                {
                                    var regionId = (from a in db.Agencies
                                                    where a.Id == record.AgencyId
                                                    select a.AgencyGroup.Country.RegionId).SingleOrDefault();
                                    if (regionId == 2)                                     //Israel
                                    {
                                        record.CountryId        = 344;
                                        record.NationalIdTypeId = 1;
                                    }
                                }
                            }
                            if (!string.IsNullOrEmpty(record.NationalId) && record.NationalId.Length < 9 && record.NationalIdTypeId == 1)
                            {
                                record.NationalId = record.NationalId.PadLeft(9, '0');
                            }
                            if (insert)
                            {
                                record.ApprovalStatusId = (int)ApprovalStatusEnum.New;
                            }
                        }

                        var dataTable = csvChunk.ToDataTable();
                        var q         = dataTable.Columns.OfType <System.Data.DataColumn>().Where(f => f.DataType == typeof(Int32)).Select(f => new
                        {
                            c      = f.ColumnName,
                            values = dataTable.Rows.OfType <System.Data.DataRow>().Select((r, i) => r[f.ColumnName])
                        });

                        sqlBulk.DestinationTableName = "ImportClients";
                        sqlBulk.NotifyAfter          = 1000;
                        MapColumns(sqlBulk);
                        sqlBulk.SqlRowsCopied += (s, e) =>
                        {
                            System.Diagnostics.Debug.Write(e.RowsCopied);
                        };

                        sqlBulk.WriteToServer(dataTable);
                    }
                }
            }
        }
Exemplo n.º 10
0
 public static string ConnectionString()
 {
     return(String.Format("{0};SearchPath={1};", ConnectionStringHelper.GetConnStr("DataLakeDatabase"), SchemaName()));
 }
Exemplo n.º 11
0
        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                // Specify a connection string. Replace the given value with a
                // valid connection string for a Northwind SQL Server sample
                // database accessible to your system.
                //var connectionString = ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString;


                using (SqlConnection connection = new SqlConnection(ConnectionStringHelper.GetConnectionString()))
                {
                    using (SqlCommand command = new SqlCommand("[dbo].[usp_SaveProduct]", connection))
                    {
                        command.CommandType = CommandType.StoredProcedure;



                        command.Parameters.Add(new SqlParameter("@ProductID", SqlDbType.BigInt)
                        {
                            Value = Convert.ToInt64(lblProductID.Text)
                        });
                        command.Parameters.Add(new SqlParameter("@Color", SqlDbType.NVarChar, 50)
                        {
                            Value = cmbColor1.SelectedValue
                        });
                        command.Parameters.Add(new SqlParameter("@EmissionNorms", SqlDbType.NVarChar, 100)
                        {
                            Value = cmbEmission.SelectedValue
                        });
                        command.Parameters.Add(new SqlParameter("@MajorVariant", SqlDbType.NVarChar, 500)
                        {
                            Value = cmbMajorVariant1.SelectedValue
                        });
                        command.Parameters.Add(new SqlParameter("@Type", SqlDbType.NVarChar, 20)
                        {
                            Value = cmbType.SelectedValue
                        });
                        command.Parameters.Add(new SqlParameter("@CustomerCode", SqlDbType.NVarChar, 150)
                        {
                            Value = txtCustCode1.Text
                        });
                        command.Parameters.Add(new SqlParameter("@BarCode", SqlDbType.NVarChar, 1000)
                        {
                            Value = txtBarCode1.Text
                        });
                        LoggedInUser.SetUserParameters(command);

                        connection.Open();
                        int result = command.ExecuteNonQuery();

                        // Check Error
                        if (result < 0)
                        {
                            Console.WriteLine("Error inserting data into Database!");
                        }
                    }
                }

                ReLoadGrid();

                MessageBox.Show("Master record saved successfully");
            }
            catch (Exception ex)
            {
                LogException(ex);
            }
        }
Exemplo n.º 12
0
        private IQuery BuildQuery(QueryXml queryXml)
        {
            var connectionString = new ConnectionStringHelper().Execute(queryXml, Xml.Settings.SettingsXml.DefaultScope.SystemUnderTest);

            return(new NBi.Core.Query.Query(queryXml.InlineQuery, connectionString, new TimeSpan(0, 0, 0)));
        }
Exemplo n.º 13
0
 public HintHistoryRepository()
 {
     this.context = new ApplicationContext(ConnectionStringHelper.GetConnectionStringByName(ConnectionType.RiddlesDB));
 }
Exemplo n.º 14
0
        public async Task ConnectTest()
        {
            var edgeHub = Mock.Of <IEdgeHub>();
            ICloudConnectionProvider cloudConnectionProvider = new CloudConnectionProvider(MessageConverterProvider, ConnectionPoolSize, new ClientProvider(), Option.None <UpstreamProtocol>(), TokenProvider, DeviceScopeIdentitiesCache, TimeSpan.FromMinutes(60), true);

            cloudConnectionProvider.BindEdgeHub(edgeHub);
            string deviceConnectionString = await SecretsHelper.GetSecretFromConfigKey("device1ConnStrKey");

            var deviceIdentity                = Mock.Of <IDeviceIdentity>(m => m.Id == ConnectionStringHelper.GetDeviceId(deviceConnectionString));
            var clientCredentials             = new SharedKeyCredentials(deviceIdentity, deviceConnectionString, null);
            Try <ICloudConnection> cloudProxy = cloudConnectionProvider.Connect(clientCredentials, null).Result;

            Assert.True(cloudProxy.Success);
            bool result = await cloudProxy.Value.CloseAsync();

            Assert.True(result);
        }
Exemplo n.º 15
0
 public async Task <IEnumerable <SurowiecCenyModel> > PobierzListeSurowcowZCenamiAsync()
 {
     using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(ConnectionStringHelper.GetConnectionString()))
     {
         return(await connection.QueryAsync <SurowiecCenyModel>(SqlPobierzSurowceWrazZCenami(null)));
     }
 }
Exemplo n.º 16
0
        private JsonResult CreateApp2(string template, string name, string title, string server, string catalog, string username, string password, bool usingSsh, bool usingSsl, string sshRemoteHost, string sshUser, string sshPassword, string sshPrivateKey, int sshPort, int productPort, int?themeId)
        {
            Maps.Instance.DuradosMap.Logger.Log(GetControllerNameForLog(this.ControllerContext), this.ControllerContext.RouteData.Values["action"].ToString(), "CreateApp", "started", "", 3, "server: " + server + ", database: " + catalog, DateTime.Now);

            SqlProduct sqlProduct = SqlProduct.SqlServer;

            if (template == "1" || template == "3")
            {
                sqlProduct = SqlProduct.SqlAzure;
            }
            else if (template == "4")
            {
                sqlProduct = SqlProduct.MySql;
            }
            else if (template == "8")
            {
                sqlProduct = SqlProduct.Postgre;
            }
            else if (template == "7")
            {
                sqlProduct = SqlProduct.Oracle;
            }

            if (sshPrivateKey != null)
            {
                sshPrivateKey = sshPrivateKey.Replace(System.Environment.NewLine, string.Empty);
            }
            string errors;

            if (!IsValidConnectionData(sqlProduct, name, title, server, catalog, username, password, usingSsh, usingSsl, sshRemoteHost, sshUser, sshPassword, sshPrivateKey, sshPort, productPort, out errors))
            {
                return(Json(new { Success = false, Message = errors }));
            }
            bool isBlankDababase = template.ToLower() == "5";
            bool isAzureDemo     = template.ToLower() == "1";
            bool isOnPremiseDemo = template.ToLower() == "0";

            bool isRdsBlank = IsNewDatabase(template);

            if (isRdsBlank)
            {
                sqlProduct = Durados.Web.Mvc.UI.Helpers.RDSNewDatabaseFactory.GetSqlProductfromTemplate(template).Value;
            }
            bool   connectionExists         = false;
            string userId                   = GetUserID();
            string templateConnectionString = null;
            string demoUsername             = Maps.DemoSqlUsername;
            string demoPassword             = Maps.DemoSqlPassword;
            bool   isDemo                   = isAzureDemo || isOnPremiseDemo;

            bool basic = !isDemo;

            if (isAzureDemo)
            {
                demoUsername = Maps.DemoAzureUsername;
                demoPassword = Maps.DemoAzurePassword;
            }

            string newPassword = password;

            if (isAzureDemo || isOnPremiseDemo)
            {
                newPassword = new AccountMembershipService().GetRandomPassword(12);
            }
            string newUsername = username;

            if (string.IsNullOrEmpty(userId))
            {
                return(Json(new { Success = false, Message = "Please login or sign-up." }));
            }

            View view = GetView("durados_App");

            try
            {
                name = GetCleanName(name);
            }
            catch (Exception exception)
            {
                Map.Logger.Log(GetControllerNameForLog(this.ControllerContext), this.ControllerContext.RouteData.Values["action"].ToString(), exception.Source, exception, 1, "app name exception");

                return(Json(new { Success = false, Message = exception.Message }));
            }

            int? connectionId  = null;
            bool pendingExists = false;

            if (isAzureDemo || isOnPremiseDemo)
            {
                string source         = Maps.DemoDatabaseName + Map.SourceSuffix;
                bool   templateExists = Maps.Instance.AppExists(name).HasValue;
                if (templateExists)
                {
                    return(Json(new { Success = true, Url = Maps.GetAppUrl(name) }));
                }
                else
                {
                    connectionId     = Maps.Instance.GetConnection(server, catalog, newUsername, userId);
                    connectionExists = connectionId.HasValue;
                    if (connectionExists)
                    {
                        try
                        {
                            ValidateConnection(server, catalog, newUsername, newPassword);
                        }
                        catch (Exception exception)
                        {
                            Map.Logger.Log(GetControllerNameForLog(this.ControllerContext), this.ControllerContext.RouteData.Values["action"].ToString(), exception.Source, exception, 3, null);

                            connectionExists = false;
                        }
                    }

                    if (!connectionExists)
                    {
                        if (isAzureDemo)
                        {
                            string pending = Maps.GetPendingDatabase(template);

                            //try
                            //{
                            try
                            {
                                for (int i = 0; i < Maps.DemoPendingNext; i++)
                                {
                                    try
                                    {
                                        pendingExists = false;
                                        ValidateConnection(server, pending, demoUsername, demoPassword);
                                        templateConnectionString = RenamePendingDatabase(server, catalog, demoUsername, demoPassword, pending);
                                        pendingExists            = true;
                                        break;
                                    }
                                    catch (Exception exception)
                                    {
                                        pending = Maps.GetPendingDatabase(template);
                                        Map.Logger.Log(GetControllerNameForLog(this.ControllerContext), this.ControllerContext.RouteData.Values["action"].ToString(), exception.Source, exception, 3, "pending=" + pending + ";i=" + i);
                                    }
                                }
                                if (pendingExists)
                                {
                                    CreateDatabase(server, pending, demoUsername, demoPassword, source, template);
                                }
                            }
                            catch (Exception exception)
                            {
                                Map.Logger.Log(GetControllerNameForLog(this.ControllerContext), this.ControllerContext.RouteData.Values["action"].ToString(), exception.Source, exception, 3, null);

                                pendingExists = false;
                            }

                            //}
                            //catch (Exception exception)
                            //{
                            //    Map.Logger.Log(GetControllerNameForLog(this.ControllerContext), this.ControllerContext.RouteData.Values["action"].ToString(), exception.Source, exception, 3, null);

                            //    pendingExists = false;
                            //}



                            if (!pendingExists)
                            {
                                try
                                {
                                    templateConnectionString = CreateDatabase(server, catalog, demoUsername, demoPassword, source, template);
                                }
                                catch (Exception exception)
                                {
                                    Map.Logger.Log(GetControllerNameForLog(this.ControllerContext), this.ControllerContext.RouteData.Values["action"].ToString(), exception.Source, exception, 1, "Failed to create Azure database. username="******"Server is busy, Please try again later." }));
                                }
                            }
                            else
                            {
                                try
                                {
                                    CreateDatabaseUser(server, catalog, demoUsername, demoPassword, false, newUsername, newPassword, false);
                                }
                                catch (Exception exception)
                                {
                                    Map.Logger.Log(GetControllerNameForLog(this.ControllerContext), this.ControllerContext.RouteData.Values["action"].ToString(), exception.Source, exception, 1, "Failed to create Azure database. username="******"Server is busy, Please try again later." }));
                                }
                            }
                        }
                        else
                        {
                            templateConnectionString = CreateDatabase(server, catalog, demoUsername, demoPassword, source, template);
                            CreateDatabaseUser(server, catalog, demoUsername, demoPassword, false, newUsername, newPassword, false);
                        }
                    }
                }
            }

            if (!isAzureDemo && !isBlankDababase && !isRdsBlank)
            {
                try
                {
                    ValidateConnection(server, catalog, newUsername, newPassword, sqlProduct, 3306, usingSsh, usingSsl, userId, sshRemoteHost, sshUser, sshPassword, sshPrivateKey, sshPort, productPort);
                }
                catch (Exception exception)
                {
                    string           cnnstr           = GetConnection(server, catalog, null, username, "*****", null, sqlProduct, productPort, usingSsh, usingSsl);
                    TroubleshootInfo troubleshootInfo = ConnectionStringHelper.GetTroubleshootInfo(exception, server, catalog, username, password, usingSsh, sqlProduct, sshRemoteHost, sshUser, sshPassword, sshPort, productPort);
                    Map.Logger.Log(GetControllerNameForLog(this.ControllerContext), this.ControllerContext.RouteData.Values["action"].ToString(), exception.Source, exception, 1, cnnstr + "\n\r" + "Troubleshoot Info Id = " + troubleshootInfo.Id);
                    SendError(1, exception, GetControllerNameForLog(this.ControllerContext), this.ControllerContext.RouteData.Values["action"].ToString(), Map.Logger, cnnstr + "\n\r" + "Troubleshoot Info Id = " + troubleshootInfo.Id);
                    //if(exception.InnerException is MySql.Data.MySqlClient.MySqlException)
                    //    return Json(new { Success = false, Message = "Could not connect. "+exception.InnerException.Message });
                    //return Json(new { Success = false, Message = "Could not connect. Please check the connection parameters and make sure the server is up and running." });
                    string message = exception.InnerException == null ? exception.Message : exception.InnerException.Message;
                    return(Json(new { Success = false, Message = message, CnnString = cnnstr, port = productPort, TroubleshootInfo = troubleshootInfo }));
                }
            }

            if (!connectionId.HasValue && !isBlankDababase)
            {
                try
                {
                    connectionId = SaveConnection(server, catalog, newUsername, newPassword, userId, sqlProduct, usingSsh, usingSsl, sshRemoteHost, sshUser, sshPassword, sshPrivateKey, sshPort, productPort);
                }
                catch (Exception exception)
                {
                    Map.Logger.Log(GetControllerNameForLog(this.ControllerContext), this.ControllerContext.RouteData.Values["action"].ToString(), exception.Source, exception, 1, "fail to save connection string");

                    return(Json(new { Success = false, Message = exception.Message }));
                }
            }

            Dictionary <string, object> values = new Dictionary <string, object>();

            values.Add("Name", name);
            values.Add("Title", title);
            values.Add("Image", Durados.Database.LongProductName + ".png");

            if (!isBlankDababase)
            {
                values.Add("FK_durados_App_durados_DataSourceType_Parent", "2");
                values.Add("FK_durados_App_durados_SqlConnection_Parent", connectionId.Value.ToString());
            }
            else
            {
                values.Add("FK_durados_App_durados_DataSourceType_Parent", "1");
                values.Add("FK_durados_App_durados_SqlConnection_Parent", string.Empty);
            }
            values.Add("FK_durados_App_durados_SqlConnection_System_Parent", string.Empty);
            values.Add("FK_durados_App_durados_Template_Parent", string.Empty);
            values.Add("SpecificDOTNET", string.Empty);
            values.Add("SpecificJS", string.Empty);
            values.Add("SpecificCss", string.Empty);
            values.Add("Description", string.Empty);
            values.Add("TemplateFile", string.Empty);
            values.Add("FK_durados_App_durados_SqlConnection_Security_Parent", string.Empty);
            values.Add("Basic", basic);
            values.Add("FK_durados_App_durados_Theme_Parent", (themeId ?? Maps.DefaultThemeId).ToString());

            DataRow row = null;

            try
            {
                row = view.Create(values, null, view_BeforeCreate, view_BeforeCreateInDatabase, view_AfterCreateBeforeCommit, view_AfterCreateAfterCommit);
                if (isAzureDemo || isOnPremiseDemo)
                {
                    //string sourcePath = Maps.DemoUploadSourcePath;
                    //string targetPath = "/Uploads/" + row["Id"] + "/";
                    //try
                    //{
                    //    DirectoryCopy(sourcePath, targetPath, true);
                    //}
                    //catch (Exception exception)
                    //{
                    //    Map.Logger.Log(GetControllerNameForLog(this.ControllerContext), this.ControllerContext.RouteData.Values["action"].ToString(), exception.Source, exception, 3, "Could not copy uploads");

                    //}
                }
            }
            catch (SqlException exception)
            {
                if (exception.Number == 2601)
                {
                    Map.Logger.Log(GetControllerNameForLog(this.ControllerContext), this.ControllerContext.RouteData.Values["action"].ToString(), exception.Source, exception, 6, "App name already exists");
                    return(Json(new { Success = false, Message = "Application name already exists, please enter a different name." }));
                }
                else
                {
                    Map.Logger.Log(GetControllerNameForLog(this.ControllerContext), this.ControllerContext.RouteData.Values["action"].ToString(), exception.Source, exception, 1, "failed to create app row");
                    SendError(1, exception, GetControllerNameForLog(this.ControllerContext), this.ControllerContext.RouteData.Values["action"].ToString(), Map.Logger);
                    return(Json(new { Success = false, Message = "Server is busy, please try again later" }));
                }
            }
            catch (PlugInUserException exception)
            {
                Map.Logger.Log(GetControllerNameForLog(this.ControllerContext), this.ControllerContext.RouteData.Values["action"].ToString(), exception.Source, exception, 2, "failed to create app row");
                //SendError(1, exception, GetControllerNameForLog(this.ControllerContext), this.ControllerContext.RouteData.Values["action"].ToString(), Map.Logger);
                return(Json(new { Success = false, Message = exception.Message }));
            }
            catch (Exception exception)
            {
                Map.Logger.Log(GetControllerNameForLog(this.ControllerContext), this.ControllerContext.RouteData.Values["action"].ToString(), exception.Source, exception, 1, "failed to create app row");
                SendError(1, exception, GetControllerNameForLog(this.ControllerContext), this.ControllerContext.RouteData.Values["action"].ToString(), Map.Logger);
                return(Json(new { Success = false, Message = "Server is busy, please try again later" }));
            }

            if (isAzureDemo || isOnPremiseDemo)
            {
                try
                {
                    HandleTemplate(row, templateConnectionString);
                }
                catch (Exception exception)
                {
                    Map.Logger.Log(GetControllerNameForLog(this.ControllerContext), this.ControllerContext.RouteData.Values["action"].ToString(), exception.Source, exception, 1, "failed to create northwind template");

                    return(Json(new { Success = false, Message = "Server is busy, please try again later" }));
                }

                if (isAzureDemo)
                {
                    if (!pendingExists)
                    {
                        bool inProcess = true;
                        int  counter   = 0;
                        while (inProcess && counter < 10)
                        {
                            try
                            {
                                counter++;
                                ValidateConnection(server, catalog, newUsername, newPassword);
                                System.Threading.Thread.Sleep(500);
                                inProcess = false;
                            }
                            catch
                            {
                                inProcess = true;
                            }
                        }

                        if (inProcess)
                        {
                            try
                            {
                                ValidateConnection(server, catalog, newUsername, newPassword);
                            }
                            catch (Exception exception)
                            {
                                Map.Logger.Log(GetControllerNameForLog(this.ControllerContext), this.ControllerContext.RouteData.Values["action"].ToString(), exception.Source, exception, 1, null);
                            }
                        }

                        try
                        {
                            CreateDatabaseUser(server, catalog, demoUsername, demoPassword, false, newUsername, newPassword, false);
                        }
                        catch (Exception exception)
                        {
                            Map.Logger.Log(GetControllerNameForLog(this.ControllerContext), this.ControllerContext.RouteData.Values["action"].ToString(), exception.Source, exception, 1, "Failed to create Azure database. username="******"http://" + name + Durados.Web.Mvc.Maps.UserPreviewUrl + GetThemePath(themeId);

            return(Json(new { Success = true, Url = Maps.GetAppUrl(name), previewUrl = previewUrl }));
        }
 private static string GetConnectionString()
 {
     return(ConnectionStringHelper.GetConnectionString("VirtoCommerce"));
 }
Exemplo n.º 18
0
 public SecurityDbContext()
     : this(ConnectionStringHelper.GetConnectionString("VirtoCommerce"))
 {
 }
Exemplo n.º 19
0
            public void ThrowsArgumentExceptionForNullOrWhitespaceConnectionString()
            {
                var dbContext = new TestDbContextContainer();

                ExceptionTester.CallMethodAndExpectException <ArgumentException>(() => ConnectionStringHelper.SetConnectionString(dbContext, null));
                ExceptionTester.CallMethodAndExpectException <ArgumentException>(() => ConnectionStringHelper.SetConnectionString(dbContext, string.Empty));
            }
Exemplo n.º 20
0
        public void LoadNewDatabase(
			int index,
			string name,
			DatabaseTypes databaseType,
			ConnectionStringHelper connectionString,
			List<string> tablePrefixes,
			List<string> viewPrefixes,
			List<string> storedProcedurePredixes,
			bool fetchTables,
			bool fetchViews,
			bool fetchStroredProcedures)
        {
            Model.Database database = Model.Database.LoadNewDatabase(name, databaseType, connectionString, tablePrefixes, viewPrefixes, storedProcedurePredixes, fetchTables, fetchViews, fetchStroredProcedures);
            UpdateDatabase(database, index);
        }
Exemplo n.º 21
0
            public void ThrowsArgumentExceptionForNullOrWhitespaceConnectionString()
            {
                var connectionString = EfConnectionStringHelper.GetEntityFrameworkConnectionString(typeof(TestObjectContextContainer), TestConnectionStrings.ObjectContextDefault);
                var objectContext    = new TestObjectContextContainer(connectionString);

                ExceptionTester.CallMethodAndExpectException <ArgumentException>(() => ConnectionStringHelper.SetConnectionString(objectContext, null));
                ExceptionTester.CallMethodAndExpectException <ArgumentException>(() => ConnectionStringHelper.SetConnectionString(objectContext, string.Empty));
            }
Exemplo n.º 22
0
 public void Attach(XpandModuleBase xpandModuleBase) {
     if (!xpandModuleBase.Executed<ISequenceGeneratorUser>(SequenceGeneratorHelperName)) {
         if (SequenceObjectType == null){
             SequenceObjectType = xpandModuleBase.LoadFromBaseImpl("Xpand.Persistent.BaseImpl.SequenceObject");
         }
         if (xpandModuleBase.RuntimeMode) {
             _xpandModuleBase = xpandModuleBase;
             Application.LoggedOff += ApplicationOnLoggedOff;
             var helper = new ConnectionStringHelper();
             helper.Attach(_xpandModuleBase);
             helper.ConnectionStringUpdated += (sender, args) => InitializeSequenceGenerator();
         }
     }
 }
Exemplo n.º 23
0
 public void ThrowsArgumentNullExceptionForNullDbContext()
 {
     ExceptionTester.CallMethodAndExpectException <ArgumentNullException>(() => ConnectionStringHelper.SetConnectionString((DbContext)null, "dummy"));
 }
Exemplo n.º 24
0
 public void Attach(XpandModuleBase xpandModuleBase, ConnectionStringHelper helper) {
     _xpandModuleBase = xpandModuleBase;
     if (!_xpandModuleBase.Executed<ISequenceGeneratorUser>(SequenceGeneratorHelperName)) {
         if (_xpandModuleBase.RuntimeMode) {
             Application.LoggedOff += ApplicationOnLoggedOff;
             AddToAdditionalExportedTypes(new[] { "Xpand.Persistent.BaseImpl.SequenceObject" });
             helper.ConnectionStringUpdated += XpandModuleBaseOnConnectionStringUpdated;
         }
     }
 }
Exemplo n.º 25
0
 /// <summary>	Default constructor. </summary>
 public DummySqLiteDataService() : base(ConnectionStringHelper.GetConnectionStringFor("SqLite"),
                                        new SqLiteConnectionFactory())
 {
 }
Exemplo n.º 26
0
 //, List<string> scriptObjectPrefixes)
 protected ScriptBLL(DatabaseTypes dalAssemblyName, ConnectionStringHelper connectionString)
 {
     DalAssemblyName = dalAssemblyName;
     ConnectionString = connectionString;
 }
Exemplo n.º 27
0
 /// <summary>	Default constructor. </summary>
 public DummyPgsqlDataService() : base(ConnectionStringHelper.GetConnectionStringFor("PGSQL"))
 {
 }