Example #1
0
 public ServerStatus(ServerVersion version, PlayerList players, string description, string icon)
 {
     Version = version;
     Players = players;
     Description = description;
     Icon = icon;
 }
Example #2
0
    /// <summary>
    /// Constructor
    /// </summary>
    /// <param name="serverNameWithProtocol"></param>
    /// <param name="siteUrlSegment"></param>
    public TableauServerUrls(string protocol, string serverName, string siteUrlSegment, int pageSize, ServerVersion serverVersion)
    {
        //Cannonicalize the protocol
        protocol = protocol.ToLower();

        this.ServerProtocol = protocol;

        this.PageSize = pageSize;
        string serverNameWithProtocol = protocol + serverName;
        this._serverVersion = serverVersion;
        this.SiteUrlSegement = siteUrlSegment;
        this.ServerName = serverName;
        this.ServerUrlWithProtocol                 = serverNameWithProtocol;
        this.UrlLogin                              = serverNameWithProtocol + "/api/2.0/auth/signin";
        this.UrlLogout                             = serverNameWithProtocol + "/api/2.0/auth/signout";
        this._urlListWorkbooksForUserTemplate = serverNameWithProtocol + "/api/2.0/sites/{{iwsSiteId}}/users/{{iwsUserId}}/workbooks?pageSize={{iwsPageSize}}&pageNumber={{iwsPageNumber}}";
        this._urlListWorkbookConnectionsTemplate   = serverNameWithProtocol + "/api/2.0/sites/{{iwsSiteId}}/workbooks/{{iwsWorkbookId}}/connections";
        this._urlListDatasourcesTemplate           = serverNameWithProtocol + "/api/2.0/sites/{{iwsSiteId}}/datasources?pageSize={{iwsPageSize}}&pageNumber={{iwsPageNumber}}";
        this._urlListProjectsTemplate              = serverNameWithProtocol + "/api/2.0/sites/{{iwsSiteId}}/projects?pageSize={{iwsPageSize}}&pageNumber={{iwsPageNumber}}";
        this._urlListGroupsTemplate                = serverNameWithProtocol + "/api/2.0/sites/{{iwsSiteId}}/groups?pageSize={{iwsPageSize}}&pageNumber={{iwsPageNumber}}";
        this._urlListUsersTemplate                 = serverNameWithProtocol + "/api/2.0/sites/{{iwsSiteId}}/users?pageSize={{iwsPageSize}}&pageNumber={{iwsPageNumber}}";
        this._urlListUsersInGroupTemplate          = serverNameWithProtocol + "/api/2.0/sites/{{iwsSiteId}}/groups/{{iwsGroupId}}/users?pageSize={{iwsPageSize}}&pageNumber={{iwsPageNumber}}";
        this._urlDownloadDatasourceTemplate        = serverNameWithProtocol + "/api/2.0/sites/{{iwsSiteId}}/datasources/{{iwsRepositoryId}}/content";
        this._urlDownloadWorkbookTemplate          = serverNameWithProtocol + "/api/2.0/sites/{{iwsSiteId}}/workbooks/{{iwsRepositoryId}}/content";
        this._urlSiteInfoTemplate                  = serverNameWithProtocol + "/api/2.0/sites/{{iwsSiteId}}";
        this._urlInitiateUploadTemplate            = serverNameWithProtocol + "/api/2.0/sites/{{iwsSiteId}}/fileUploads";
        this._urlAppendUploadChunkTemplate         = serverNameWithProtocol + "/api/2.0/sites/{{iwsSiteId}}/fileUploads/{{iwsUploadSession}}";
        this._urlFinalizeUploadDatasourceTemplate  = serverNameWithProtocol + "/api/2.0/sites/{{iwsSiteId}}/datasources?uploadSessionId={{iwsUploadSession}}&datasourceType={{iwsDatasourceType}}&overwrite=true";
        this._urlFinalizeUploadWorkbookTemplate    = serverNameWithProtocol + "/api/2.0/sites/{{iwsSiteId}}/workbooks?uploadSessionId={{iwsUploadSession}}&workbookType={{iwsWorkbookType}}&overwrite=true";
        this._urlCreateProjectTemplate             = serverNameWithProtocol + "/api/2.0/sites/{{iwsSiteId}}/projects";
        this._urlDeleteWorkbookTagTemplate         = serverNameWithProtocol + "/api/2.0/sites/{{iwsSiteId}}/workbooks/{{iwsWorkbookId}}/tags/{{iwsTagText}}";
        this._urlDeleteDatasourceTagTemplate       = serverNameWithProtocol + "/api/2.0/sites/{{iwsSiteId}}/datasources/{{iwsDatasourceId}}/tags/{{iwsTagText}}";
        this._urlUpdateWorkbookTemplate            = serverNameWithProtocol + "/api/2.0/sites/{{iwsSiteId}}/workbooks/{{iwsWorkbookId}}";
        this._urlUpdateDatasourceTemplate          = serverNameWithProtocol + "/api/2.0/sites/{{iwsSiteId}}/datasources/{{iwsDatasourceId}}";
        //Any server version specific things we want to do?
        switch (serverVersion)
        {
            case ServerVersion.server8:
                throw new Exception("This app does not support v8 Server");
            case ServerVersion.server9:
                break;
            default:
                AppDiagnostics.Assert(false, "Unknown server version");
                throw new Exception("Unknown server version");
        }
    }
        public static void ConfigureDbContext(this IServiceCollection services, IConfiguration configuration)
        {
            string connectionStr = configuration.GetConnectionString("mysqlConString");

            services
            .AddPooledDbContextFactory <StorageContext>(opt => opt.UseMySql(connectionStr, ServerVersion.AutoDetect(connectionStr)));
        }
Example #4
0
            public MockedConnection(AccessMode mode, List <Tuple <IRequestMessage, IResponseMessage> > messages,
                                    ServerInfo serverInfo = null, IDictionary <string, string> routingContext = null)
            {
                foreach (var pair in messages)
                {
                    if (pair.Item1 != null)
                    {
                        _requestMessages.Add(pair.Item1);
                    }

                    if (pair.Item2 != null)
                    {
                        _responseMessages.Add(pair.Item2);
                    }
                }

                _mockConn.Setup(x => x.EnqueueAsync(It.IsAny <IRequestMessage>(), It.IsAny <IResponseHandler>(),
                                                    It.IsAny <IRequestMessage>(), It.IsAny <IResponseHandler>()))
                .Returns(Task.CompletedTask)
                .Callback <IRequestMessage, IResponseHandler, IRequestMessage, IResponseHandler>(
                    (msg1, handler1, msg2, handler2) =>
                {
                    msg1.ToString().Should().Be(_requestMessages[_requestCount].ToString());
                    _requestCount++;
                    _pipeline.Enqueue(msg1, handler1);

                    if (msg2 != null)
                    {
                        msg2.ToString().Should().Be(_requestMessages[_requestCount].ToString());
                        _requestCount++;
                        _pipeline.Enqueue(msg2, handler2);
                    }
                });

                _mockConn.Setup(x => x.ReceiveOneAsync())
                .Returns(() =>
                {
                    if (_responseCount < _responseMessages.Count)
                    {
                        _responseMessages[_responseCount].Dispatch(_pipeline);
                        _responseCount++;
                        _pipeline.AssertNoFailure();
                        return(Task.CompletedTask);
                    }
                    else
                    {
                        throw new InvalidOperationException("Not enough response message to provide");
                    }
                });

                _mockConn.Setup(x => x.SyncAsync())
                .Returns(() =>
                {
                    if (_responseCount < _responseMessages.Count)
                    {
                        _responseMessages[_responseCount].Dispatch(_pipeline);
                        _responseCount++;
                        _pipeline.AssertNoFailure();
                        return(Task.CompletedTask);
                    }
                    else
                    {
                        throw new InvalidOperationException("Not enough response message to provide");
                    }
                });


                _mockConn.Setup(x => x.IsOpen).Returns(() => _responseCount < _responseMessages.Count);

                _mockConn.Setup(x => x.Mode).Returns(mode);

                var protocol = new BoltProtocolV3();

                if (serverInfo != null)
                {
                    if (ServerVersion.From(serverInfo.Agent) >= new ServerVersion(4, 0, 0))
                    {
                        protocol = new BoltProtocolV4_0();
                    }
                    if (ServerVersion.From(serverInfo.Agent) >= new ServerVersion(4, 3, 0))
                    {
                        protocol = new BoltProtocolV4_3(routingContext);
                    }

                    _mockConn.Setup(x => x.Server).Returns(serverInfo);
                }
                else
                {
                    _mockConn.Setup(x => x.Server)
                    .Returns(new ServerInfo(new Uri("bolt://123:456"))
                    {
                        Agent = "Neo4j/3.5.0"
                    });
                }

                _mockConn.Setup(x => x.BoltProtocol).Returns(protocol);
            }
