public async Task <IEnumerable <HashTag> > GetTopAsync(int amount) { ServiceHelpers.CheckValidId(amount); return(await _repository.GetTopAsync(amount)); }
/// <summary> /// Example how to create route on server with route parameters /// Minimum parameters is specified /// </summary> /// <param name="mission">Mission where create route</param> /// <param name="vehicleProfile">Profile for route</param> /// <param name="name">Route name</param> /// <returns></returns> public Route CreateNewRoute(Mission mission, VehicleProfile vehicleProfile, String name = "TestRoute") { var routeName = string.Format("{0} {1}", name, DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString()); Route route = new Route { CreationTime = ServiceHelpers.CreationTime(), Name = routeName, Mission = mission }; ChangeRouteVehicleProfileRequest request = new ChangeRouteVehicleProfileRequest { ClientId = _connect.AuthorizeHciResponse.ClientId, Route = route, NewProfile = new VehicleProfile { Id = vehicleProfile.Id } }; MessageFuture <ChangeRouteVehicleProfileResponse> future = _connect.Executor.Submit <ChangeRouteVehicleProfileResponse>(request); future.Wait(); route = future.Value.Route; route.Mission = mission; route.TrajectoryType = TrajectoryType.TT_STAIR; route.MaxAltitude = 50.0; route.SafeAltitude = 3.0; route.CheckAerodromeNfz = false; route.CheckAerodromeNfzSpecified = true; route.InitialSpeed = 0.0; route.MaxSpeed = 0.0; route.CheckCustomNfz = false; route.CheckCustomNfzSpecified = true; route.Failsafes.Add(new Failsafe() { Action = FailsafeAction.FA_GO_HOME, ActionSpecified = true, Reason = FailsafeReason.FR_RC_LOST, ReasonSpecified = true, }); route.Failsafes.Add(new Failsafe() { Action = FailsafeAction.FA_LAND, ActionSpecified = true, Reason = FailsafeReason.FR_LOW_BATTERY, ReasonSpecified = true }); route.Failsafes.Add(new Failsafe() { Action = FailsafeAction.FA_WAIT, ActionSpecified = true, Reason = FailsafeReason.FR_GPS_LOST, ReasonSpecified = true }); route.Failsafes.Add(new Failsafe() { Action = FailsafeAction.FA_GO_HOME, ActionSpecified = true, Reason = FailsafeReason.FR_DATALINK_LOST, ReasonSpecified = true }); return(SaveUpdatedRoute(route)); }
protected override void Seed(MVCForumContext context) { #region Initial Installer Code //var isFirstInstall = false; // Add the language - If it's not already there const string langCulture = "en-GB"; var language = context.Language.FirstOrDefault(x => x.LanguageCulture == langCulture); if (language == null) { //isFirstInstall = true; var cultureInfo = LanguageUtils.GetCulture(langCulture); language = new Language { Name = cultureInfo.EnglishName, LanguageCulture = cultureInfo.Name, }; context.Language.Add(language); // Save the language context.SaveChanges(); // Now add the default language strings var file = HostingEnvironment.MapPath(@"~/Installer/en-GB.csv"); var commaSeparator = new[] { ',' }; if (file != null) { // Unpack the data var allLines = new List <string>(); using (var streamReader = new StreamReader(file, Encoding.UTF8, true)) { while (streamReader.Peek() >= 0) { allLines.Add(streamReader.ReadLine()); } } // Read the CSV file and import all the keys and values var lineCounter = 0; foreach (var csvline in allLines) { var line = csvline; if (line.StartsWith("\"")) { line = line.Replace("\"", ""); } lineCounter++; // Only split on the first comma, so the value strings can have commas in var keyValuePair = line.Split(commaSeparator, 2, StringSplitOptions.None); // Get the key and value var key = keyValuePair[0]; var value = keyValuePair[1]; if (string.IsNullOrEmpty(key)) { // Ignore empty keys continue; } if (string.IsNullOrEmpty(value)) { // Ignore empty values continue; } // Trim both the key and value key = key.Trim(); value = value.Trim(); // Create the resource key var resourceKey = new LocaleResourceKey { Name = key, DateAdded = DateTime.UtcNow, }; context.LocaleResourceKey.Add(resourceKey); // Set the value for the resource var stringResource = new LocaleStringResource { Language = language, LocaleResourceKey = resourceKey, ResourceValue = value }; context.LocaleStringResource.Add(stringResource); } // Save the language strings context.SaveChanges(); } var saveRoles = false; // Create the admin role if it doesn't exist var adminRole = context.MembershipRole.FirstOrDefault(x => x.RoleName == AppConstants.AdminRoleName); if (adminRole == null) { adminRole = new MembershipRole { RoleName = AppConstants.AdminRoleName }; context.MembershipRole.Add(adminRole); saveRoles = true; } // Create the Standard role if it doesn't exist var standardRole = context.MembershipRole.FirstOrDefault(x => x.RoleName == SiteConstants.Instance.StandardMembers); if (standardRole == null) { standardRole = new MembershipRole { RoleName = SiteConstants.Instance.StandardMembers }; context.MembershipRole.Add(standardRole); saveRoles = true; } // Create the Guest role if it doesn't exist var guestRole = context.MembershipRole.FirstOrDefault(x => x.RoleName == AppConstants.GuestRoleName); if (guestRole == null) { guestRole = new MembershipRole { RoleName = AppConstants.GuestRoleName }; context.MembershipRole.Add(guestRole); saveRoles = true; } if (saveRoles) { context.SaveChanges(); } // Create an example Category if (!context.Category.Any()) { // Doesn't exist so add the example category const string exampleCatName = "Example Category"; var exampleCat = new Category { Name = exampleCatName, ModeratePosts = false, ModerateTopics = false, Slug = ServiceHelpers.CreateUrl(exampleCatName), DateCreated = DateTime.UtcNow }; context.Category.Add(exampleCat); context.SaveChanges(); } // if the settings already exist then do nothing // If not then add default settings var currentSettings = context.Setting.FirstOrDefault(); if (currentSettings == null) { // create the settings var settings = new Settings { ForumName = "MVCForum", ForumUrl = "http://www.mydomain.com", IsClosed = false, EnableRSSFeeds = true, DisplayEditedBy = true, EnablePostFileAttachments = false, EnableMarkAsSolution = true, EnableSpamReporting = true, EnableMemberReporting = true, EnableEmailSubscriptions = true, ManuallyAuthoriseNewMembers = false, EmailAdminOnNewMemberSignUp = true, TopicsPerPage = 20, PostsPerPage = 20, EnablePrivateMessages = true, MaxPrivateMessagesPerMember = 50, PrivateMessageFloodControl = 1, EnableSignatures = false, EnablePoints = true, PointsAllowedToVoteAmount = 1, PointsAllowedForExtendedProfile = 1, PointsAddedPerPost = 1, PointsAddedForSolution = 4, PointsDeductedNagativeVote = 2, PointsAddedPostiveVote = 2, AdminEmailAddress = "*****@*****.**", NotificationReplyEmail = "*****@*****.**", SMTPEnableSSL = false, Theme = "Metro", NewMemberStartingRole = standardRole, DefaultLanguage = language, ActivitiesPerPage = 20, EnableAkisment = false, EnableSocialLogins = false, EnablePolls = true, MarkAsSolutionReminderTimeFrame = 7, EnableEmoticons = true, DisableStandardRegistration = false, ShowPostContent = true, AutoLoginAfterRegister = true }; context.Setting.Add(settings); context.SaveChanges(); } // Create the initial category permissions // Edit Posts if (context.Permission.FirstOrDefault(x => x.Name == SiteConstants.Instance.PermissionEditPosts) == null) { var permission = new Permission { Name = SiteConstants.Instance.PermissionEditPosts }; context.Permission.Add(permission); // NOTE: Because this is null - We assumed it's a new install so carry on checking and adding the other permissions // Read Only if (context.Permission.FirstOrDefault(x => x.Name == SiteConstants.Instance.PermissionReadOnly) == null) { var p = new Permission { Name = SiteConstants.Instance.PermissionReadOnly }; context.Permission.Add(p); } // Delete Posts if (context.Permission.FirstOrDefault(x => x.Name == SiteConstants.Instance.PermissionDeletePosts) == null) { var p = new Permission { Name = SiteConstants.Instance.PermissionDeletePosts }; context.Permission.Add(p); } // Sticky Topics if (context.Permission.FirstOrDefault(x => x.Name == SiteConstants.Instance.PermissionCreateStickyTopics) == null) { var p = new Permission { Name = SiteConstants.Instance.PermissionCreateStickyTopics }; context.Permission.Add(p); } // Lock Topics if (context.Permission.FirstOrDefault(x => x.Name == SiteConstants.Instance.PermissionLockTopics) == null) { var p = new Permission { Name = SiteConstants.Instance.PermissionLockTopics }; context.Permission.Add(p); } // Vote In Polls if (context.Permission.FirstOrDefault(x => x.Name == SiteConstants.Instance.PermissionVoteInPolls) == null) { var p = new Permission { Name = SiteConstants.Instance.PermissionVoteInPolls }; context.Permission.Add(p); } // Create Polls if (context.Permission.FirstOrDefault(x => x.Name == SiteConstants.Instance.PermissionCreatePolls) == null) { var p = new Permission { Name = SiteConstants.Instance.PermissionCreatePolls }; context.Permission.Add(p); } // Create Topics if (context.Permission.FirstOrDefault(x => x.Name == SiteConstants.Instance.PermissionCreateTopics) == null) { var p = new Permission { Name = SiteConstants.Instance.PermissionCreateTopics }; context.Permission.Add(p); } // Attach Files if (context.Permission.FirstOrDefault(x => x.Name == SiteConstants.Instance.PermissionAttachFiles) == null) { var p = new Permission { Name = SiteConstants.Instance.PermissionAttachFiles }; context.Permission.Add(p); } // Deny Access if (context.Permission.FirstOrDefault(x => x.Name == SiteConstants.Instance.PermissionDenyAccess) == null) { var p = new Permission { Name = SiteConstants.Instance.PermissionDenyAccess }; context.Permission.Add(p); } // === Global Permissions === // // Deny Access if (context.Permission.FirstOrDefault(x => x.Name == SiteConstants.Instance.PermissionEditMembers) == null) { var p = new Permission { Name = SiteConstants.Instance.PermissionEditMembers, IsGlobal = true }; context.Permission.Add(p); } // Insert Editor Images if (context.Permission.FirstOrDefault(x => x.Name == SiteConstants.Instance.PermissionInsertEditorImages) == null) { var p = new Permission { Name = SiteConstants.Instance.PermissionInsertEditorImages, IsGlobal = true }; context.Permission.Add(p); } // Save to the database context.SaveChanges(); } // If the admin user exists then don't do anything else const string adminUsername = "******"; if (context.MembershipUser.FirstOrDefault(x => x.UserName == adminUsername) == null) { // create the admin user and put him in the admin role var admin = new MembershipUser { Email = "*****@*****.**", UserName = adminUsername, Password = "******", IsApproved = true, DisableEmailNotifications = false, DisablePosting = false, DisablePrivateMessages = false, CreateDate = DateTime.UtcNow, LastLockoutDate = (DateTime)SqlDateTime.MinValue, LastPasswordChangedDate = (DateTime)SqlDateTime.MinValue, LastLoginDate = DateTime.UtcNow, LastActivityDate = null, IsLockedOut = false, Slug = ServiceHelpers.CreateUrl(adminUsername) }; // Hash the password var salt = StringUtils.CreateSalt(AppConstants.SaltSize); var hash = StringUtils.GenerateSaltedHash(admin.Password, salt); admin.Password = hash; admin.PasswordSalt = salt; // Put the admin in the admin role admin.Roles = new List <MembershipRole> { adminRole }; context.MembershipUser.Add(admin); context.SaveChanges(); // Now add read me const string name = "Read Me"; var category = context.Category.FirstOrDefault(); var topic = new Topic { Category = category, CreateDate = DateTime.UtcNow, User = admin, IsSticky = true, Name = name, Slug = ServiceHelpers.CreateUrl(name) }; context.Topic.Add(topic); context.SaveChanges(); const string readMeText = @"<h2>Administration</h2> <p>We have auto created an admin user for you to manage the site</p> <p>Username: <strong>admin</strong><br />Password: <strong>password</strong></p> <p>Once you have logged in, you can manage the forum <a href=""/admin/"">through the admin section</a>. </p> <p><strong><font color=""#ff0000"">Important:</font> </strong>Please update the admin password (and username) before putting this site live.</p> <h2>Documentation</h2> <p>We have documentation on Github in the WIKI</p> <p><a href=""https://github.com/YodasMyDad/mvcforum/wiki"">https://github.com/YodasMyDad/mvcforum/wiki</a></p> <p>You can also grab the source code from Github too.</p>"; var post = new Post { DateCreated = DateTime.UtcNow, DateEdited = DateTime.UtcNow, Topic = topic, IsTopicStarter = true, User = admin, PostContent = readMeText, SearchField = name }; topic.LastPost = post; context.Post.Add(post); context.SaveChanges(); } } else { // ---- Do Data Updates here // Data to update on versions v1.7+ // Insert Editor Images if (context.Permission.FirstOrDefault(x => x.Name == SiteConstants.Instance.PermissionInsertEditorImages) == null) { var p = new Permission { Name = SiteConstants.Instance.PermissionInsertEditorImages, IsGlobal = true }; context.Permission.Add(p); } } #endregion }
/// <inheritdoc /> public async Task <IPipelineProcess <Category> > Process(IPipelineProcess <Category> input, IMvcForumContext context) { _localizationService.RefreshContext(context); _categoryService.RefreshContext(context); try { Guid?parentCategoryGuid = null; if (input.ExtendedData.ContainsKey(Constants.ExtendedDataKeys.ParentCategory)) { parentCategoryGuid = input.ExtendedData[Constants.ExtendedDataKeys.ParentCategory] as Guid?; } // Sort if this is a section Section section = null; if (input.ExtendedData.ContainsKey(Constants.ExtendedDataKeys.Section)) { if (input.ExtendedData[Constants.ExtendedDataKeys.Section] is Guid guid) { section = _categoryService.GetSection(guid); } } // Sort the section - If it's null remove it input.EntityToProcess.Section = section ?? null; var isEdit = false; if (input.ExtendedData.ContainsKey(Constants.ExtendedDataKeys.IsEdit)) { isEdit = input.ExtendedData[Constants.ExtendedDataKeys.IsEdit] as bool? == true; } if (isEdit) { var parentCat = parentCategoryGuid != null ? _categoryService.Get(parentCategoryGuid.Value) : null; // Check they are not trying to add a subcategory of this category as the parent or it will break if (parentCat?.Path != null && parentCategoryGuid != null) { var parentCats = parentCat.Path.Split(',').Where(x => !string.IsNullOrWhiteSpace(x)) .Select(x => new Guid(x)).ToList(); if (parentCats.Contains(input.EntityToProcess.Id)) { // Remove the parent category, but still let them create the catgory parentCategoryGuid = null; } } if (parentCategoryGuid != null) { // Set the parent category var parentCategory = _categoryService.Get(parentCategoryGuid.Value); input.EntityToProcess.ParentCategory = parentCategory; // Append the path from the parent category _categoryService.SortPath(input.EntityToProcess, parentCategory); } else { // Must access property (trigger lazy-loading) before we can set it to null (Entity Framework bug!!!) var triggerEfLoad = input.EntityToProcess.ParentCategory; input.EntityToProcess.ParentCategory = null; // Also clear the path input.EntityToProcess.Path = null; } _categoryService.UpdateSlugFromName(input.EntityToProcess); await context.SaveChangesAsync(); } else { if (parentCategoryGuid != null) { var parentCategory = await context.Category.FirstOrDefaultAsync(x => x.Id == parentCategoryGuid.Value); input.EntityToProcess.ParentCategory = parentCategory; _categoryService.SortPath(input.EntityToProcess, parentCategory); } // url slug generator input.EntityToProcess.Slug = ServiceHelpers.GenerateSlug(input.EntityToProcess.Name, _categoryService.GetBySlugLike(ServiceHelpers.CreateUrl(input.EntityToProcess.Name)).Select(x => x.Slug).ToList(), null); // Add the category context.Category.Add(input.EntityToProcess); } await context.SaveChangesAsync(); _cacheService.ClearStartsWith("CategoryList"); } catch (Exception ex) { input.AddError(ex.Message); _loggingService.Error(ex); } return(input); }
/// <summary> /// Return a static list of all U.S. states /// </summary> /// <returns></returns> public IEnumerable <State> ListOfStates() { var states = ServiceHelpers.CreateStateList(); return(states.ToList()); }
public async Task <ICollection <ApplicationUser> > GetRange(int from, int to) { ServiceHelpers.CheckRange(from, to); return(await _repository.GetRange(from, to)); }
public async Task <ICollection <ApplicationUser> > GetFollowers(int userId) { ServiceHelpers.CheckValidId(userId); return(await _repository.GetFollowers(userId)); }
/// <summary> /// The main entry point for the application. /// </summary> public static void Main() { // Create the loggerFactory as Console + Log4Net. using (var loggerFactory = LoggerFactory.Create(builder => { builder.AddConsole(); builder.SetMinimumLevel(LogLevel.Trace); builder.AddLog4Net(); })) { var relativePaths = new[] { "../Config", "../../../../../SampleConfigurations" }; var configurationsPathRoot = ConfigurationService.FindRelativeDirectory(relativePaths, loggerFactory.CreateLogger("Main")); var aetConfigurationProvider = new AETConfigProvider( loggerFactory.CreateLogger("ModelSettings"), configurationsPathRoot); var gatewayProcessorConfigProvider = new GatewayProcessorConfigProvider( loggerFactory.CreateLogger("ProcessorSettings"), configurationsPathRoot); var segmentationClientLogger = loggerFactory.CreateLogger("SegmentationClient"); // The ProjectInstaller.cs uses the service name to install the service. // If you change it please update the ProjectInstaller.cs ServiceHelpers.RunServices( ServiceName, gatewayProcessorConfigProvider.ServiceSettings(), new ConfigurationService( gatewayProcessorConfigProvider.CreateInnerEyeSegmentationClient(segmentationClientLogger), gatewayProcessorConfigProvider.ConfigurationServiceConfig, loggerFactory.CreateLogger("ConfigurationService"), new UploadService( gatewayProcessorConfigProvider.CreateInnerEyeSegmentationClient(segmentationClientLogger), aetConfigurationProvider.GetAETConfigs, GatewayMessageQueue.UploadQueuePath, GatewayMessageQueue.DownloadQueuePath, GatewayMessageQueue.DeleteQueuePath, gatewayProcessorConfigProvider.DequeueServiceConfig, loggerFactory.CreateLogger("UploadService"), instances: 2), new DownloadService( gatewayProcessorConfigProvider.CreateInnerEyeSegmentationClient(segmentationClientLogger), GatewayMessageQueue.DownloadQueuePath, GatewayMessageQueue.PushQueuePath, GatewayMessageQueue.DeleteQueuePath, gatewayProcessorConfigProvider.DownloadServiceConfig, gatewayProcessorConfigProvider.DequeueServiceConfig, loggerFactory.CreateLogger("DownloadService"), instances: 1), new PushService( aetConfigurationProvider.GetAETConfigs, new DicomDataSender(), GatewayMessageQueue.PushQueuePath, GatewayMessageQueue.DeleteQueuePath, gatewayProcessorConfigProvider.DequeueServiceConfig, loggerFactory.CreateLogger("PushService"), instances: 1), new DeleteService( GatewayMessageQueue.DeleteQueuePath, gatewayProcessorConfigProvider.DequeueServiceConfig, loggerFactory.CreateLogger("DeleteService")))); } }
public async Task <ApplicationUser> GetById(int userId) { ServiceHelpers.CheckValidId(userId); return(await _repository.FindAsync(u => u.Id.Equals(userId))); }
public void AddQueryInURL_EmptyString_ReturnString(string url, string query) { var result = ServiceHelpers.AddQueryInURL(url, query); result.Should().Contain("?"); }
public void AddQueryInURL_String_ReturnString(string url, string query) { var result = ServiceHelpers.AddQueryInURL(url, query); result.Should().Be("test?test/"); }
public void GetObjectFromString_EmptyString_ReturnString(string str) { var result = ServiceHelpers.GetObjectFromString(str); result.GetType().Name.Should().Be("String"); }
public void GetObjectFromString_CorrectString_ReturnXDoc(string str) { var result = ServiceHelpers.GetObjectFromString(str); result.GetType().Name.Should().Be("XDocument"); }
public ResponceInfo SendMessage(RequestInfo request) { var(isValid, results) = Validate.ValidateModel(request); if (isValid) { try { Log.Logger().LogInformation("Request: " + Environment.NewLine + request.Url + Environment.NewLine + request.Method + Environment.NewLine + request.Content.ReadAsStringAsync().Result); var resp = fprovider.SendRequest(request); var content = ServiceHelpers.GetObjectFromString(resp.Result.Content.ReadAsStringAsync().Result); Log.Logger().LogInformation("Responce: " + Environment.NewLine + resp.Result.StatusCode + Environment.NewLine + resp.Result.Content.ReadAsStringAsync().Result); return(new ResponceInfo { Headers = resp.Result.Headers, Content = content, Request = request, StatusCode = resp.Result.StatusCode }); } catch (FlurlHttpTimeoutException) { Log.Logger().LogError("Request:" + request.Url + Environment.NewLine + request.Method + Environment.NewLine + request.Content.Headers.ToString() + Environment.NewLine + "timed out."); return(new ResponceInfo { Headers = null, Content = new StringContent(string.Empty), StatusCode = System.Net.HttpStatusCode.GatewayTimeout, Request = request }); } catch (Exception ex) { if (ex.InnerException is FlurlHttpException fex) { if (fex.Call == null) { Log.Logger().LogError("Request:" + request.Url + Environment.NewLine + request.Method + Environment.NewLine + request.Content.Headers.ToString() + Environment.NewLine + "failed:" + fex.Message); Log.Logger().LogInformation("Responce status code: " + Environment.NewLine + System.Net.HttpStatusCode.BadRequest); return(new ResponceInfo { Headers = null, Content = new StringContent(string.Empty), StatusCode = System.Net.HttpStatusCode.BadRequest, Request = request }); } else { string fexResult = string.Empty; if (fex.Call.Response != null) { fexResult = fex.Call.Response.ResponseMessage.Content.ReadAsStringAsync().Result; Log.Logger().LogInformation("Responce: " + Environment.NewLine + fex.Call.Response.StatusCode + Environment.NewLine + fexResult); } else { Log.Logger().LogInformation("Responce is empty. Check request parameters."); Log.Logger().LogError("Request:" + request.Url + Environment.NewLine + request.Method + Environment.NewLine + request.Content.Headers.ToString() + Environment.NewLine + "failed:" + fex.Message); return(null); } Log.Logger().LogError("Request:" + request.Url + Environment.NewLine + request.Method + Environment.NewLine + request.Content.Headers.ToString() + Environment.NewLine + "failed:" + fex.Message); var content = ServiceHelpers.GetObjectFromString(fexResult); return(new ResponceInfo { Headers = fex.Call.Response.ResponseMessage.Headers, Content = content, StatusCode = fex.Call.Response.ResponseMessage.StatusCode, Request = request }); } } Log.Logger().LogError("Request:" + request.Url + Environment.NewLine + request.Method + Environment.NewLine + request.Content.Headers.ToString() + Environment.NewLine + "failed:" + ex.Message); Log.Logger().LogInformation("Responce: " + Environment.NewLine + System.Net.HttpStatusCode.BadRequest); return(new ResponceInfo { Headers = null, Content = new StringContent(string.Empty), StatusCode = System.Net.HttpStatusCode.BadRequest, Request = request }); } } else { Log.Logger().LogInformation($"Request is not valid " + Environment.NewLine + request.Url + Environment.NewLine + request.Method + Environment.NewLine + request.Content.ReadAsStringAsync().Result); return(null); } }
protected override async void Action() { await Task.Factory.StartNew(() => ServiceHelpers.RestartServiceGroup(this.GroupName)); this.Controller.ShowBaloon("Stopped", $"All services in group {this.GroupName} was restarted", ToolTipIcon.Info); }
private string GetStartedServicesInfo() { var services = ServiceHelpers.GetServicesByGroupName(this.GroupName).ToList(); return($"{services.Count(service => service.IsStarted())} of {services.Count}"); }