Exemplo n.º 1
0
        /// <summary>
        /// Sets default db credentials
        /// </summary>
        protected virtual void SetDefaultDsc()
        {
            try
            {
                var cfg = Cartomatic.Utils.NetCoreConfig.GetNetCoreConfig();

                var dsc = new DataSourceCredentials();
                cfg.GetSection("Dsc").Bind(dsc);

                //if could not read, this should be default
                if (dsc.DataSourceProvider == DataSourceProvider.Unknown)
                {
                    throw new Exception();
                }

                Dsc = dsc;


                PrintDbc();
            }
            catch
            {
                ConsoleEx.WriteLine("Default db credentials are not configured. Is this intentional?", ConsoleColor.DarkRed);
                Console.WriteLine();
            }
        }
Exemplo n.º 2
0
        public void Loaded(object sender, RoutedEventArgs e)
        {
            if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
            {
                Window mainWindow = sender as Window;
                Syncfusion.Windows.Reports.Viewer.ReportViewer viewer = mainWindow.FindName("viewer") as Syncfusion.Windows.Reports.Viewer.ReportViewer;

                List <DataSourceCredentials> crdentials = new List <DataSourceCredentials>();

                foreach (var dataSource in viewer.GetDataSources())
                {
                    DataSourceCredentials credn = new DataSourceCredentials();
                    credn.Name     = dataSource.Name;
                    credn.UserId   = "ssrs1";
                    credn.Password = "******";
                    crdentials.Add(credn);
                }

                viewer.SetDataSourceCredentials(crdentials);
                viewer.RefreshReport();
            }

            else
            {
                MessageBox.Show("Internet connection is required to run this sample", "SSRS Demo", MessageBoxButton.OK);
            }
        }
Exemplo n.º 3
0
 public WorkbookPublisher(PublisherSettings publisherSettings, DataSourceCredentials creds, ILoggerFactory loggerFactory)
 {
     _publisherSettings = publisherSettings;
     _dbCreds           = creds;
     _loggerFactory     = loggerFactory;
     _logger            = _loggerFactory.CreateLogger <WorkbookPublisher>();
 }
Exemplo n.º 4
0
        /// <summary>
        /// creates a datastore object for given file and declared type
        /// </summary>
        /// <param name="fName"></param>
        /// <param name="type"></param>
        /// <param name="schema"></param>
        /// <returns></returns>
        public static DataStore GetDataStore(string fName, string type, DataSourceCredentials ds, string schema = "imported_geodata")
        {
            if (!CheckIfObjectSafe(fName))
            {
                throw MapHive.Core.DataModel.Validation.Utils.GenerateValidationFailedException("FileName", "bad_file_name",
                                                                                                "File name contains forbidden words");
            }

            //postgres has a 63 byte limit on the domain names
            var tblName = $"l_{DateTime.Now:yyyyMMddHHmmss}_{type}_{GetSafeDbObjectName(fName)}";

            if (tblName.Length > 63)
            {
                tblName = tblName.Substring(0, 63);
            }


            return(new DataStore
            {
                Name = fName,
                DataSource = new DataSource
                {
                    DataSourceCredentials = ds,
                    Schema = schema,
                    Table = tblName,
                    Columns = new List <Column>()
                }
            });
        }
Exemplo n.º 5
0
 public WorkbookPublisher(LogSharkConfiguration config, PublisherSettings publisherSettings, DataSourceCredentials creds, ILoggerFactory loggerFactory)
 {
     _config            = config;
     _publisherSettings = publisherSettings;
     _dbCreds           = creds;
     _loggerFactory     = loggerFactory;
     _logger            = _loggerFactory.CreateLogger <WorkbookPublisher>();
 }
Exemplo n.º 6
0
        public void DefaultDbName_WhenDataSourceIsPostgres_ShouldBePostgres()
        {
            var dsc = new DataSourceCredentials()
            {
                DataSourceType = DataSourceType.PgSql
            };

            dsc.GetDefaultDbName().Should().Be("postgres");
        }
Exemplo n.º 7
0
    public static void PatchDatasourceCredentials(string importName, string sqlAzureUser, string sqlAzurePassword)
    {
        PowerBIClient   pbiClient = GetPowerBiClient();
        IList <Dataset> datasets  = pbiClient.Datasets.GetDatasets().Value;

        foreach (var dataset in datasets)
        {
            if (dataset.Name.Equals(importName))
            {
                var    Datasource   = pbiClient.Datasets.GetGatewayDatasources(dataset.Id).Value[0];
                string DatasourceId = Datasource.Id;
                string GatewayId    = Datasource.GatewayId;

                // patching credentials does not yet work through the v2 API
                // you must complete this action with a direct HTTP PATCH request

                // create URL with pattern v1.0/myorg/gateways/{gateway_id}/datasources/{datasource_id}
                string restUrlPatchCredentials =
                    urlPowerBiRestApiRoot + "" +
                    "v1.0/myorg/" +
                    "gateways/" + GatewayId + "/" +
                    "datasources/" + DatasourceId + "/";

                // create C# object with credential data
                DataSourceCredentials dataSourceCredentials =
                    new DataSourceCredentials {
                    credentialType   = "Basic",
                    basicCredentials = new BasicCredentials {
                        username = sqlAzureUser,
                        password = sqlAzurePassword
                    }
                };

                // serialize C# object into JSON
                string jsonDelta = JsonConvert.SerializeObject(dataSourceCredentials);

                // add JSON to HttpContent object and configure content type
                HttpContent patchRequestBody = new StringContent(jsonDelta);
                patchRequestBody.Headers.ContentType = new MediaTypeWithQualityHeaderValue("application/json");

                // prepare PATCH request
                var method  = new HttpMethod("PATCH");
                var request = new HttpRequestMessage(method, restUrlPatchCredentials);
                request.Content = patchRequestBody;

                HttpClient client = new HttpClient();
                client.DefaultRequestHeaders.Add("Accept", "application/json");
                client.DefaultRequestHeaders.Add("Authorization", "Bearer " + GetAccessToken());

                // send PATCH request to Power BI service
                var result = client.SendAsync(request).Result;

                Console.WriteLine("Credentials have been updated..");
                Console.WriteLine();
            }
        }
    }