Example #5
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <KT_24SPContext>(options =>
                                                   options.UseSqlServer(Configuration.GetConnectionString("KT24SP")));

            string connectionString = Configuration.GetConnectionString("BonusCalc");

            services.AddDbContext <BonusCalcContext>(options =>
                                                     options.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString), mySqlOptions => mySqlOptions
                                                                      .CharSetBehavior(CharSetBehavior.NeverAppend)));


            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "firmaApi", Version = "v1"
                });
            });
        }
Example #6
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add Services
            services.AddScoped(typeof(IAsyncRepository <>), typeof(Repository <>));
            services.AddScoped(typeof(IMainTableService <,>), typeof(MainTableService <,>));
            services.AddScoped <IDashboardService, DashboardService>();
            services.AddScoped <IEmployeeService, EmployeeService>();
            services.AddScoped <IHardwareVaultService, HardwareVaultService>();
            services.AddScoped <IHardwareVaultTaskService, HardwareVaultTaskService>();
            services.AddScoped <IAccountService, AccountService>();
            services.AddScoped <IWorkstationService, WorkstationService>();
            services.AddScoped <IWorkstationAuditService, WorkstationAuditService>();
            services.AddScoped <ISharedAccountService, SharedAccountService>();
            services.AddScoped <ITemplateService, TemplateService>();
            services.AddScoped <IApplicationUserService, ApplicationUserService>();
            services.AddScoped <IOrgStructureService, OrgStructureService>();
            services.AddScoped <ILogsViewerService, LogsViewerService>();
            services.AddScoped <IRemoteWorkstationConnectionsService, RemoteWorkstationConnectionsService>();
            services.AddScoped <IRemoteDeviceConnectionsService, RemoteDeviceConnectionsService>();
            services.AddScoped <IRemoteTaskService, RemoteTaskService>();
            services.AddScoped <IEmailSenderService, EmailSenderService>();
            services.AddScoped <ILicenseService, LicenseService>();
            services.AddScoped <IAppSettingsService, AppSettingsService>();
            services.AddScoped <IToastService, ToastService>();
            services.AddScoped <IModalDialogService, ModalDialogService>();
            services.AddScoped <IGroupService, GroupService>();
            services.AddScoped <ILdapService, LdapService>();
            services.AddScoped <ISoftwareVaultService, SoftwareVaultService>();
            services.AddScoped <IBreadcrumbsService, BreadcrumbsService>();
            services.AddScoped <IFido2Service, Fido2Service>();
            services.AddScoped <IIdentityApiClient, IdentityApiClient>();

            services.AddScoped <HttpClient>();
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            services.AddSingleton <IDataProtectionService, DataProtectionService>();
            services.AddSingleton <ISynchronizationService, SynchronizationService>();

            services.AddHostedService <RemoveLogsHostedService>();
            services.AddHostedService <LicenseHostedService>();
            services.AddHostedService <ActiveDirectoryHostedService>();

            services.AddHttpClient().RemoveAll <IHttpMessageHandlerBuilderFilter>();
            services.AddSignalR();
            services.AddMemoryCache();

            // Cookie
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.ConfigureApplicationCookie(options =>
            {
                options.Cookie.HttpOnly = true;
                options.ExpireTimeSpan  = TimeSpan.FromDays(14);
                options.LoginPath       = "/login";
                options.LogoutPath      = "/Account/Logout";
                options.Cookie          = new CookieBuilder
                {
                    IsEssential = true // required for auth to work without explicit user consent; adjust to suit your privacy policy
                };
            });

            // Dismiss strong password
            services.Configure <IdentityOptions>(options =>
            {
                // Password settings
                options.Password.RequireDigit           = false;
                options.Password.RequiredLength         = 3;
                options.Password.RequireLowercase       = false;
                options.Password.RequireUppercase       = false;
                options.Password.RequiredUniqueChars    = 0;
                options.Password.RequireNonAlphanumeric = false;

                // Lockout settings
                options.Lockout.DefaultLockoutTimeSpan  = TimeSpan.FromMinutes(15);
                options.Lockout.MaxFailedAccessAttempts = 10;
                options.Lockout.AllowedForNewUsers      = true;
            });

            services.Configure <Fido2Configuration>(Configuration.GetSection("Fido2"));

            // Database
            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseMySql(Configuration.GetConnectionString("DefaultConnection"), ServerVersion.AutoDetect(Configuration.GetConnectionString("DefaultConnection"))));

            // Identity
            services.AddIdentity <ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders();

            // IDP
            if (Saml2pEnabled)
            {
                services.AddIdentityServer(options =>
                {
                    options.Events.RaiseErrorEvents       = true;
                    options.Events.RaiseFailureEvents     = true;
                    options.Events.RaiseSuccessEvents     = true;
                    options.Events.RaiseInformationEvents = true;
                    options.UserInteraction.LoginUrl      = "/sso";
                    options.UserInteraction.LogoutUrl     = "/slo";
                })
                .AddAspNetIdentity <ApplicationUser>()
                .AddInMemoryIdentityResources(SamlConfig.GetIdentityResources())
                .AddInMemoryApiResources(SamlConfig.GetApis())
                .AddInMemoryClients(SamlConfig.GetClients(Configuration))
                .AddSigningCredential(SamlConfig.GetCertificate(Configuration))
                .AddSamlPlugin(options =>
                {
                    options.Licensee   = Configuration.GetValue <string>("SAML2P:LicenseName");
                    options.LicenseKey = Configuration.GetValue <string>("SAML2P:LicenseKey");
                    options.WantAuthenticationRequestsSigned = false;
                })
                .AddInMemoryServiceProviders(SamlConfig.GetServiceProviders(Configuration))
                .Services.Configure <CookieAuthenticationOptions>(IdentityServerConstants.DefaultCookieAuthenticationScheme, cookie => { cookie.Cookie.Name = "idsrv.idp"; });
            }

            // Auth policy
            services.AddAuthorization(config =>
            {
                config.AddPolicy("RequireAdministratorRole",
                                 policy => policy.RequireRole("Administrator"));
                config.AddPolicy("RequireUserRole",
                                 policy => policy.RequireRole("User"));
            });

            // Override OnRedirectToLogin via API
            services.ConfigureApplicationCookie(config =>
            {
                config.Events = new CookieAuthenticationEvents
                {
                    OnRedirectToAccessDenied = context =>
                    {
                        if (context.Request.Path.StartsWithSegments("/api"))
                        {
                            context.Response.StatusCode = (int)System.Net.HttpStatusCode.Forbidden;
                        }
                        else
                        {
                            context.Response.Redirect(context.RedirectUri);
                        }

                        return(Task.CompletedTask);
                    },
                    OnRedirectToLogin = context =>
                    {
                        if (context.Request.Path.StartsWithSegments("/api"))
                        {
                            context.Response.StatusCode = (int)System.Net.HttpStatusCode.Unauthorized;
                        }
                        else
                        {
                            context.Response.Redirect(context.RedirectUri);
                        }
                        return(Task.CompletedTask);
                    }
                };
            });

            // Mvc
            services.AddMvc()
            .AddRazorPagesOptions(options =>
            {
                options.Conventions.AuthorizeAreaFolder("Identity", "/Account/Manage", "RequireAdministratorRole");
            })
            .AddNewtonsoftJson(x => x.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);

            services.AddControllers();
            services.AddRazorPages();
            services.AddServerSideBlazor();
            services.AddDatabaseDeveloperPageExceptionFilter();

            // Localization Options
            services.Configure <RequestLocalizationOptions>(options =>
            {
                var supportedCultures = new[]
                {
                    new CultureInfo("en-US"),
                    new CultureInfo("en-GB"),
                    new CultureInfo("en"),
                    new CultureInfo("fr-FR"),
                    new CultureInfo("fr"),
                    new CultureInfo("it-IT"),
                    new CultureInfo("it"),
                    new CultureInfo("uk-UA"),
                    new CultureInfo("uk"),
                    new CultureInfo("ru-RU"),
                    new CultureInfo("ru-UA"),
                    new CultureInfo("ru"),
                    new CultureInfo("de-DE"),
                    new CultureInfo("de")
                };

                options.DefaultRequestCulture = new RequestCulture("en-US");
                options.SupportedCultures     = supportedCultures;
                options.SupportedUICultures   = supportedCultures;
            });

            // Register the Swagger generator
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "HES API", Version = "v1"
                });
            });
        }
