public static async Task FetchServerDatabasesAsync(ServerRecord server, IAsyncDocumentSession session) { var client = await ServerHelpers.CreateAsyncServerClient(session, server); try { await StoreDatabaseNames(server, client, session); // Mark server as online now, so if one of the later steps throw we'll have this value. server.NotifyServerIsOnline(); await StoreActiveDatabaseNames(server, client, session); await CheckReplicationStatusOfEachActiveDatabase(server, client, session); // Mark server as online at the LastOnlineTime. server.NotifyServerIsOnline(); } catch (HttpRequestException ex) { Log.ErrorException("Error", ex); var webException = ex.InnerException as WebException; if (webException != null) { var socketException = webException.InnerException as SocketException; if (socketException != null) { server.IsOnline = false; } } } catch (AggregateException ex) { Log.ErrorException("Error", ex); var exception = ex.ExtractSingleInnerException(); var webException = exception as WebException; if (webException != null) { var response = webException.Response as HttpWebResponse; if (response != null && response.StatusCode == HttpStatusCode.Unauthorized) { server.IsUnauthorized = true; } else { server.IsOnline = false; } } } catch (Exception ex) { Log.ErrorException("Error", ex); } finally { server.LastTriedToConnectAt = DateTimeOffset.UtcNow; } }
public async Task CreateUser(CreateUserInput input) { var user = input.MapTo <User>(); if (user.Id != 0) { var userFound = _userRepository.Get(user.Id); var modified = input.MapTo(userFound); await UserManager.SetTwoFactorEnabledAsync(input.Id, input.IsTwoFactorEnabled); await UserManager.UpdateAsync(modified); } else { user.TenantId = AbpSession.TenantId; user.Password = new PasswordHasher().HashPassword(input.Password); CheckErrors(await UserManager.CreateAsync(user)); if (bool.Parse(await SettingManager.GetSettingValueAsync("Abp.Zero.UserManagement.IsEmailConfirmationRequiredForLogin")) && input.SendNotificationMail) { var code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); var serverUrl = ServerHelpers.GetServerUrl(HttpContext.Current.Request.RequestContext.HttpContext.Request); var url = serverUrl + "/Account/EmailConfirmation/?userId=" + user.Id + "&token=" + code; await SendEmailConfirmationCode(url, user.EmailAddress); } await CurrentUnitOfWork.SaveChangesAsync(); await UserManager.SetTwoFactorEnabledAsync(user.Id, input.IsTwoFactorEnabled); await SetDefaultRoles(user); await _usersAppNotificationsSender.SendUserCreatedNotification((await GetCurrentUserAsync()), user); } }
private string GetIndexPattern(ElasticClient client, Type type = null) { if (UseTypeIndex) { return(type.IsNotNull() ? ServerHelpers.CreateIndexName(client.TenantId, type.FullName) : ServerHelpers.CreateIndexName <T>(client.TenantId)); } return(string.IsNullOrEmpty(client.TenantId) ? "_all" : $"{client.TenantId}_*"); }
private static SearchResult <T2> Do <T2>(ElasticClient client, Query <T> query, string path, JsonSerializerSettings jsonSettings, HttpMethod httpMethod) where T2 : class { var response = client.Client.DoRequest <StringResponse>(httpMethod, $"{ServerHelpers.CreateIndexName<T2>(client.TenantId)}/{path}", query.ToJson()); if (typeof(T).IsCastableTo(typeof(T2), true)) { JsonConvert.DeserializeObject <SearchResult <T2> >(response.Body, jsonSettings); } return(null); }
public void TestInitialize1() { var faker = new Faker(); var itemCountGenerator = new RandomGenerator(); var customers = Builder <Customer> .CreateListOfSize(1000) .All() .With(c => c.FirstName = faker.Name.FirstName()) .With(c => c.LastName = faker.Name.LastName()) .With(c => c.TelephoneNumber = faker.Phone.PhoneNumber()) .With(c => c.Id = Guid.NewGuid().ToString()) .With(c => c.Created = faker.Date.Past()) .With(c => c.Age = itemCountGenerator.Next(1, 200)) .Random(70) .With(c => c.EmailAddress = faker.Internet.Email()) .Build(); customers.ForEach(c => { c.Products = Builder <Product> .CreateListOfSize(itemCountGenerator.Next(1, 200)) .All() .With(oi => oi.Description = faker.Lorem.Sentence(itemCountGenerator.Next(3, 10))) .With(oi => oi.Id = Guid.NewGuid().ToString()) .With(oi => oi.Name = faker.Hacker.Noun()) .With(oi => oi.Price = faker.Finance.Amount()) .Build().ToList(); }); var configuration = IntegrationTestHelper.GetApplicationConfiguration(); _client = new ElasticClient(configuration.Protocol, configuration.Host, configuration.Port, true, configuration.Username, configuration.Password, "test"); var indexer = new ElasticIndexer <Customer>(_client); var tmap = new TypeMapping <Customer>(); tmap.AddMapping( new KeyValuePair <Expression <Func <Customer, object> >, FieldTypes>(customer => customer.Products, FieldTypes.Nested), new KeyValuePair <Expression <Func <Customer, object> >, FieldTypes>(customer => customer.FirstName, FieldTypes.Keyword), new KeyValuePair <Expression <Func <Customer, object> >, FieldTypes>(customer => customer.LastName, FieldTypes.Keyword)); indexer.DeleteIndex(ServerHelpers.CreateIndexName <Customer>("test")); indexer.CreateIndex(tmap); indexer.IndexBulk(customers, customer => customer.Id, 100); Thread.Sleep(3000); }
public OperationStatus PostGetWeeklyReport() { string token = ServerHelpers.GetAccessTokenFromRequest(this.Request); if ((bool)_usersService.Authorize(token)) { return(this._reportService.GetWeeklyReports(token)); } else { return(OperationStatus.Failed("Token is invalid")); } }
public OperationStatus PostGetTimeEntries(TimeEntryFilter filter) { string token = ServerHelpers.GetAccessTokenFromRequest(this.Request); if ((bool)_usersService.Authorize(token)) { return(_timeService.GetTimeEntryList(token, filter)); } else { return(OperationStatus.Failed("Token is invalid")); } }
public OperationStatus PostAddTimeEntry(TimeEntry timeEntry) { string token = ServerHelpers.GetAccessTokenFromRequest(this.Request); if ((bool)_usersService.Authorize(token)) { return(_timeService.InsertTimeEntry(timeEntry, token)); } else { return(OperationStatus.Failed("Token is invalid")); } }
static void Main(string[] args) { ServerHelpers.CreateServerAndConnectedClient(out s, out c1, out c2); c1.Disconnected.Subscribe(exn => { Console.WriteLine("C1 d/c " + exn); }); c2.Disconnected.Subscribe(exn => { Console.WriteLine("C2 d/c " + exn); }); Measure(8192, 8192); Console.ReadLine(); Measure(8192, 8192 * 16); Console.ReadLine(); }
public static void Main() { Console.WriteLine("Init"); Console.WriteLine("ServerHelpers connecting to Pageflex Server..."); ServerHelpers helpers = new ServerHelpers("10.0.0.110", 8008); Console.WriteLine("Connected"); Console.WriteLine("ServerHelpers fetching queue length..."); int QueueLength = helpers.GetQueueLength("pfclient-test"); Console.WriteLine("Queue Length:\t{0}", QueueLength); }
private async Task <DocumentSearchResult <T> > DoAsync <T2>(ElasticClient client, Query <T> query, string searchPath, JsonSerializerSettings jsonSerializerSettings, HttpMethod httpMethod, bool returnQuery) where T2 : class { var indexPattern = ServerHelpers.CreateIndexName <T2>(client.TenantId); var rq = string.IsNullOrEmpty(query.Scroll) ? null : new SearchRequestParameters { Scroll = TimeSpan.FromMinutes(5) }; var response = await client.Client.DoRequestAsync <StringResponse>(httpMethod, $"{indexPattern}/{searchPath}", new CancellationToken(false), query.ToJson(), rq); CheckResponse(response); var result = JsonConvert.DeserializeObject <DocumentSearchResult <T> >(response.Body, jsonSerializerSettings); if (returnQuery) { result.Query = query; } return(result); }
public CredentialsModule(IAsyncDocumentSession session) : base("/api/servers/credentials") { this.session = session; Post["/save", true] = async(parameters, ct) => { string serverId = Request.Query.ServerId; var serverRecord = await session.LoadAsync <ServerRecord>(serverId); if (serverRecord == null) { return(new NotFoundResponse()); } var credentials = this.Bind <ServerCredentials>(); await session.StoreAsync(credentials); serverRecord.CredentialsId = credentials.Id; await HealthMonitorTask.FetchServerDatabasesAsync(serverRecord, session); return(null); }; Post["/test", true] = async(parameters, ct) => { string serverId = Request.Query.ServerId; var serverRecord = await session.LoadAsync <ServerRecord>(serverId); if (serverRecord == null) { return(new NotFoundResponse()); } var credentials = this.Bind <ServerCredentials>(); var client = await ServerHelpers.CreateAsyncServerClient(session, serverRecord, credentials); try { var adminStatistics = await client.GlobalAdmin.GetStatisticsAsync(); } catch (AggregateException ex) { var exception = ex.ExtractSingleInnerException(); var webException = exception as WebException; if (webException != null) { var response = webException.Response as HttpWebResponse; if (response != null && response.StatusCode == HttpStatusCode.Unauthorized) { var failMessage = "Unauthorized. "; if (credentials.AuthenticationMode == AuthenticationMode.ApiKey) { failMessage += " Check that the Api Kay exists and enabled on the server."; } else { failMessage += " Check that the username exists in the server (or domain) and the password is correct and was not expired."; } return(new CredentialsTest { Success = false, Message = failMessage, Type = "Unauthorized", Exception = response.ToString(), }); } else { return(new CredentialsTest { Success = false, Message = "Not found. Check that the server is online and that you have access to it.", Type = "NotFound", Exception = exception.ToString(), }); } } return(new CredentialsTest { Success = false, Message = "An error occurred. See exception for more details.", Exception = exception.ToString(), }); } catch (Exception ex) { return(new CredentialsTest { Success = false, Message = "An error occurred.", Exception = ex.ToString(), }); } return(new CredentialsTest { Success = true, }); }; }
private static string GetIndexPattern <T2>(ElasticClient client) where T2 : class { return(string.IsNullOrEmpty(client.TenantId) ? "_all" : $"{ServerHelpers.CreateIndexName<T2>(client.TenantId)}"); }
private static async Task <SearchResult <T> > DoAsync(ElasticClient client, Query <T> query, string path, JsonSerializerSettings jsonSettings, HttpMethod httpMethod, CancellationToken token) { var response = await client.Client.DoRequestAsync <StringResponse>(httpMethod, $"{ServerHelpers.CreateIndexName<T>(client.TenantId)}/{path}", token, query.ToJson()); CheckResponse(response); return(JsonConvert.DeserializeObject <SearchResult <T> >(response.Body, jsonSettings)); }
private static ElasticsearchResponse <string> Do(ElasticClient client, string query, string type, string path, HttpMethod httpMethod) { var response = client.Client.DoRequest <StringResponse>(httpMethod, $"{ServerHelpers.CreateIndexName(client.TenantId, type)}/{path}", query); return(response); }
public async Task CreateUser(CreateUserInput input) { var user = input.MapTo <User>(); var hasher = new PasswordHasher(); if (user.Id != 0) { var userFound = _userRepository.Get(user.Id); var pssw = userFound.Password; var modified = input.MapTo(userFound); modified.Password = pssw; await UserManager.SetTwoFactorEnabledAsync(input.Id, input.IsTwoFactorEnabled); await UserManager.UpdateAsync(modified); if (!string.IsNullOrEmpty(input.Password)) { var checkedPassword = hasher.VerifyHashedPassword(pssw, input.Password); switch (checkedPassword) { case PasswordVerificationResult.Failed: //Is new password modified.Password = hasher.HashPassword(input.Password); await UserManager.UpdateAsync(modified); break; //Rev-02.09.2016 //case PasswordVerificationResult.Success: // //Is old password // modified.Password = pssw; // await UserManager.UpdateAsync(modified); // break; //case PasswordVerificationResult.SuccessRehashNeeded: // modified.Password = hasher.HashPassword(input.Password); // await UserManager.UpdateAsync(modified); // break; default: throw new ArgumentOutOfRangeException(); } await _usersAppNotificationsSender.SendUserEditedNotification((await GetCurrentUserAsync()), userFound); } else { modified.Password = pssw; await UserManager.UpdateAsync(modified); } } else { user.TenantId = AbpSession.TenantId; user.Password = new PasswordHasher().HashPassword(input.Password); CheckErrors(await UserManager.CreateAsync(user)); if (bool.Parse(await SettingManager.GetSettingValueAsync("Abp.Zero.UserManagement.IsEmailConfirmationRequiredForLogin")) && input.SendNotificationMail) { var code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); var serverUrl = ServerHelpers.GetServerUrl(HttpContext.Current.Request.RequestContext.HttpContext.Request); var url = serverUrl + "/Account/EmailConfirmation/?userId=" + user.Id + "&token=" + code; await SendEmailConfirmationCode(url, user.EmailAddress); } await CurrentUnitOfWork.SaveChangesAsync(); await UserManager.SetTwoFactorEnabledAsync(user.Id, input.IsTwoFactorEnabled); await SetDefaultRoles(user); await _usersAppNotificationsSender.SendUserCreatedNotification((await GetCurrentUserAsync()), user); //if (input.SendNotificationMail) //{ // await SendWelcomeEmail(user, input.Password); //} } }