Exemplo n.º 8
0
        public void DefaultDbName_WhenDataSourceIsPostgres_ShouldBePostgres()
        {
            var dsc = new DataSourceCredentials()
            {
                DataSourceProvider = DataSourceProvider.Npgsql
            };

            dsc.GetDefaultDbName().Should().Be("postgres");
        }
 public async Task CreateOrUpdateDocumentDbDataSourceAsync(string dataSourceName, string dataSourceColletion)
 {
     string connectionString = string.Format("AccountEndpoint={0};AccountKey={1};Database={2}",
                                             _documentDbEndpoint, _documentDbAccountKey, _documentDbDatabase);
     DataSourceCredentials credentials = new DataSourceCredentials(connectionString);
     DataContainer         container   = new DataContainer(dataSourceColletion);
     DataSource            docDbSource = new DataSource(dataSourceName, DataSourceType.DocumentDb, credentials, container);
     await _serviceClient.DataSources.CreateOrUpdateAsync(docDbSource);
 }
Exemplo n.º 10
0
        public void GetDbConnection_WhenDataSourceTypeIsPgSql_ReturnsNpgsqlConnection()
        {
            var dbc = new DataSourceCredentials()
            {
                DataSourceType = DataSourceType.PgSql
            };

            var conn = dbc.GetDbConnectionObject();

            conn.GetType().FullName.Should().Be("Npgsql.NpgsqlConnection");
        }
Exemplo n.º 11
0
        public void GetDbDataAdapterObject_WhenDataSourceTypeIsPgSql_ReturnsNpgsqlDataAdapter()
        {
            var dbc = new DataSourceCredentials()
            {
                DataSourceType = DataSourceType.PgSql
            };

            var conn = dbc.GetDbDataAdapterObject();

            conn.GetType().FullName.Should().Be("Npgsql.NpgsqlDataAdapter");
        }
Exemplo n.º 12
0
        public void GetDbDataAdapterObject_WhenDataSourceTypeIsSqlServer_ReturnsSqlClientSqlDataAdapter()
        {
            var dbc = new DataSourceCredentials()
            {
                DataSourceType = DataSourceType.SqlServer
            };

            var conn = dbc.GetDbDataAdapterObject();

            conn.GetType().FullName.Should().Be("System.Data.SqlClient.SqlDataAdapter");
        }
        public void GetDbCommandObject_WhenDataSourceProviderIsPgSql_ReturnsNpgsqlCommand()
        {
            var dbc = new DataSourceCredentials()
            {
                DataSourceProvider = DataSourceProvider.Npgsql
            };

            var conn = dbc.GetDbCommandObject();

            conn.GetType().FullName.Should().Be("Npgsql.NpgsqlCommand");
        }
        public void GetDbCommandObject_WhenDataSourceProviderIsSqlServer_ReturnsSqlClientSqlCommandn()
        {
            var dbc = new DataSourceCredentials()
            {
                DataSourceProvider = DataSourceProvider.SqlServer
            };

            var conn = dbc.GetDbCommandObject();

            conn.GetType().FullName.Should().Be("System.Data.SqlClient.SqlCommand");
        }
 internal DataSource(string name, string description, DataSourceType type, DataSourceCredentials credentials, DataContainer container, DataChangeDetectionPolicy dataChangeDetectionPolicy, DataDeletionDetectionPolicy dataDeletionDetectionPolicy, string eTag)
 {
     Name        = name;
     Description = description;
     Type        = type;
     Credentials = credentials;
     Container   = container;
     DataChangeDetectionPolicy   = dataChangeDetectionPolicy;
     DataDeletionDetectionPolicy = dataDeletionDetectionPolicy;
     ETag = eTag;
 }
        public ActionResult Export(string writerFormat)
        {
            try
            {
                string       fileName        = null;
                string       reportserverUrl = WebConfigurationManager.AppSettings["ReportServerUrl"];
                WriterFormat format;
                HttpContext  httpContext  = System.Web.HttpContext.Current;
                ReportWriter reportWriter = new ReportWriter();
                reportWriter.ReportProcessingMode   = ProcessingMode.Remote;
                reportWriter.ReportServerUrl        = reportserverUrl;
                reportWriter.ReportPath             = "/SSRSSamples2/Territory Sales new";
                reportWriter.ReportServerCredential = new System.Net.NetworkCredential("ssrs", "RDLReport1");

                DataSourceCredentials _credential = new DataSourceCredentials();
                _credential.Name     = "AdventureWorks";
                _credential.UserId   = "ssrs1";
                _credential.Password = "******";

                IList <DataSourceCredentials> _credentials = new List <DataSourceCredentials>();
                _credentials.Add(_credential);
                reportWriter.SetDataSourceCredentials(_credentials);

                if (writerFormat == "PDF")
                {
                    fileName = "Territory Sales.pdf";
                    format   = WriterFormat.PDF;
                }
                else if (writerFormat == "Word")
                {
                    fileName = "Territory Sales.doc";
                    format   = WriterFormat.Word;
                }
                else if (writerFormat == "Html")
                {
                    fileName = "Territory Sales.Html";
                    format   = WriterFormat.HTML;
                }
                else
                {
                    fileName = "Territory Sales.xls";
                    format   = WriterFormat.Excel;
                }
                reportWriter.Save(fileName, format, httpContext.Response);
            }
            catch { }

            return(View());
        }