Example #7
0
        private bool ImportServer(ServerVersion version, ServerValidationInfo validationInfo,
                                  string originalServerDirectory, string serverName)
        {
            string serverPath = Path.Combine(App.ServerPath, serverName);

            while (Directory.Exists(serverPath))
            {
                serverPath += "-Copy";
                serverName += "-Copy";
            }

            ServerSettings settings;

            if (new FileInfo(Path.Combine(originalServerDirectory, "server.properties")).Exists)
            {
                var settingsDict = new FileReader().ReadServerSettings(originalServerDirectory);
                settings = new ServerSettings(settingsDict);
            }
            else
            {
                string worldName = validationInfo.Worlds.First().Name;
                settings = new ServerSettings(worldName);
            }

            Server server = new Server(serverName, version, settings, new JavaSettings());

            serverNames.Add(serverName);

            //Create server directory
            DirectoryInfo serverDirectory = Directory.CreateDirectory(serverPath);

            //Add server to Fork
            ServerViewModel viewModel = new ServerViewModel(server);

            viewModel.StartImport();
            Application.Current.Dispatcher.Invoke(() => Entities.Add(viewModel));
            ApplicationManager.Instance.MainViewModel.SelectedEntity = viewModel;


            //Import server files
            Thread copyThread = new Thread(() =>
            {
                FileImporter fileImporter         = new FileImporter();
                fileImporter.CopyProgressChanged += viewModel.CopyProgressChanged;
                fileImporter.DirectoryCopy(originalServerDirectory, serverPath, true, new List <string> {
                    "server.jar"
                });
                Console.WriteLine("Finished copying server files for server " + serverName);
                viewModel.FinishedCopying();
            });

            copyThread.Start();

            //Download server.jar
            Downloader.DownloadJarAsync(viewModel, serverDirectory);

            if (!validationInfo.EulaTxt)
            {
                //Write Eula
                new FileWriter().WriteEula(serverPath);
            }


            return(new DirectoryInfo(serverPath).Exists);
        }
Example #8
0
 public void ConfigureServices(IServiceCollection services)
 {
     services.AddMvc();
     services.AddEntityFrameworkMySql().AddDbContext <HairSalonContext>(options => options.UseMySql(Configuration["ConnectionStrings:DefaultConnection"], ServerVersion.AutoDetect(Configuration["ConnectionStrings:DefaultConnection"])));
 }
Example #9
0
        private void Connect()
        {
            if (UsageTimer == null)
            {
                //Save Timer Resource for licensed usage
                if (!LicenseUtils.HasLicensedFeature(LicenseFeature.Redis))
                {
                    UsageTimer = new Timer(delegate
                    {
                        __requestsPerHour = 0;
                    }, null, TimeSpan.FromMilliseconds(0), TimeSpan.FromHours(1));
                }
            }

            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
            {
                SendTimeout    = SendTimeout,
                ReceiveTimeout = ReceiveTimeout
            };
            try
            {
                if (ConnectTimeout <= 0)
                {
                    socket.Connect(Host, Port);
                }
                else
                {
                    var connectResult = socket.BeginConnect(Host, Port, null, null);
                    connectResult.AsyncWaitHandle.WaitOne(ConnectTimeout, true);
                }

                if (!socket.Connected)
                {
                    socket.Close();
                    socket        = null;
                    DeactivatedAt = DateTime.UtcNow;
                    return;
                }

                Stream networkStream = new NetworkStream(socket);

                if (Ssl)
                {
                    if (Env.IsMono)
                    {
                        //Mono doesn't support EncryptionPolicy
                        sslStream = new SslStream(networkStream,
                                                  leaveInnerStreamOpen: false,
                                                  userCertificateValidationCallback: RedisConfig.CertificateValidationCallback,
                                                  userCertificateSelectionCallback: RedisConfig.CertificateSelectionCallback);
                    }
                    else
                    {
                        var ctor = typeof(SslStream).GetConstructors()
                                   .First(x => x.GetParameters().Length == 5);

                        var policyType  = AssemblyUtils.FindType("System.Net.Security.EncryptionPolicy");
                        var policyValue = Enum.Parse(policyType, "RequireEncryption");

                        sslStream = (SslStream)ctor.Invoke(new[] {
                            networkStream,
                            false,
                            RedisConfig.CertificateValidationCallback,
                            RedisConfig.CertificateSelectionCallback,
                            policyValue,
                        });
                    }

                    sslStream.AuthenticateAsClient(Host);

                    if (!sslStream.IsEncrypted)
                    {
                        throw new Exception("Could not establish an encrypted connection to " + Host);
                    }

                    networkStream = sslStream;
                }

                Bstream = new BufferedStream(networkStream, 16 * 1024);

                if (!string.IsNullOrEmpty(Password))
                {
                    SendUnmanagedExpectSuccess(Commands.Auth, Password.ToUtf8Bytes());
                }

                if (db != 0)
                {
                    SendUnmanagedExpectSuccess(Commands.Select, db.ToUtf8Bytes());
                }

                if (Client != null)
                {
                    SendUnmanagedExpectSuccess(Commands.Client, Commands.SetName, Client.ToUtf8Bytes());
                }

                try
                {
                    if (ServerVersionNumber == 0)
                    {
                        ServerVersionNumber = RedisConfig.AssumeServerVersion.GetValueOrDefault(0);
                        if (ServerVersionNumber <= 0)
                        {
                            var parts   = ServerVersion.Split('.');
                            var version = int.Parse(parts[0]) * 1000;
                            if (parts.Length > 1)
                            {
                                version += int.Parse(parts[1]) * 100;
                            }
                            if (parts.Length > 2)
                            {
                                version += int.Parse(parts[2]);
                            }

                            ServerVersionNumber = version;
                        }
                    }
                }
                catch (Exception)
                {
                    //Twemproxy doesn't support the INFO command so automatically closes the socket
                    //Fallback to ServerVersionNumber=Unknown then try re-connecting
                    ServerVersionNumber = Unknown;
                    Connect();
                    return;
                }

                var ipEndpoint = socket.LocalEndPoint as IPEndPoint;
                clientPort               = ipEndpoint != null ? ipEndpoint.Port : -1;
                lastCommand              = null;
                lastSocketException      = null;
                LastConnectedAtTimestamp = Stopwatch.GetTimestamp();

                OnConnected();

                if (ConnectionFilter != null)
                {
                    ConnectionFilter(this);
                }
            }
            catch (SocketException)
            {
                log.Error(ErrorConnect.Fmt(Host, Port));
                throw;
            }
        }
 public EcpServerVersion(ServerVersion serverVersion)
 {
     this.serverVersion = serverVersion;
 }
Example #11
0
 public DbContextMySQL(IConfiguration config)
     : base(new DbContextOptionsBuilder().UseMySql(config.GetConnectionString("MySQL"), ServerVersion.AutoDetect(config.GetConnectionString("MySQL"))).Options)
 {
 }
Example #12
0
        public static bool Process(
            ServerVersion version,
            string targetConnection,
            string repositoryConnection,
            int snapshotid,
            Database database,
            ServerType serverType,
            out bool isGuestEnabled,
            ref Dictionary <Sql.SqlObjectType, Dictionary <MetricMeasureType, uint> > metricsData
            )
        {
            Debug.Assert(version != ServerVersion.Unsupported);
            Debug.Assert(!string.IsNullOrEmpty(targetConnection));
            Debug.Assert(!string.IsNullOrEmpty(repositoryConnection));
            Debug.Assert(database != null);
            Stopwatch sw = new Stopwatch();

            sw.Start();
            uint numProcessedUsers = 0;

            // Init return.
            bool isOk = true;

            isGuestEnabled = false;
            Program.ImpersonationContext wi = Program.SetLocalImpersonationContext();

            // Process database users.
            List <int> uidList = new List <int>();
            Dictionary <string, KeyValuePair <int, string> > nameDictionary = new Dictionary <string, KeyValuePair <int, string> >();

            using (SqlConnection target = new SqlConnection(targetConnection),
                   repository = new SqlConnection(repositoryConnection))
            {
                try
                {
                    // Open repository and target connections.
                    repository.Open();
                    Program.SetTargetSQLServerImpersonationContext();
                    target.Open();

                    // Use bulk copy object to write to repository.
                    using (SqlBulkCopy bcp = new SqlBulkCopy(repository))
                    {
                        // Set the destination table.
                        bcp.DestinationTableName = DatabasePrincipalDataTable.RepositoryTable;
                        bcp.BulkCopyTimeout      = SQLCommandTimeout.GetSQLCommandTimeoutFromRegistry();
                        // Create the datatable to write to the repository.
                        using (DataTable dataTable = DatabasePrincipalDataTable.Create())
                        {
                            // Create the query.
                            string query = createPrincipalQuery(version, database, serverType);
                            Debug.Assert(!string.IsNullOrEmpty(query));

                            // Query to get the table objects.
                            using (SqlDataReader rdr = Sql.SqlHelper.ExecuteReader(target, null,
                                                                                   CommandType.Text, query, null))
                            {
                                while (rdr.Read())
                                {
                                    // Retrieve information.
                                    SqlString name              = rdr.GetSqlString(FieldPrincipalName);
                                    SqlInt32  uid               = rdr.GetSqlInt32(FieldPrincipalUid);
                                    SqlString type              = rdr.GetSqlString(FieldPrincipalType);
                                    SqlBinary usersid           = rdr.GetSqlBinary(FieldPrincipalUsersid);
                                    SqlString isalias           = rdr.GetSqlString(FieldPrincipalIsalias);
                                    SqlInt32  altuid            = rdr.GetSqlInt32(FieldPrincipalAltuid);
                                    SqlString hasaccess         = rdr.GetSqlString(FieldPrincipalHasaccess);
                                    SqlInt32  owner             = rdr.GetSqlInt32(FieldPrincipalOwner);
                                    SqlString defaultSchemaName = rdr.GetSqlString(FieldPrincipalDefaultschemaname);

                                    // Azure SQL DB does not support contained databases.
                                    SqlBoolean isContained = (serverType == ServerType.AzureSQLDatabase ? true : database.IsContained) &&
                                                             rdr.GetBoolean(FieldIsContainedUser);

                                    SqlString authenticationType = rdr.GetString(FieldAuthenticationType);

                                    // Add to uid collection for later permission processing.
                                    Debug.Assert(!uid.IsNull);
                                    uidList.Add(uid.Value);

                                    // Add to name dictionary for SQL 2000 role member processing & public role processing.
                                    Debug.Assert(!name.IsNull);
                                    Debug.Assert(!type.IsNull);
                                    nameDictionary.Add(name.Value, new KeyValuePair <int, string>(uid.Value, type.Value));

                                    // If guest account set guest enabled flag.
                                    if (uid.Value == Constants.GuestUser && string.Compare(hasaccess.Value, "Y", true) == 0)
                                    {
                                        isGuestEnabled = true;
                                    }

                                    // Update the datatable.
                                    DataRow dr = dataTable.NewRow();
                                    dr[DatabasePrincipalDataTable.ParamSnapshotid]         = snapshotid;
                                    dr[DatabasePrincipalDataTable.ParamOwner]              = owner;
                                    dr[DatabasePrincipalDataTable.ParamDbid]               = database.DbId;
                                    dr[DatabasePrincipalDataTable.ParamUid]                = uid;
                                    dr[DatabasePrincipalDataTable.ParamName]               = name;
                                    dr[DatabasePrincipalDataTable.ParamUsersid]            = usersid;
                                    dr[DatabasePrincipalDataTable.ParamType]               = type;
                                    dr[DatabasePrincipalDataTable.ParamIsalias]            = isalias;
                                    dr[DatabasePrincipalDataTable.ParamAltuid]             = altuid;
                                    dr[DatabasePrincipalDataTable.ParamHasaccess]          = hasaccess;
                                    dr[DatabasePrincipalDataTable.ParamDefaultschemaname]  = defaultSchemaName;
                                    dr[DatabasePrincipalDataTable.ParamHashkey]            = "";
                                    dr[DatabasePrincipalDataTable.ParamIsContained]        = isContained;
                                    dr[DatabasePrincipalDataTable.ParamAuthenticationType] = authenticationType;

                                    dataTable.Rows.Add(dr);

                                    numProcessedUsers++;

                                    // Write to repository if exceeds threshold.
                                    if (dataTable.Rows.Count > Constants.RowBatchSize)
                                    {
                                        try
                                        {
                                            bcp.WriteToServer(dataTable);
                                            dataTable.Clear();
                                        }
                                        catch (SqlException ex)
                                        {
                                            string strMessage = "Writing database principals to Repository ";
                                            logX.loggerX.Error("ERROR - " + strMessage, ex);
                                            throw ex;
                                        }
                                    }
                                }

                                // Write any items still in the data table.
                                if (dataTable.Rows.Count > 0)
                                {
                                    try
                                    {
                                        bcp.WriteToServer(dataTable);
                                        dataTable.Clear();
                                    }
                                    catch (SqlException ex)
                                    {
                                        string strMessage = "Writing database principals to Repository ";
                                        logX.loggerX.Error("ERROR - " + strMessage, ex);
                                        throw ex;
                                    }
                                }
                            }
                        }
                    }
                }
                catch (SqlException ex)
                {
                    string strMessage = "Processing database principals";
                    logX.loggerX.Error("ERROR - " + strMessage, ex);
                    Sql.Database.CreateApplicationActivityEventInRepository(repositoryConnection,
                                                                            snapshotid,
                                                                            Collector.Constants.ActivityType_Error,
                                                                            Collector.Constants.ActivityEvent_Error,
                                                                            strMessage + ex.Message);
                    AppLog.WriteAppEventError(SQLsecureEvent.ExErrExceptionRaised, SQLsecureCat.DlDataLoadCat,
                                              " SQL Server = " + new SqlConnectionStringBuilder(targetConnection).DataSource +
                                              strMessage, ex.Message);


                    isOk = false;
                }
                finally
                {
                    Program.RestoreImpersonationContext(wi);
                }
            }

            // Process role memberships.
            if (isOk)
            {
                if (!processMembers(version, targetConnection, repositoryConnection, snapshotid, database, nameDictionary))
                {
                    logX.loggerX.Error("ERROR - error encountered in processing database role members");
                    isOk = false;
                }
            }

            // Load principal permissions, if its 2005.
            if (isOk)
            {
                if (version != ServerVersion.SQL2000)
                {
                    if (!DatabasePrincipalPermission.Process(targetConnection, repositoryConnection, snapshotid, database, uidList))
                    {
                        logX.loggerX.Error("ERROR - error encountered in processing  database principal permissions");
                        isOk = false;
                    }
                }
            }

            uint oldMetricCount = 0;
            uint oldMetricTime  = 0;

            sw.Stop();
            // See if User is already in Metrics Dictionary
            // ----------------------------------------------
            Dictionary <MetricMeasureType, uint> de;

            if (metricsData.TryGetValue(SqlObjectType.User, out de))
            {
                de.TryGetValue(MetricMeasureType.Count, out oldMetricCount);
                de.TryGetValue(MetricMeasureType.Time, out oldMetricTime);
            }
            else
            {
                de = new Dictionary <MetricMeasureType, uint>();
            }
            de[MetricMeasureType.Count]     = numProcessedUsers + oldMetricCount;
            de[MetricMeasureType.Time]      = (uint)sw.ElapsedMilliseconds + oldMetricTime;
            metricsData[SqlObjectType.User] = de;


            return(isOk);
        }