Exemplo n.º 17
0
        private void ReportViewer_ReportLoaded(object sender, EventArgs e)
        {
            List <DataSourceCredentials> crdentials = new List <DataSourceCredentials>();

            foreach (var dataSource in reportViewer.GetDataSources())
            {
                DataSourceCredentials credn = new DataSourceCredentials();
                credn.Name     = dataSource.Name;
                credn.UserId   = "ssrs1";
                credn.Password = "******";
                crdentials.Add(credn);
            }

            this.reportViewer.SetDataSourceCredentials(crdentials);
        }
Exemplo n.º 18
0
 private static void AssertCredentialsEqual(DataSourceCredentials expected, DataSourceCredentials actual, bool isGet)
 {
     if (expected == null)
     {
         Assert.Null(actual);
     }
     else if (isGet)
     {
         // Get doesn't return the connection string
         Assert.Null(actual.ConnectionString);
     }
     else
     {
         Assert.NotNull(actual);
         Assert.Equal(expected.ConnectionString, actual.ConnectionString);
     }
 }
Exemplo n.º 19
0
        /// <summary>
        /// Report Initialization method that is triggered when report begin processed.
        /// </summary>
        /// <param name="reportOptions">The ReportViewer options.</param>
        public void OnInitReportOptions(ReportViewerOptions reportOptions)
        {
            //throw new NotImplementedException();

            // Add RDL Server and database credentials here
            // Report Server
            string user     = LibraryHelper.AppSettings <string>("Report.RDLUser");
            string password = LibraryHelper.AppSettings <string>("Report.RDLPassword");

            reportOptions.ReportModel.ReportServerCredential = new System.Net.NetworkCredential(user, password);
            // Data Source
            string connectionName = "Chinook";

            string[] userPassword = AdoNetHelper.GetUserPassword(connectionName);
            DataSourceCredentials dataSourceCredentials = new DataSourceCredentials(connectionName, userPassword[0], userPassword[1]);

            reportOptions.ReportModel.DataSourceCredentials.Add(dataSourceCredentials);
        }
        private async Task CreateDataSourceAsync()
        {
            var dataContainer             = new DataContainer("Package", null);
            var dataSourceCredentials     = new DataSourceCredentials(GetCosmosDBConnectionString());
            var dataChangeDetectionPolicy = new HighWaterMarkChangeDetectionPolicy("_ts");

            var dataDeletionDetectionPolicy = new SoftDeleteColumnDeletionDetectionPolicy("IsDeleted", true);

            var dataSource = new DataSource(
                DATASOURCE_NAME,
                DataSourceType.DocumentDb,
                dataSourceCredentials,
                dataContainer, "Strikes CosmosDB Settings",
                dataChangeDetectionPolicy,
                dataDeletionDetectionPolicy);

            await _client.DataSources.CreateOrUpdateWithHttpMessagesAsync(dataSource);
        }
Exemplo n.º 21
0
        protected void Page_Load(object sender, EventArgs e)
        {
            ReportExecutionService rs = new ReportExecutionService();

            //set parameters and report settings
            string reportPath = "/StudentHistory";

            rs.Url = "http://sunflower.arvixe.com/ReportServer_SQL_Service/ReportExecution2005.asmx?wsdl";

            DataSourceCredentials credentials = new DataSourceCredentials();

            credentials.DataSourceName = "sunflower.arvixe.com";
            credentials.UserName       = "******";
            credentials.Password       = "******";

            rs.SetExecutionCredentials(new DataSourceCredentials[] { credentials });

            ExecutionInfo   info = new ExecutionInfo();
            ExecutionHeader header = new ExecutionHeader();
            string          historyId = "", extension = "", mimeType = "", encoding = "", devInfo = "False";

            string[]  streamId;
            Warning[] warning;
            byte[]    result;

            ParameterValue param = new ParameterValue();

            param.Name  = "@auditionOrgId";
            param.Value = "1036";

            rs.ExecutionHeaderValue = header;
            info = rs.LoadReport(reportPath, historyId);
            rs.SetExecutionParameters(new ParameterValue[] { param }, "en-us");
            result = rs.Render("PDF", devInfo, out extension, out mimeType, out encoding,
                               out warning, out streamId);

            Response.ClearContent();
            Response.AppendHeader("content-length", result.Length.ToString());
            Response.ContentType = "application/pdf";
            Response.BinaryWrite(result);
            Response.End();
            Response.Flush();
        }