Example #13
0
        private static string createPrincipalQuery(
            ServerVersion version,
            Database database,
            ServerType serverType
            )
        {
            Debug.Assert(version != ServerVersion.Unsupported);
            Debug.Assert(database != null);

            string query = null;

            //SQLsecure 3.1 (Tsuahr)--On basis of server type creating queries.
            if (serverType != ServerType.AzureSQLDatabase)
            {
                // Create query based on the SQL Server version.
                if (version == ServerVersion.SQL2000)
                {
                    query = @"SELECT 
                            name, 
                            uid = CAST(uid AS int), 
                            type = CASE 
	                                    WHEN islogin = 1 AND isntname = 0 AND issqluser = 1 THEN 'S'
	                                    WHEN islogin = 1 AND isntname = 1 AND isntgroup = 1 THEN 'G'
                                        WHEN islogin = 1 AND isntname = 1 AND isntuser = 1 THEN 'U'
                                        WHEN isapprole = 1 THEN 'A'
                                        ELSE 'R'
                                   END, 
                            usersid = sid, 
                            isalias = CASE WHEN isaliased = 1 THEN 'Y' ELSE 'N' END, 
                            altuid = CAST(altuid AS int), 
                            hasaccess = CASE WHEN hasdbaccess = 1 THEN 'Y' ELSE 'N' END,
                            owner = CAST (NULL AS int),
                            defaultschemaname = CAST (NULL AS NVARCHAR),
                            isContainedUser = CAST (0 as bit),
                            authenticationtype = 'NOT SUPPORTED' "
                            + @"FROM " + Sql.SqlHelper.CreateSafeDatabaseName(database.Name) + @".dbo.sysusers";
                }
                else if (version < ServerVersion.SQL2012)
                {
                    query = @"SELECT
                            dp.name, 
                            uid = dp.principal_id, 
                            ISNULL(dp.type,'R'), 
                            usersid = dp.sid, 
                            isalias = 'N', 
                            altuid = CAST(su.altuid AS int),
                            hasaccess = CASE WHEN su.hasdbaccess = 1 THEN 'Y' ELSE 'N' END,
                            owner = dp.owning_principal_id, 
                            defaultschemaname = dp.default_schema_name, 
                            isContainedUser = cast(0 as bit) ,"
                            + "authenticationtype= 'NOT SUPPORTED' "
                            + @"FROM " + Sql.SqlHelper.CreateSafeDatabaseName(database.Name) + @".sys.database_principals AS dp JOIN "
                            + Sql.SqlHelper.CreateSafeDatabaseName(database.Name) + @".sys.sysusers AS su ON (dp.principal_id = su.uid) "
                            + @"UNION ALL SELECT
                            name, 
                            uid = CAST(uid AS int), 
                            type = CASE 
	                                    WHEN islogin = 1 AND isntname = 0 AND issqluser = 1 THEN 'S'
	                                    WHEN islogin = 1 AND isntname = 1 AND isntgroup = 1 THEN 'G'
                                        WHEN islogin = 1 AND isntname = 1 AND isntuser = 1 THEN 'U'
                                        WHEN isapprole = 1 THEN 'A'
                                        ELSE 'R'
                                   END, 
                            usersid = sid, 
                            isalias = CASE WHEN isaliased = 1 THEN 'Y' ELSE 'N' END, 
                            altuid = CAST(altuid AS int), 
                            hasaccess = CASE WHEN hasdbaccess = 1 THEN 'Y' ELSE 'N' END,
                            owner = CAST (NULL AS int),
                            defaultschemaname = CAST (NULL AS NVARCHAR), "
                            + "isContainedUser = cast(0 as bit),"
                            + "authenticationtype= 'NOT SUPPORTED' "
                            + @"FROM " + Sql.SqlHelper.CreateSafeDatabaseName(database.Name) + @".sys.sysusers "
                            + @"WHERE isaliased = 1";
                }
                else if (version >= ServerVersion.SQL2012)
                {
                    query = @"SELECT
                            dp.name, 
                            uid = dp.principal_id, 
                            ISNULL(dp.type,'R'), 
                            usersid = dp.sid, 
                            isalias = 'N', 
                            altuid = CAST(su.altuid AS int),
                            hasaccess = CASE WHEN su.hasdbaccess = 1 THEN 'Y' ELSE 'N' END,
                            owner = dp.owning_principal_id, 
                            defaultschemaname = dp.default_schema_name, 
                            isContainedUser = cast(( case authentication_type
                               when 2 then 1
                               when 3 then  isnull((select top 1 0 from " + Sql.SqlHelper.CreateSafeDatabaseName(database.Name) + @".sys.database_principals cdp
							    where cdp.principal_id=dp.principal_id and cdp.sid  in (SELECT sid FROM "                             + Sql.SqlHelper.CreateSafeDatabaseName(database.Name) + @".sys.server_principals) 
								and    type in ( 'U', 'S', 'G' )    
								), 1)
								else 0
                             end ) as bit), " +
                            " authenticationtype = authentication_type_desc "
                            + @"FROM " + Sql.SqlHelper.CreateSafeDatabaseName(database.Name) + @".sys.database_principals AS dp JOIN "
                            + Sql.SqlHelper.CreateSafeDatabaseName(database.Name) + @".sys.sysusers AS su ON (dp.principal_id = su.uid) "
                            + @"UNION ALL SELECT
                            name, 
                            uid = CAST(uid AS int), 
                            type = CASE 
	                                    WHEN islogin = 1 AND isntname = 0 AND issqluser = 1 THEN 'S'
	                                    WHEN islogin = 1 AND isntname = 1 AND isntgroup = 1 THEN 'G'
                                        WHEN islogin = 1 AND isntname = 1 AND isntuser = 1 THEN 'U'
                                        WHEN isapprole = 1 THEN 'A'
                                        ELSE 'R'
                                   END, 
                            usersid = sid, 
                            isalias = CASE WHEN isaliased = 1 THEN 'Y' ELSE 'N' END, 
                            altuid = CAST(altuid AS int), 
                            hasaccess = CASE WHEN hasdbaccess = 1 THEN 'Y' ELSE 'N' END,
                            owner = CAST (NULL AS int),
                            defaultschemaname = CAST (NULL AS NVARCHAR), "
                            + "isContainedUser = cast(0 as bit) ,"
                            + "authenticationtype= 'NOT SUPPORTED' "
                            + @"FROM " + Sql.SqlHelper.CreateSafeDatabaseName(database.Name) + @".sys.sysusers "
                            + @"WHERE isaliased = 1";
                }
                else
                {
                    query = @"SELECT
                            dp.name, 
                            uid = dp.principal_id, 
                            ISNULL(dp.type,'R'), 
                            usersid = dp.sid, 
                            isalias = 'N', 
                            altuid = CAST(su.altuid AS int),
                            hasaccess = CASE WHEN su.hasdbaccess = 1 THEN 'Y' ELSE 'N' END,
                            owner = dp.owning_principal_id, 
                            defaultschemaname = dp.default_schema_name, 
                            isContainedUser = cast(( case authentication_type
                               when 2 then 1
                               when 3 then  isnull((select top 1 0 from " + Sql.SqlHelper.CreateSafeDatabaseName(database.Name) + @".sys.database_principals cdp
							    where cdp.principal_id=dp.principal_id and cdp.sid  in (SELECT sid FROM "                             + Sql.SqlHelper.CreateSafeDatabaseName(database.Name) + @".sys.server_principals) 
								and    type in ( 'U', 'S', 'G' )    
								), 1)
								else 0
                             end ) as bit), " +
                            " authenticationtype = authentication_type_desc "
                            + @"FROM " + Sql.SqlHelper.CreateSafeDatabaseName(database.Name) + @".sys.database_principals AS dp JOIN "
                            + Sql.SqlHelper.CreateSafeDatabaseName(database.Name) + @".sys.sysusers AS su ON (dp.principal_id = su.uid) "
                            + @"UNION ALL SELECT
                            name, 
                            uid = CAST(uid AS int), 
                            type = CASE 
	                                    WHEN islogin = 1 AND isntname = 0 AND issqluser = 1 THEN 'S'
	                                    WHEN islogin = 1 AND isntname = 1 AND isntgroup = 1 THEN 'G'
                                        WHEN islogin = 1 AND isntname = 1 AND isntuser = 1 THEN 'U'
                                        WHEN isapprole = 1 THEN 'A'
                                        ELSE 'R'
                                   END, 
                            usersid = sid, 
                            isalias = CASE WHEN isaliased = 1 THEN 'Y' ELSE 'N' END, 
                            altuid = CAST(altuid AS int), 
                            hasaccess = CASE WHEN hasdbaccess = 1 THEN 'Y' ELSE 'N' END,
                            owner = CAST (NULL AS int),
                            defaultschemaname = CAST (NULL AS NVARCHAR), "
                            + "isContainedUser = cast(0 as bit) ,"
                            + "authenticationtype= 'NOT SUPPORTED' "
                            + @"FROM " + Sql.SqlHelper.CreateSafeDatabaseName(database.Name) + @".sys.sysusers "
                            + @"WHERE isaliased = 1";
                }
            }
            else
            {
                //SQLsecure 3.1 (Tushar)--Query for Azure DB.
                query = @"SELECT
                            dp.name, 
                            uid = dp.principal_id, 
                            ISNULL(dp.type,'R'), 
                            usersid = dp.sid, 
                            isalias = 'N', 
                            altuid = CAST(su.altuid AS int),
                            hasaccess = CASE WHEN su.hasdbaccess = 1 THEN 'Y' ELSE 'N' END,
                            owner = dp.owning_principal_id, 
                            defaultschemaname = dp.default_schema_name, 
                            isContainedUser = cast((case authentication_type
                               when 2 then 1
                               when 4 then IIF(type = 'E' or type = 'X',"
                        + ((database.Name == Constants.MASTER_DB_NAME) ? 0 : 1)
                        + @", 0) else 0
                               end) as bit),
                              authenticationtype = authentication_type_desc "
                        + @"FROM " + Sql.SqlHelper.CreateSafeDatabaseName(database.Name) + @".sys.database_principals AS dp JOIN "
                        + Sql.SqlHelper.CreateSafeDatabaseName(database.Name) + @".sys.sysusers AS su ON (dp.principal_id = su.uid) "
                        + @"UNION ALL SELECT
                            name, 
                            uid = CAST(uid AS int), 
                            type = CASE 
	                                    WHEN islogin = 1 AND isntname = 0 AND issqluser = 1 THEN 'S'
	                                    WHEN islogin = 1 AND isntname = 1 AND isntgroup = 1 THEN 'G'
                                        WHEN islogin = 1 AND isntname = 1 AND isntuser = 1 THEN 'U'
                                        WHEN isapprole = 1 THEN 'A'
                                        ELSE 'R'
                                   END, 
                            usersid = sid, 
                            isalias = CASE WHEN isaliased = 1 THEN 'Y' ELSE 'N' END, 
                            altuid = CAST(altuid AS int), 
                            hasaccess = CASE WHEN hasdbaccess = 1 THEN 'Y' ELSE 'N' END,
                            owner = CAST (NULL AS int),
                            defaultschemaname = CAST (NULL AS NVARCHAR), "
                        + "isContainedUser = cast(0 as bit) ,"
                        + "authenticationtype= 'NOT SUPPORTED' "
                        + @"FROM " + Sql.SqlHelper.CreateSafeDatabaseName(database.Name) + @".sys.sysusers "
                        + @"WHERE isaliased = 1";
            }
            return(query);
        }
Example #14
0
        private static bool processMembers(
            ServerVersion version,
            string targetConnection,
            string repositoryConnection,
            int snapshotid,
            Database database,
            Dictionary <string, KeyValuePair <int, string> > nameDictionary
            )
        {
            Debug.Assert(version != ServerVersion.Unsupported);
            Debug.Assert(!string.IsNullOrEmpty(targetConnection));
            Debug.Assert(!string.IsNullOrEmpty(repositoryConnection));
            Debug.Assert(database != null);
            Debug.Assert(nameDictionary != null);
            Program.ImpersonationContext wi = Program.SetLocalImpersonationContext();
            // Process database role members.
            bool isOk = true;

            using (SqlConnection target = new SqlConnection(targetConnection),
                   repository = new SqlConnection(repositoryConnection))
            {
                try
                {
                    // Open repository and target connections.
                    repository.Open();
                    Program.SetTargetSQLServerImpersonationContext();
                    target.Open();


                    // Use bulk copy object to write to repository.
                    using (SqlBulkCopy bcp = new SqlBulkCopy(repository))
                    {
                        // Set the destination table.
                        bcp.DestinationTableName = DatabaseRoleMemberDataTable.RepositoryTable;
                        bcp.BulkCopyTimeout      = SQLCommandTimeout.GetSQLCommandTimeoutFromRegistry();
                        // Create the datatable to write to the repository.
                        using (DataTable dataTable = DatabaseRoleMemberDataTable.Create())
                        {
                            // Create the query.
                            string query = createRoleMemberQuery(version, database);
                            Debug.Assert(!string.IsNullOrEmpty(query));

                            // Query to get the role member objects.
                            // Note : this query does not return public role members, so we
                            // have to do special processing for public role members.  See below.
                            using (SqlDataReader rdr = Sql.SqlHelper.ExecuteReader(target, null,
                                                                                   CommandType.Text, query, null))
                            {
                                while (rdr.Read())
                                {
                                    // Retrieve and setup the table row.
                                    if (version == ServerVersion.SQL2000)
                                    {
                                        KeyValuePair <int, string> role, member;
                                        if (nameDictionary.TryGetValue((string)rdr[0], out role) &&
                                            nameDictionary.TryGetValue((string)rdr[1], out member))
                                        {
                                            DataRow dr = dataTable.NewRow();
                                            dr[DatabaseRoleMemberDataTable.ParamDbid]          = database.DbId;
                                            dr[DatabaseRoleMemberDataTable.ParamGroupuid]      = role.Key;
                                            dr[DatabaseRoleMemberDataTable.ParamRolememberuid] = member.Key;
                                            dr[DatabaseRoleMemberDataTable.ParamSnapshotid]    = snapshotid;
                                            dr[DatabaseRoleMemberDataTable.ParamHashkey]       = "";
                                            dataTable.Rows.Add(dr);
                                        }
                                        else
                                        {
                                            logX.loggerX.Warn("WARN - uid not found for db role member", (string)rdr[0], ", or ", (string)rdr[1]);
                                        }
                                    }
                                    else
                                    {
                                        DataRow dr = dataTable.NewRow();
                                        dr[DatabaseRoleMemberDataTable.ParamDbid]          = database.DbId;
                                        dr[DatabaseRoleMemberDataTable.ParamGroupuid]      = rdr.GetSqlInt32(0);
                                        dr[DatabaseRoleMemberDataTable.ParamRolememberuid] = rdr.GetSqlInt32(1);
                                        dr[DatabaseRoleMemberDataTable.ParamSnapshotid]    = snapshotid;
                                        dr[DatabaseRoleMemberDataTable.ParamHashkey]       = "";
                                        dataTable.Rows.Add(dr);
                                    }

                                    // Write to repository if exceeds threshold.
                                    if (dataTable.Rows.Count > Constants.RowBatchSize)
                                    {
                                        try
                                        {
                                            bcp.WriteToServer(dataTable);
                                            dataTable.Clear();
                                        }
                                        catch (SqlException ex)
                                        {
                                            logX.loggerX.Error("ERROR - writing database role members to Repository, ", ex);
                                            isOk = false;
                                        }
                                    }
                                }

                                // Write any items still in the data table.
                                if (dataTable.Rows.Count > 0)
                                {
                                    try
                                    {
                                        bcp.WriteToServer(dataTable);
                                        dataTable.Clear();
                                    }
                                    catch (SqlException ex)
                                    {
                                        logX.loggerX.Error("ERROR - writing database role members to Repository, ", ex);
                                        isOk = false;
                                    }
                                }
                            }

                            // Now write all SQL user, windows user and windows group as a
                            // member of the public role.   Note: the queries used above
                            // do not return any public role members.   So we have to do
                            // special processing here.
                            const int PublicRoleUid = 0;
                            dataTable.Clear();
                            foreach (KeyValuePair <int, string> dbprincipal in nameDictionary.Values)
                            {
                                // Add row to the data table, if a user.
                                if (isUserPrincipal(dbprincipal.Value))
                                {
                                    DataRow dr = dataTable.NewRow();
                                    dr[DatabaseRoleMemberDataTable.ParamDbid]          = database.DbId;
                                    dr[DatabaseRoleMemberDataTable.ParamGroupuid]      = PublicRoleUid;
                                    dr[DatabaseRoleMemberDataTable.ParamRolememberuid] = dbprincipal.Key;
                                    dr[DatabaseRoleMemberDataTable.ParamSnapshotid]    = snapshotid;
                                    dr[DatabaseRoleMemberDataTable.ParamHashkey]       = "";
                                    dataTable.Rows.Add(dr);
                                }

                                // Write to repository if exceeds threshold.
                                if (dataTable.Rows.Count > Constants.RowBatchSize)
                                {
                                    try
                                    {
                                        bcp.WriteToServer(dataTable);
                                        dataTable.Clear();
                                    }
                                    catch (SqlException ex)
                                    {
                                        logX.loggerX.Error("ERROR - writing database role members to Repository, ", ex);
                                        isOk = false;
                                    }
                                }
                            }

                            // Write any items still in the data table.
                            if (dataTable.Rows.Count > 0)
                            {
                                try
                                {
                                    bcp.WriteToServer(dataTable);
                                    dataTable.Clear();
                                }
                                catch (SqlException ex)
                                {
                                    logX.loggerX.Error("ERROR - writing database role members to Repository, ", ex);
                                    isOk = false;
                                }
                            }
                        }
                    }
                }
                catch (SqlException ex)
                {
                    logX.loggerX.Error("ERROR - exception encountered when processing database role members, ", ex);
                    isOk = false;
                }
                finally
                {
                    Program.RestoreImpersonationContext(wi);
                }
            }

            return(isOk);
        }
Example #15
0
    public void BeforeCheck(Action <bool> AsynResult, Action OnError)
    {
        //阻塞,直到超时问题解决
        var checkTimeout = new CheckTimeout();

        checkTimeout.AsynIsNetworkTimeout((success) =>
        {
            if (success)
            {
                DownloadMgr.Instance.AsynDownLoadText(SystemConfig.GetCfgInfoUrl(SystemConfig.VERSION_URL_KEY),
                                                      (serverVersion) =>
                {
                    if (File.Exists(SystemConfig.ServerVersionPath))    //增加本地版本检查
                    {
                        serverVersion = Utils.LoadFile(SystemConfig.ServerVersionPath);
                        LoggerHelper.Info("serverVersion exist:\n" + serverVersion);
                    }
                    ServerVersion = GetVersionInXML(serverVersion);
                    if (ServerVersion.IsDefault())
                    {
                        if (OnError != null)
                        {
                            OnError();
                        }
                        return;
                    }

                    /*
                     *  Mogo.Util.LoggerHelper.Debug("服务器程序版本: " + ServerVersion.ProgramVersionInfo);
                     *  Mogo.Util.LoggerHelper.Debug("服务器资源版本: " + ServerVersion.ResouceVersionInfo);
                     *  Mogo.Util.LoggerHelper.Debug("服务器包列表: " + ServerVersion.PackageList);
                     *  Mogo.Util.LoggerHelper.Debug("服务器包地址: " + ServerVersion.PackageUrl);
                     *  Mogo.Util.LoggerHelper.Debug("服务器Apk地址: " + ServerVersion.ApkUrl);
                     *  Mogo.Util.LoggerHelper.Debug("服务器md5地址: " + ServerVersion.PackageMd5List);
                     */
                    var compareProgramVersion  = ServerVersion.ProgramVersionInfo.Compare(LocalVersion.ProgramVersionInfo) > 0;   //服务程序版本号比本地版本号大
                    var compareResourceVersion = ServerVersion.ResouceVersionInfo.Compare(LocalVersion.ResouceVersionInfo) > 0;   //服务器资源版本比本地高
                    AsynResult(compareProgramVersion || compareResourceVersion);
                },
                                                      OnError);
            }
            else
            {
                if (OnError != null)
                {
                    OnError();
                }
            }
        });
        //CheckNetworkTimeout();
        //var serverVersion = DownloadMgr.Instance.DownLoadText(SystemConfig.GetCfgInfoUrl(SystemConfig.VERSION_URL_KEY));
        //{
        //    ServerVersion = GetVersionInXML(serverVersion);
        //    Mogo.Util.LoggerHelper.Debug("服务器程序版本: " + ServerVersion.ProgramVersionInfo);
        //    Mogo.Util.LoggerHelper.Debug("服务器资源版本: " + ServerVersion.ResouceVersionInfo);
        //    Mogo.Util.LoggerHelper.Debug("服务器包列表: " + ServerVersion.PackageList);
        //    Mogo.Util.LoggerHelper.Debug("服务器包地址: " + ServerVersion.PackageUrl);
        //    Mogo.Util.LoggerHelper.Debug("服务器Apk地址: " + ServerVersion.ApkUrl);
        //    Mogo.Util.LoggerHelper.Debug("服务器md5地址: " + ServerVersion.PackageMd5List);
        //}
        //var compareProgramVersion = ServerVersion.ProgramVersionInfo.Compare(LocalVersion.ProgramVersionInfo) > 0;//服务程序版本号比本地版本号大
        //var compareResourceVersion = ServerVersion.ResouceVersionInfo.Compare(LocalVersion.ResouceVersionInfo) > 0;//服务器资源版本比本地高
        //return compareProgramVersion || compareResourceVersion;
    }
Example #16
0
        protected override void OnConfiguring(DbContextOptionsBuilder options)
        {
            var connStr     = Configuration.GetSection("dbConfig")["connectionString"];
            var efcoreBuild =
                Configuration.GetSection("dbConfig")["efcoreBuild"] != null; // Used for building migrations

            options.UseMySql(connStr,
                             efcoreBuild ? MySqlServerVersion.LatestSupportedServerVersion : ServerVersion.AutoDetect(connStr));
        }
 /// <summary>
 /// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider"
 /// /> and <see cref="ignoreCase" />
 /// </summary>
 /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param>
 /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param>
 /// <param name="formatProvider">not used by this TypeConverter.</param>
 /// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param>
 /// <returns>
 /// an instance of <see cref="ServerVersion" />, or <c>null</c> if there is no suitable conversion.
 /// </returns>
 public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ServerVersion.CreateFrom(sourceValue);
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            //this helps to inject the connection string value from appsettings.json
            string mySqlConnectionStr = Configuration.GetConnectionString("DefaultConnection");

            services.AddDbContextPool <CommerceBankAppContext>(options =>
                                                               options.UseMySql(mySqlConnectionStr, ServerVersion.AutoDetect(mySqlConnectionStr)));
            //inject the service in this method to enable the api to interact with records from the Data Access Layer(DAL)
            services.AddScoped(typeof(IUserService), typeof(UserService));
            //meaning that where ever we have Iuserservice we indirectly have access to the Userservice(concrete) class methods
            services.AddScoped(typeof(IPersonService), typeof(PersonService));
            services.AddScoped(typeof(IAccountTypeService), typeof(AccountTypeService));
            services.AddScoped(typeof(IBankActivityService), typeof(BankActivityService));
            services.AddScoped(typeof(IAccountService), typeof(AccountService));
            services.AddScoped(typeof(ILastTransactionService), typeof(LastTransactionService));
            services.AddScoped(typeof(IMailService), typeof(MailService));
            services.AddScoped(typeof(IRepositoryService <>), typeof(RepositoryService <>));
            //this is for api documentation
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "Commerce_Bank API", Version = "v1"
                });
            });
            //inject email service
            services.Configure <MailSettings>(Configuration.GetSection("MailSettings"));
        }
 protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
 {
     optionsBuilder.UseMySql(
         "server=127.0.0.1;database=vaultdb;uid=root;pwd=1907genclik;", ServerVersion.AutoDetect("server=127.0.0.1;database=vaultdb;uid=root;pwd=1907genclik;"));
 }
Example #20
0
        public async Task ConnectAsync(ConnectionSettings cs, IOBehavior ioBehavior, CancellationToken cancellationToken)
        {
            lock (m_lock)
            {
                VerifyState(State.Created);
                m_state = State.Connecting;
            }
            var connected = false;

            if (cs.ConnectionType == ConnectionType.Tcp)
            {
                connected = await OpenTcpSocketAsync(cs, ioBehavior, cancellationToken).ConfigureAwait(false);
            }
            else if (cs.ConnectionType == ConnectionType.Unix)
            {
                connected = await OpenUnixSocketAsync(cs, ioBehavior, cancellationToken).ConfigureAwait(false);
            }
            if (!connected)
            {
                lock (m_lock)
                    m_state = State.Failed;
                throw new MySqlException("Unable to connect to any of the specified MySQL hosts.");
            }

            var byteHandler = new SocketByteHandler(m_socket);

            m_payloadHandler = new StandardPayloadHandler(byteHandler);

            var payload = await ReceiveAsync(ioBehavior, cancellationToken).ConfigureAwait(false);

            var reader           = new ByteArrayReader(payload.ArraySegment.Array, payload.ArraySegment.Offset, payload.ArraySegment.Count);
            var initialHandshake = new InitialHandshakePacket(reader);

            // if PluginAuth is supported, then use the specified auth plugin; else, fall back to protocol capabilities to determine the auth type to use
            string authPluginName;

            if ((initialHandshake.ProtocolCapabilities & ProtocolCapabilities.PluginAuth) != 0)
            {
                authPluginName = initialHandshake.AuthPluginName;
            }
            else
            {
                authPluginName = (initialHandshake.ProtocolCapabilities & ProtocolCapabilities.SecureConnection) == 0 ? "mysql_old_password" : "mysql_native_password";
            }
            if (authPluginName != "mysql_native_password" && authPluginName != "sha256_password")
            {
                throw new NotSupportedException("Authentication method '{0}' is not supported.".FormatInvariant(initialHandshake.AuthPluginName));
            }

            ServerVersion    = new ServerVersion(Encoding.ASCII.GetString(initialHandshake.ServerVersion));
            ConnectionId     = initialHandshake.ConnectionId;
            AuthPluginData   = initialHandshake.AuthPluginData;
            m_useCompression = cs.UseCompression && (initialHandshake.ProtocolCapabilities & ProtocolCapabilities.Compress) != 0;

            var serverSupportsSsl = (initialHandshake.ProtocolCapabilities & ProtocolCapabilities.Ssl) != 0;

            if (cs.SslMode != MySqlSslMode.None && (cs.SslMode != MySqlSslMode.Preferred || serverSupportsSsl))
            {
                if (!serverSupportsSsl)
                {
                    throw new MySqlException("Server does not support SSL");
                }
                await InitSslAsync(initialHandshake.ProtocolCapabilities, cs, ioBehavior, cancellationToken).ConfigureAwait(false);
            }

            m_supportsConnectionAttributes = (initialHandshake.ProtocolCapabilities & ProtocolCapabilities.ConnectionAttributes) != 0;
            if (m_supportsConnectionAttributes && s_connectionAttributes == null)
            {
                s_connectionAttributes = CreateConnectionAttributes();
            }

            m_supportsDeprecateEof = (initialHandshake.ProtocolCapabilities & ProtocolCapabilities.DeprecateEof) != 0;

            var response = HandshakeResponse41Packet.Create(initialHandshake, cs, m_useCompression, m_supportsConnectionAttributes ? s_connectionAttributes : null);

            payload = new PayloadData(new ArraySegment <byte>(response));
            await SendReplyAsync(payload, ioBehavior, cancellationToken).ConfigureAwait(false);

            payload = await ReceiveReplyAsync(ioBehavior, cancellationToken).ConfigureAwait(false);

            // if server doesn't support the authentication fast path, it will send a new challenge
            if (payload.HeaderByte == AuthenticationMethodSwitchRequestPayload.Signature)
            {
                await SwitchAuthenticationAsync(cs, payload, ioBehavior, cancellationToken).ConfigureAwait(false);

                payload = await ReceiveReplyAsync(ioBehavior, cancellationToken).ConfigureAwait(false);
            }

            OkPayload.Create(payload);

            if (m_useCompression)
            {
                m_payloadHandler = new CompressedPayloadHandler(m_payloadHandler.ByteHandler);
            }
        }