Exemplo n.º 22
0
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                SkinStorage.SetVisualStyle(this, "Metro");
                if (tipo == true)
                {
                    //MessageBox.Show("1");
                    //viewer.Reset();
                    string xnameReporte = carpeta;
                    string usuario      = UserServer;
                    string contraseña   = UserServerPass;

                    viewer.ReportPath             = xnameReporte;
                    viewer.ReportServerUrl        = Server;
                    viewer.ProcessingMode         = ProcessingMode.Remote;
                    viewer.ReportServerCredential = new System.Net.NetworkCredential(usuario, contraseña);
                    List <DataSourceCredentials> crdentials = new List <DataSourceCredentials>();

                    foreach (var dataSource in viewer.GetDataSources())
                    {
                        DataSourceCredentials credn = new DataSourceCredentials();
                        credn.Name     = dataSource.Name;
                        credn.UserId   = "*****@*****.**";
                        credn.Password = "******";
                        crdentials.Add(credn);
                    }
                    viewer.SetDataSourceCredentials(crdentials);
                    viewer.RefreshReport();
                }
                //if (tipo == false) Navegador.Visibility = Visibility.Hidden;
            }
            catch (Exception w)
            {
                MessageBox.Show("error al cargar reporte:" + w);
            }
        }
        public void reporte()
        {
            //Syncfusion.Windows.Reports.Viewer.ReportViewer viewer = new Syncfusion.Windows.Reports.Viewer.ReportViewer();
            viewer1.ReportPath             = @"/Inventarios/ListaPrecios";
            viewer1.ReportServerUrl        = @"http://192.168.0.12:7333/Reportservergs";
            viewer1.ProcessingMode         = ProcessingMode.Remote;
            viewer1.ReportServerCredential = new System.Net.NetworkCredential(@"grupo\wilmer.barrios", "Siasoft2018*");
            viewer1.RefreshReport();
            List <DataSourceCredentials> crdentials = new List <DataSourceCredentials>();

            foreach (var dataSource in viewer1.GetDataSources())
            {
                DataSourceCredentials credn = new DataSourceCredentials();
                credn.Name     = dataSource.Name;
                credn.UserId   = "*****@*****.**";
                credn.Password = "******";
                crdentials.Add(credn);
            }
            viewer1.SetDataSourceCredentials(crdentials);
            viewer1.RefreshReport();

            //List<DataSourceCredentials> crdentials = new List<DataSourceCredentials>();

            //foreach (var dataSource in viewer.GetDataSources())
            //{
            //    DataSourceCredentials credn = new DataSourceCredentials();
            //    credn.Name = dataSource.Name;
            //    credn.UserId = "ssrs1";
            //    credn.Password = "******";
            //    crdentials.Add(credn);
            //}
            //viewer.SetDataSourceCredentials(crdentials);
            //viewer.RefreshReport();

            //viewer.ServerReport.SetParameters(parameters);
        }
Exemplo n.º 24
0
        public static bool ExportRDL(ZOperationResult operationResult, ref string exportPath, string exportFormat,
                                     string reportDirectory, string reportName, IDictionary <string, string> reportParameters)
        {
            try
            {
                ReportWriter reportWriter = new ReportWriter();
                reportWriter.ReportPath = "/" + MultiTenantHelper.Tenant.Name +
                                          (String.IsNullOrEmpty(reportDirectory) ? "" : "/" + reportDirectory) +
                                          "/" + reportName;
                reportWriter.ReportProcessingMode = ProcessingMode.Remote;

                // Report Credentials

                string user     = ConfigurationHelper.AppSettings <string>("Report.RDL.User");
                string password = ConfigurationHelper.AppSettings <string>("Report.RDL.Password");
                reportWriter.ReportServerCredential = new System.Net.NetworkCredential(user, password);

                reportWriter.ReportServerUrl = ConfigurationHelper.AppSettings <string>("Report.RDL.Url");

                // Data Source Credentials

                string   connection   = reportDirectory;
                string[] userPassword = AdoNetHelper.GetUserPassword(connection);
                DataSourceCredentials dataSourceCredentials = new DataSourceCredentials(connection, userPassword[0], userPassword[1]);
                reportWriter.SetDataSourceCredentials(new DataSourceCredentials[] { dataSourceCredentials });

                // Parameter(s)

                IList <ReportParameter> reportWriterParameters = new List <ReportParameter>(); // Syncfusion.Reports.EJ.ReportParameter
                foreach (KeyValuePair <string, string> pair in reportParameters)
                {
                    ReportParameter reportParameter = new ReportParameter();
                    reportParameter.Name = pair.Key;
                    reportParameter.Values.Add(pair.Value);
                    reportWriterParameters.Add(reportParameter);
                }
                reportWriter.SetParameters(reportWriterParameters);

                // Data Source(s) & DataSet(s)

                // Export

                string       fileExtension = ".pdf";
                WriterFormat writerFormat  = WriterFormat.PDF;
                switch (exportFormat.ToLower())
                {
                case "doc":
                    fileExtension = ".doc";
                    writerFormat  = WriterFormat.Word;
                    break;

                case "xls":
                    fileExtension = ".xls";
                    writerFormat  = WriterFormat.Excel;
                    break;
                }
                exportPath = exportPath.Trim() + fileExtension;
                FileStream fileStream = new FileStream(exportPath, FileMode.Create);
                reportWriter.Save(fileStream, writerFormat);
                fileStream.Close();

                operationResult.StatusMessage = exportPath;
            }
            catch (Exception exception)
            {
                operationResult.ParseException(exception);
            }

            return(operationResult.Ok);
        }
 /// <remarks/>
 public void GetItemParametersAsync(string ItemPath, string HistoryID, bool ForRendering, ParameterValue[] Values, DataSourceCredentials[] Credentials)
 {
     this.GetItemParametersAsync(ItemPath, HistoryID, ForRendering, Values, Credentials, null);
 }
Exemplo n.º 26
0
        /// <summary>
        /// Processes a shp file and uploads it to a db
        /// </summary>
        /// <param name="dbCtx"></param>
        /// <param name="path">Path to a directory a shapefile has been uploaded to</param>
        /// <param name="dsc"></param>
        /// <returns></returns>
        public static async Task <DataStore> ProcessShp(DbContext dbCtx, string path, DataSourceCredentials dsc)
        {
            //assuming a single zip can only be present in a directory, as uploading data for a single layer

            //if there is a zip archive, need to extract it
            ExtractZip(path);


            //test for required shp format files presence...
            var shp = string.Empty;

            ValidateShpFilePresence(path, out shp);


            var fName = Path.GetFileNameWithoutExtension(shp);

            var output = GetDataStore(fName, "shp", dsc);


            //need this for a proper code page handling when reading dbf
            System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);

            //looks like it should be possible to read shp now...
            using (var shpReader = new NetTopologySuite.IO.ShapefileDataReader(shp, new GeometryFactory()))
            {
                ExtractShpDataBbox(shpReader, output);

                ExtractShpColumns(shpReader, output);

                //create object straight away, so when something goes wrong with import, etc. there is a chance for a cleanup bot
                //to pick it up and cleanup the orphaned data when necessary
                await output.CreateAsync(dbCtx);

                await ReadAndLoadShpData(shpReader, output);
            }


            return(output);
        }
Exemplo n.º 27
0
        /// <summary>
        /// Handles setting up the MapHive environment - maphive meta db, idsrv db and membership reboot db
        /// </summary>
        /// <param name="args"></param>
        protected virtual async Task Handle_SetUpDb(IDictionary <string, string> args)
        {
            var cmd = GetCallerName();

            if (GetHelp(args))
            {
                Console.WriteLine($"'{cmd}' : sets up the maphive dbs - maphive_meta, maphive_idsrv, maphive_mr; uses the configured db credentials to connect to the db server.");
                Console.WriteLine($"syntax: {cmd} space separated params: ");
                Console.WriteLine("\t[full:{presence}; whether or not all the databases created/upgraded]");
                Console.WriteLine("\t[mh:{presence}; whether or not maphive_meta should be created/upgraded]");
                Console.WriteLine("\t[mr:{presence}; whether or not maphive_mr (MembershipReboot) should be created/upgraded]");
                Console.WriteLine("\t[idsrv:{presence}; whether or not maphive_idsrv (IdentityServer) should be created/upgraded]");
                Console.WriteLine("\t[xfull:{presence}; whether or not all the databases should be dropped prior to being recreated]");
                Console.WriteLine("\t[xmh:{presence}; whether or not maphive_meta should be dropped prior to being recreated]");
                Console.WriteLine("\t[xmr:{presence}; whether or not maphive_mr (MembershipReboot) should be dropped prior to being recreated]");
                Console.WriteLine("\t[xidsrv:{presence}; whether or not maphive_idsrv (IdentityServer) should be dropped prior to being recreated]");

                Console.WriteLine($"example: {cmd} m mr idsrv xm xmr xidsrv");
                Console.WriteLine($"example: {cmd} full xfull");
                Console.WriteLine();

                return;
            }

            var dbsToDrop        = new List <string>();
            var migrationConfigs = new Dictionary <DbMigrationsConfiguration, string>();

            if (ContainsParam("full", args) || ContainsParam("mh", args))
            {
                migrationConfigs[new MapHive.Server.Core.DAL.Migrations.MapHiveMetaConfiguration.Configuration()] = "maphive_meta";
            }
            if (ContainsParam("xfull", args) || ContainsParam("xmh", args))
            {
                dbsToDrop.Add("maphive_meta");
            }
            if (ContainsParam("full", args) || ContainsParam("mr", args))
            {
                migrationConfigs[new MapHive.Identity.MembershipReboot.Migrations.Configuration()] = "maphive_mr";
            }
            if (ContainsParam("xfull", args) || ContainsParam("xmr", args))
            {
                dbsToDrop.Add("maphive_mr");
            }
            if (ContainsParam("full", args) || ContainsParam("idsrv", args))
            {
                migrationConfigs[new MapHive.Identity.IdentityServer.Migrations.ClientConfiguration.Configuration()]      = "maphive_idsrv";
                migrationConfigs[new MapHive.Identity.IdentityServer.Migrations.OperationalConfiguration.Configuration()] = "maphive_idsrv";
                migrationConfigs[new MapHive.Identity.IdentityServer.Migrations.ScopeConfiguration.Configuration()]       = "maphive_idsrv";
            }
            if (ContainsParam("xfull", args) || ContainsParam("xidsrv", args))
            {
                dbsToDrop.Add("maphive_idsrv");
            }

            //got here, so need to drop the dbs first in order to recreate them later
            if (dbsToDrop.Count > 0)
            {
                if (
                    !PromptUser(
                        $"You are about to drop the following databases {string.Join(", ", dbsToDrop)}. Are you sure you want to proceed?"))
                {
                    return;
                }

                DropDb(dbsToDrop.ToArray());
            }


            if (migrationConfigs.Count > 0)
            {
                ConsoleEx.WriteLine("Updating dbs... ", ConsoleColor.DarkYellow);
                try
                {
                    foreach (var migrationCfg in migrationConfigs.Keys)
                    {
                        var dbc = new DataSourceCredentials
                        {
                            DbName         = migrationConfigs[migrationCfg],
                            ServerHost     = Dsc.ServerHost,
                            ServerPort     = Dsc.ServerPort,
                            UserName       = Dsc.UserName,
                            Pass           = Dsc.Pass,
                            DataSourceType = DataSourceType.PgSql
                        };

                        try
                        {
                            ConsoleEx.Write($"{migrationCfg.ToString()}... ", ConsoleColor.DarkYellow);

                            //TODO - make the provider name somewhat more dynamic...
                            migrationCfg.TargetDatabase = new DbConnectionInfo(dbc.GetConnectionString(), "Npgsql");

                            var migrator = new DbMigrator(migrationCfg);


                            migrator.Update();
                            ConsoleEx.Write("Done!" + Environment.NewLine, ConsoleColor.DarkGreen);
                        }
                        catch (Exception ex)
                        {
                            ConsoleEx.WriteErr($"OOOPS... Failed to create/update database: {migrationCfg}");
                            HandleException(ex, true);
                            throw;
                        }
                    }
                }
                catch (Exception ex)
                {
                    //ignore
                    return;
                }
            }


            if (dbsToDrop.Count == 0 && migrationConfigs.Count == 0)
            {
                ConsoleEx.WriteLine(
                    "Looks like i have nothing to do... Type 'setup help' for more details on how to use this command.",
                    ConsoleColor.DarkYellow);
            }
            else
            {
                EfConnectionsPoolCacheCleanup();
            }

            Console.WriteLine();
        }
 /// <remarks/>
 public void SetExecutionCredentialsAsync(DataSourceCredentials[] Credentials, object userState)
 {
     if ((this.SetExecutionCredentialsOperationCompleted == null)) {
         this.SetExecutionCredentialsOperationCompleted = new System.Threading.SendOrPostCallback(this.OnSetExecutionCredentialsOperationCompleted);
     }
     this.InvokeAsync("SetExecutionCredentials", new object[] {
                 Credentials}, this.SetExecutionCredentialsOperationCompleted, userState);
 }
 /// <remarks/>
 public System.IAsyncResult BeginSetExecutionCredentials2(DataSourceCredentials[] Credentials, System.AsyncCallback callback, object asyncState)
 {
     return this.BeginInvoke("SetExecutionCredentials2", new object[] {
                 Credentials}, callback, asyncState);
 }
 /// <remarks/>
 public void GetReportParametersAsync(string Report, string HistoryID, bool ForRendering, ParameterValue[] Values, DataSourceCredentials[] Credentials, object userState)
 {
     if ((this.GetReportParametersOperationCompleted == null))
     {
         this.GetReportParametersOperationCompleted = new System.Threading.SendOrPostCallback(this.OnGetReportParametersOperationCompleted);
     }
     this.InvokeAsync("GetReportParameters", new object[] {
                 Report,
                 HistoryID,
                 ForRendering,
                 Values,
                 Credentials}, this.GetReportParametersOperationCompleted, userState);
 }
 public ExecutionInfo2 SetExecutionCredentials2(DataSourceCredentials[] Credentials)
 {
     object[] results = this.Invoke("SetExecutionCredentials2", new object[] {
                 Credentials});
     return ((ExecutionInfo2)(results[0]));
 }
 /// <remarks/>
 public System.IAsyncResult BeginGetReportParameters(string Report, string HistoryID, bool ForRendering, ParameterValue[] Values, DataSourceCredentials[] Credentials, System.AsyncCallback callback, object asyncState)
 {
     return this.BeginInvoke("GetReportParameters", new object[] {
                 Report,
                 HistoryID,
                 ForRendering,
                 Values,
                 Credentials}, callback, asyncState);
 }
 /// <remarks/>
 public void SetExecutionCredentialsAsync(DataSourceCredentials[] Credentials)
 {
     this.SetExecutionCredentialsAsync(Credentials, null);
 }