Example #21
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <CookiePolicyOptions>(options =>
            {
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;

            byte[] encKey           = Encoding.UTF8.GetBytes(Configuration.GetSection("Schlussel").Value);
            byte[] encryptedString  = Convert.FromBase64String(Configuration.GetSection("ConnectionStrings")["DefaultConnection"]);
            string decryptedString  = Configuration.GetSection("ConnectionStrings")["DefaultConnection2"];
            string connectionString = Criptografia.Decriptografar(encryptedString, encKey);

            services.AddDbContext <ApplicationDbContext>(options => options.UseMySql(decryptedString, ServerVersion.AutoDetect(decryptedString)), ServiceLifetime.Scoped);
            services.AddIdentity <UsuarioADE, IdentityRole>()
            .AddErrorDescriber <PortugueseIdentityErrorDescriber>()
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders();

            services.Configure <IdentityOptions>(options =>
            {
                options.Password.RequireDigit           = false;
                options.Password.RequireLowercase       = false;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase       = false;
                options.Password.RequiredLength         = 6;
                options.Password.RequiredUniqueChars    = 0;

                options.Lockout.DefaultLockoutTimeSpan  = TimeSpan.FromMinutes(5);
                options.Lockout.MaxFailedAccessAttempts = 20;
                options.Lockout.AllowedForNewUsers      = false;

                options.User.AllowedUserNameCharacters =
                    "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
                options.User.RequireUniqueEmail = false;
            });

            services.Configure <RazorViewEngineOptions>(o =>
            {
                o.ViewLocationFormats.Clear();
                o.ViewLocationFormats.Add("/Controllers/{1}/Views/{0}" + RazorViewEngine.ViewExtension);
                o.ViewLocationFormats.Add("/Controllers/Shared/Views/{0}" + RazorViewEngine.ViewExtension);
                o.AreaViewLocationFormats.Clear();
                o.AreaViewLocationFormats.Add("/Areas/{2}/Views/{1}/{0}.cshtml");
                o.AreaViewLocationFormats.Add("/Areas/{2}/Views/{1}/{0}.cshtml");
                o.AreaViewLocationFormats.Add("/Areas/{2}/Pages/{1}/{0}.cshtml");
                o.AreaViewLocationFormats.Add("/Areas/{2}/Views/Shared/{0}.cshtml");
                o.AreaViewLocationFormats.Add("/Areas/{2}/Views/Shared/{1}/{0}.cshtml");
                o.AreaViewLocationFormats.Add("/Areas/Shared/{0}.cshtml");
            });

            services.AddScoped(typeof(IRepositorioBase <>), typeof(RepositorioBase <>));
            services.AddTransient <DbContext, ApplicationDbContext>();
            services.AddScoped <RoleServices>();
            services.AddScoped <AuthMessageSender>();

            //services.AddAuthentication().AddGoogle(googleOptions =>
            //{
            //    googleOptions.ClientId = Configuration.GetSection("Secure")["Authentication:Google:ClientId"];
            //    googleOptions.ClientSecret = Configuration.GetSection("Secure")["Authentication:Google:ClientSecret"];
            //});

            //services.AddAuthentication().AddFacebook(facebookOptions =>
            //{
            //    facebookOptions.AppId = Configuration.GetSection("Secure")["Authentication:Facebook:AppId"];
            //    facebookOptions.AppSecret = Configuration.GetSection("Secure")["Authentication:Facebook:AppSecret"];
            //});

            services.AddAuthentication(o =>
            {
                o.DefaultSignInScheme       = CookieAuthenticationDefaults.AuthenticationScheme;
                o.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            }).AddCookie();

            services.AddMemoryCache();
            services.AddSession(options =>
            {
                options.Cookie.Name        = ".ADE";
                options.IdleTimeout        = TimeSpan.FromSeconds(10);
                options.Cookie.IsEssential = true;
            });
            services.AddMvc(options => { options.MaxModelValidationErrors = 50; options.EnableEndpointRouting = false; options.ModelBindingMessageProvider.SetValueMustNotBeNullAccessor((_) => "Algum campo obrigatorio estava nulo."); })
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2).AddMvcOptions(MvcOptions => MvcOptions.EnableEndpointRouting = false).AddSessionStateTempDataProvider()
            .AddRazorPagesOptions(options =>
            {
                //options.AllowAreas = true;
                options.Conventions.AuthorizeAreaFolder("Administracao", "/");
            });

            services.AddControllersWithViews();

            services.AddRazorPages().AddNewtonsoftJson();
            services.AddProgressiveWebApp(new PwaOptions()
            {
                RegisterServiceWorker = false
            });

            services.Configure <AuthMessageSenderOptions>(Configuration);
        }
        // Token: 0x060055FB RID: 22011 RVA: 0x00136068 File Offset: 0x00134268
        private static void AdminDisplayVersionSetter(object value, IPropertyBag propertyBag)
        {
            ServerVersion serverVersion = (ServerVersion)value;

            propertyBag[MailboxTransportServerADSchema.SerialNumber] = serverVersion.ToString(true);
        }
 /// <summary>
 ///     Returns true when connected site is at least the provided SharePoint version.
 /// </summary>
 /// <param name="context"></param>
 /// <param name="version"></param>
 /// <returns></returns>
 public static bool IsMinimalServerVersion(this ClientRuntimeContext context, ServerVersion version)
 {
     if (context.ServerSchemaVersion.Major < (int) version)
         return false;
     return true;
 }
Example #24
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Read environment Values
            string dbServer   = Configuration.GetValue <string>("DB_SERVER");
            string dbUser     = Configuration.GetValue <string>("DB_USER");
            string dbPassword = Configuration.GetValue <string>("DB_PASSWORD");

            string secretKey = Configuration.GetValue <string>("SECRET_KEY");

            string messagingBrokers = Configuration.GetValue <string>("MESSAGING_BROKERS");


            // Connection string from appsettings
            string connectionString = Configuration.GetConnectionString("AppDB");

            string dbConnectionString = connectionString.Replace("DB_SERVER", dbServer)
                                        .Replace("DB_USER", dbUser)
                                        .Replace("DB_PASSWORD", dbPassword);


            // DB Contexts
            // if env variables not set use connection string as it is
            services.AddDbContext <AppDbContext>(options =>
                                                 options.UseMySql(dbConnectionString, ServerVersion.AutoDetect(String.IsNullOrEmpty(dbServer) ? connectionString : dbConnectionString)));

            // Register the ConfigurationBuilder instance of AuthSettings
            var authSettings = Configuration.GetSection(nameof(AuthSettings));

            services.Configure <AuthSettings>(authSettings);


            var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretKey + "" == "" ? authSettings[nameof(AuthSettings.SecretKey)] : secretKey));

            // jwt wire up
            // Get options from app settings
            var jwtAppSettingOptions = Configuration.GetSection("JwtIssuerOptions");

            var tokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidIssuer    = jwtAppSettingOptions["Issuer"],

                ValidateAudience = true,
                ValidAudience    = jwtAppSettingOptions["Audience"],

                ValidateIssuerSigningKey = true,
                IssuerSigningKey         = signingKey,

                RequireExpirationTime = false,
                ValidateLifetime      = true,
                ClockSkew             = TimeSpan.Zero
            };

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(configureOptions =>
            {
                configureOptions.ClaimsIssuer = jwtAppSettingOptions["Issuer"];
                configureOptions.TokenValidationParameters = tokenValidationParameters;
                configureOptions.SaveToken = true;

                configureOptions.Events = new JwtBearerEvents
                {
                    OnAuthenticationFailed = context =>
                    {
                        if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
                        {
                            context.Response.Headers.Add("X-Token-Expired", "true");
                        }
                        return(Task.CompletedTask);
                    }
                };
            });


            services.AddControllers()
            .AddFluentValidation(fv => fv.RegisterValidatorsFromAssemblyContaining <BaseCommand>());

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "App.API", Version = "v1"
                });
            });


            //Kafka
            var messagingConfigs = Configuration.GetSection("Messaging");

            var clientConfig = new ClientConfig
            {
                BootstrapServers = String.IsNullOrEmpty(messagingBrokers) ? messagingConfigs["BootstrapServers"] : messagingBrokers
            };

            var consumerConfig = new ConsumerConfig(clientConfig)
            {
                GroupId              = "MessagesApp",
                EnableAutoCommit     = true,
                AutoOffsetReset      = AutoOffsetReset.Earliest,
                StatisticsIntervalMs = 5000,
                SessionTimeoutMs     = 6000
            };


            services.AddSingleton(consumerConfig);

            services.AddScoped(typeof(IMessageHandler <string, NotificationMessageDTO>), typeof(NotificationMessageHandler));
            services.AddSingleton(typeof(IMessageConsumer <,>), typeof(MessageConsumer <,>));
            services.AddHostedService <NotificationMessageConsumer>();

            services.AddTransient <IMachineDateTime, MachineDateTime>();
            services.AddTransient <IMachineLogger, MachineLogger>();

            services.AddTransient <IFileUtils, FileUtils>();
            services.AddTransient <IStringUtils, StringUtils>();
            services.AddTransient <IEmailService, EmailService>();

            //Add Mediator
            services.AddTransient(typeof(IPipelineBehavior <,>), typeof(RequestPreProcessorBehavior <,>));
            services.AddTransient(typeof(IPipelineBehavior <,>), typeof(RequestPerformanceBehaviour <,>));
            services.AddTransient(typeof(IPipelineBehavior <,>), typeof(RequestValidationBehaviour <,>));
            services.AddMediatR(typeof(SeedDBCommand).GetTypeInfo().Assembly);


            //CORS
            services.ConfigureCors(Configuration);
        }
Example #25
0
 public ServerInfo()
 {
     serverVersion = new ServerVersion();
 }
Example #26
0
 protected override void OnConfiguring(DbContextOptionsBuilder options)
 {
     options.UseMySql(ConnectionString, ServerVersion.FromString("8.0.20-mysql"), options => options.EnableRetryOnFailure().CharSet(CharSet.Utf8Mb4));
 }