Exemplo n.º 34
0
        //private void TreeViewItem_Selected(object sender, MouseButtonEventArgs e)
        private void TreeViewItem_Selected(object sender, RoutedEventArgs e)
        {
            try
            {
                TreeViewItem item = sender as TreeViewItem;


                if (item == e.OriginalSource)
                {
                    var MultiTag = (TagMultiple)(sender as TreeViewItem).Tag;

                    if (MultiTag.IsRep == true)
                    {
                        switch (MultiTag.typePnt)
                        {
                        case "1":    //abre un tab interno de esta pantalla
                            Syncfusion.Windows.Reports.Viewer.ReportViewer viewer = new Syncfusion.Windows.Reports.Viewer.ReportViewer();
                            viewer.ReportPath             = MultiTag.urlRep;
                            viewer.ReportServerUrl        = MultiTag.serverIp;
                            viewer.ProcessingMode         = ProcessingMode.Remote;
                            viewer.ReportServerCredential = new System.Net.NetworkCredential(MultiTag.userServer, MultiTag.userServerPass);
                            List <DataSourceCredentials> crdentials = new List <DataSourceCredentials>();

                            foreach (var dataSource in viewer.GetDataSources())
                            {
                                DataSourceCredentials credn = new DataSourceCredentials();
                                credn.Name     = dataSource.Name;
                                credn.UserId   = "*****@*****.**";
                                credn.Password = "******";
                                crdentials.Add(credn);
                            }
                            viewer.SetDataSourceCredentials(crdentials);
                            viewer.RefreshReport();

                            TabItemExt tabItemExt1 = new TabItemExt();
                            tabItemExt1.Header  = MultiTag.NamePnt;
                            tabItemExt1.Content = viewer;
                            TabControlPricipal.Items.Add(tabItemExt1);
                            break;

                        case "3":
                            dynamic ww = SiaWin.WindowExt(9531, "MenuReporteWindow");
                            ww.tipo                  = MultiTag.IsRep;
                            ww.Server                = MultiTag.serverIp;
                            ww.UserServer            = MultiTag.userServer;
                            ww.UserServerPass        = MultiTag.userServerPass;
                            ww.carpeta               = MultiTag.urlRep;
                            ww.ShowInTaskbar         = false;
                            ww.Owner                 = Application.Current.MainWindow;
                            ww.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                            ww.ShowDialog();
                            break;
                        }
                    }
                    else
                    {
                        switch (MultiTag.typePnt)
                        {
                        case "2":    //userconotrol reporte
                            SiaWin.TabU(MultiTag.Id_screen);
                            break;

                        case "4":
                            WebBrowser webPowBi = new WebBrowser();
                            string     urlPowBi = MultiTag.urlRep;
                            webPowBi.Navigate(urlPowBi);
                            TabItemExt tabItemExtPowBi = new TabItemExt();
                            tabItemExtPowBi.Header  = MultiTag.NamePnt;
                            tabItemExtPowBi.Content = webPowBi;
                            TabControlPricipal.Items.Add(tabItemExtPowBi);
                            break;

                        case "5":
                            WebBrowser web = new WebBrowser();
                            string     url = MultiTag.urlRep;
                            web.Navigate(url);
                            TabItemExt tabItemExt = new TabItemExt();
                            tabItemExt.Header  = MultiTag.NamePnt;
                            tabItemExt.Content = web;
                            TabControlPricipal.Items.Add(tabItemExt);
                            break;
                        }
                    }

                    //item.IsSelected = false;
                    //e.Handled = true;
                }
            }
            catch (Exception w)
            {
                MessageBox.Show("error en el select del item consulte con el administrador:" + w);
            }
        }
Exemplo n.º 35
0
        private static void CreateAndSyncIndexer()
        {
            // Create a new indexer and sync it
            try
            {
                var        creds = new DataSourceCredentials("Server=tcp:azs-playground.database.windows.net,1433;Database=usgs;User ID=reader;Password=EdrERBt3j6mZDP;Trusted_Connection=False;Encrypt=True;Connection Timeout=30");
                DataSource ds    = new DataSource("usgs-datasource", DataSourceType.AzureSql, creds, new DataContainer("GeoNamesRI"));
                ds.Description = "USGS Dataset";

                Indexer idx = new Indexer();
                idx.Name                              = "usgs-indexer";
                idx.Description                       = "USGS data indexer";
                idx.DataSourceName                    = "usgs-datasource";
                idx.TargetIndexName                   = "geonames";
                idx.Parameters                        = new IndexingParameters();
                idx.Parameters.MaxFailedItems         = 10;
                idx.Parameters.MaxFailedItemsPerBatch = 5;
                idx.Parameters.Base64EncodeKeys       = false;

                //Delete indexer and datasource if it existed
                _searchClient.DataSources.Delete("usgs-datasource");
                _searchClient.Indexers.Delete("usgs-indexer");

                //Create indexer and datasource
                _searchClient.DataSources.Create(ds);
                _searchClient.Indexers.Create(idx);

                //Launch the sync and then monitor progress until complete
                bool running = true;

                Console.WriteLine("{0}", "Synchronization running...\n");
                while (running)
                {
                    IndexerExecutionInfo status = null;
                    try
                    {
                        status = _searchClient.Indexers.GetStatus(idx.Name);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Error polling for indexer status: {0}", ex.Message);
                        return;
                    }

                    IndexerExecutionResult lastResult = status.LastResult;
                    if (lastResult != null)
                    {
                        switch (lastResult.Status)
                        {
                        case IndexerExecutionStatus.InProgress:
                            Console.WriteLine("{0}", "Synchronization running...\n");
                            Thread.Sleep(1000);
                            break;

                        case IndexerExecutionStatus.Success:
                            running = false;
                            Console.WriteLine("Synchronized {0} rows...\n", lastResult.ItemCount);
                            break;

                        default:
                            running = false;
                            Console.WriteLine("Synchronization failed: {0}\n", lastResult.ErrorMessage);
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error creating indexer: {0}: \n", ex.Message.ToString());
            }
        }
 public ReportParameter[] GetReportParameters(string Report, string HistoryID, bool ForRendering, ParameterValue[] Values, DataSourceCredentials[] Credentials)
 {
     object[] results = this.Invoke("GetReportParameters", new object[] {
                 Report,
                 HistoryID,
                 ForRendering,
                 Values,
                 Credentials});
     return ((ReportParameter[])(results[0]));
 }
        /// <summary>
        /// Processes a flat json file; file has got to have numeric lon / longitude & lat / latitude properties; coords are assumed to be in lon/lat
        /// </summary>
        /// <param name="dbCtx"></param>
        /// <param name="path"></param>
        /// <param name="dsc"></param>
        /// <returns></returns>
        public static async Task <DataStore> ProcessJson(DbContext dbCtx, string path, DataSourceCredentials dsc)
        {
            //assuming a single zip can only be present in a directory, as uploading data for a single layer

            //if there is a zip archive, need to extract it
            ExtractZip(path);


            //test for required shp format files presence...
            var file = Directory.GetFiles(path, "*.json").FirstOrDefault();

            if (string.IsNullOrEmpty(file))
            {
                throw MapHive.Core.DataModel.Validation.Utils.GenerateValidationFailedException("JSON", "no_json_file",
                                                                                                "JSON file has not been found");
            }

            var fName = Path.GetFileNameWithoutExtension(file);

            var output = GetDataStore(fName, "json", dsc);


            var json = JsonConvert.DeserializeObject(File.ReadAllText(file));

            if (json.GetType() != typeof(JArray))
            {
                throw MapHive.Core.DataModel.Validation.Utils.GenerateValidationFailedException("JSON", "not_array",
                                                                                                "JSON file has not been deserialized to array");
            }

            var data = new List <Dictionary <string, object> >(((JArray)json).Count);

            foreach (JObject jRec in (JArray)json)
            {
                var rec = new Dictionary <string, object>();

                foreach (var jProp in jRec.Properties())
                {
                    var propName = jProp.Name.ToLower();

                    //basically looking at a flat json file, BUT allowing convenience parsing for some nested properties
                    if (FlatLonProps.Contains(propName))
                    {
                        rec.Add("lo", GetValueFromJsonProperty(jProp.Value));
                    }
                    else if (FlatLatProps.Contains(propName))
                    {
                        rec.Add("la", GetValueFromJsonProperty(jProp.Value));
                    }
                    else if (FlatGeoLocationProps.Contains(propName))
                    {
                        if (TryExtractLoLaFromJsonObject((JObject)jProp.Value, out var lo, out var la))
                        {
                            rec.Add("lo", lo);
                            rec.Add("la", la);
                        }
                        ;
                    }
                    else if (FlatGeomProps.Contains(propName))
                    {
                        rec.Add("wkt", GetValueFromJsonProperty(jProp.Value));
                    }
                    else
                    {
                        rec.Add(jProp.Name, GetValueFromJsonProperty(jProp.Value));
                    }
                }

                if (rec.ContainsKey("lo") && rec.ContainsKey("la") || rec.ContainsKey("wkt"))
                {
                    data.Add(rec);
                }
            }


            //work out a data model - this is json, so can be totally unpredictable
            foreach (var rec in data)
            {
                foreach (var fProp in rec)
                {
                    //ignore lon/lat, this will be turned into a point
                    //testing for lon/lat only as data is already normalized
                    if (fProp.Key == "lo" || fProp.Key == "la" || fProp.Key == "wkt")
                    {
                        continue;
                    }

                    if (output.DataSource.Columns.Any(c => c.Name == GetSafeDbObjectName(fProp.Key)))
                    {
                        continue;
                    }

                    if (!CheckIfObjectSafe(fProp.Key))
                    {
                        throw MapHive.Core.DataModel.Validation.Utils.GenerateValidationFailedException("ColName", "bad_col_name",
                                                                                                        "Column name contains forbidden words");
                    }

                    var colType = SystemTypeToColumnDataType(fProp.Value.GetType());
                    if (colType != ColumnDataType.Unknown)
                    {
                        output.DataSource.Columns.Add(new Column
                        {
                            Type         = colType,
                            Name         = GetSafeDbObjectName(fProp.Key),
                            FriendlyName = fProp.Key
                        });
                    }
                }
            }

            //create object straight away, so when something goes wrong with import, etc. there is a chance for a cleanup bot
            //to pick it up and cleanup the orphaned data when necessary
            await output.CreateAsync(dbCtx);

            return(await ProcessFlatData(dbCtx, output, data));
        }
        /// <summary>
        /// Processes a flat csv file; file has got to have numeric lon / longitude & lat / latitude properties; coords are assumed to be in lon/lat
        /// </summary>
        /// <param name="dbCtx"></param>
        /// <param name="path"></param>
        /// <param name="dsc"></param>
        /// <returns></returns>
        public static async Task <DataStore> ProcessCsv(DbContext dbCtx, string path, DataSourceCredentials dsc)
        {
            //assuming a single zip can only be present in a directory, as uploading data for a single layer

            //if there is a zip archive, need to extract it
            var zip = Directory.GetFiles(path, "*.zip").FirstOrDefault();

            if (!string.IsNullOrEmpty(zip))
            {
                System.IO.Compression.ZipFile.ExtractToDirectory(zip, path);
            }


            //test for required shp format files presence...
            var file = Directory.GetFiles(path, "*.csv").FirstOrDefault();

            if (string.IsNullOrEmpty(file))
            {
                throw MapHive.Core.DataModel.Validation.Utils.GenerateValidationFailedException("CSV", "no_csv_file",
                                                                                                "CSV file has not been found");
            }

            var fName = Path.GetFileNameWithoutExtension(file);

            var output = GetDataStore(fName, "csv", dsc);

            ExtractCsvColumns(file, output);

            var data = ExtractCsvData(file, output);

            //create object straight away, so when something goes wrong with import, etc. there is a chance for a cleanup bot
            //to pick it up and cleanup the orphaned data when necessary
            await output.CreateAsync(dbCtx);

            return(await ProcessFlatData(dbCtx, output, data));
        }
 /// <remarks/>
 public void GetReportParametersAsync(string Report, string HistoryID, bool ForRendering, ParameterValue[] Values, DataSourceCredentials[] Credentials)
 {
     this.GetReportParametersAsync(Report, HistoryID, ForRendering, Values, Credentials, null);
 }