public void ExecuteRecipeStep(RecipeContext recipeContext) { if (!String.Equals(recipeContext.RecipeStep.Name, "Forms", StringComparison.OrdinalIgnoreCase)) { return; } var formsElement = recipeContext.RecipeStep.Step.Elements(); foreach (var formElement in formsElement) { var formName = formElement.Attr <string>("Name"); var submissionElements = formElement.Element("Submissions").Elements(); foreach (var submissionElement in submissionElements) { _formService.CreateSubmission(new Submission { FormName = formName, CreatedUtc = submissionElement.Attr <DateTime>("CreatedUtc"), FormData = submissionElement.Value }); } } recipeContext.Executed = true; }
static void Main(string[] args) { using (var context = new RecipeContext()) { context.Database.EnsureCreated(); } var crawler = new RecipeCrawler(); crawler.page = 1; var res = crawler.GetRecipeResponseAsync(); res.Wait(); //TODO: After each recipe go to the next page in the recipes BaseURL = "https://www.bonappetit.com/"; //Go to The Recipes page ScrapingBrowser browser = new ScrapingBrowser(); //set UseDefaultCookiesParser as false if a website returns invalid cookies format //browser.UseDefaultCookiesParser = false; WebPage recipesPage = browser.NavigateToPage(new Uri(BaseURL + "recipes")); //Create a process for grabbing recipe urls var recipeCards = recipesPage.Html.CssSelect(".card-hed a").ToList(); foreach (var recipe in recipeCards) { MapRecipe(recipe, browser); } System.Console.WriteLine("Done reading Recipes, press any key to close"); System.Console.ReadLine(); }
public static void MapRecipe(HtmlAgilityPack.HtmlNode recipe, ScrapingBrowser browser) { using (var context = new RecipeContext()) { WebPage recipePage = browser.NavigateToPage(new Uri(BaseURL + recipe.Attributes["href"].Value)); var html = recipePage.Html; var name = html.CssSelect("h1.post__header__hed a").FirstOrDefault().InnerHtml; var result = context.Recipes.FirstOrDefault(x => x.RecipeName == name); if (result == null) { result = new Recipe(); result.RecipeName = name; context.Recipes.Add(result); result.Ingredients = new List <Ingredient>(); } var ingredients = html.CssSelect("li.ingredient div").ToList(); System.Console.WriteLine(name); foreach (var ingredientHtml in ingredients) { if (context.Ingredients.Any(x => x.IngredientName == ingredientHtml.InnerHtml) == false && result.Ingredients.Any(x => x.IngredientName == ingredientHtml.InnerHtml)) { result.Ingredients.Add(MapIngredient(ingredientHtml)); } } context.SaveChanges(); } }
// GET: /Recipe/Display/ public ActionResult Display(int recipeId, double scaler = 1, bool?isCelsius = null) { string key = recipeId.ToString(); if (GlobalCachingProvider.Instance.IsCached(key)) { //This casting is bad should fix later on down the road currentRecipe = (Recipe)GlobalCachingProvider.Instance.GetItem(key); } else { IRecipeDBManager db = new RecipeContext(); currentRecipe = db.GetRecipeById(recipeId); GlobalCachingProvider.Instance.AddItem(key, currentRecipe); } RecipeViewModel viewModel; if (isCelsius == null) { viewModel = new RecipeViewModel(currentRecipe.ScaleRecipe(scaler), scaler); } else { viewModel = new RecipeViewModel(currentRecipe.ScaleRecipe(scaler), scaler, (bool)isCelsius); } return(View(viewModel)); }
public ActionResult Browse() { IRecipeDBManager db = new RecipeContext(); List <Recipe> model = db.GetFullListRecipes(); return(View(model)); }
// <Data /> // Import Data public void ExecuteRecipeStep(RecipeContext recipeContext) { if (!String.Equals(recipeContext.RecipeStep.Name, "Data", StringComparison.OrdinalIgnoreCase)) { return; } // First pass to resolve content items from content identities for all content items, new and old. var importContentSession = new ImportContentSession(_orchardServices.ContentManager); foreach (var element in recipeContext.RecipeStep.Step.Elements()) { var elementId = element.Attribute("Id"); if (elementId == null) { continue; } var identity = elementId.Value; var status = element.Attribute("Status"); importContentSession.Set(identity, element.Name.LocalName); var item = importContentSession.Get(identity); } // Second pass to import the content items. foreach (var element in recipeContext.RecipeStep.Step.Elements()) { _orchardServices.ContentManager.Import(element, importContentSession); } recipeContext.Executed = true; }
/* * <Settings> * <SiteSettingsPart PageSize="30" /> * <CommentSettingsPart ModerateComments="true" /> * </Settings> */ // Set site and part settings. public void ExecuteRecipeStep(RecipeContext recipeContext) { if (!String.Equals(recipeContext.RecipeStep.Name, "Settings", StringComparison.OrdinalIgnoreCase)) { return; } var site = _siteService.GetSiteSettings(); foreach (var element in recipeContext.RecipeStep.Step.Elements()) { var partName = XmlConvert.DecodeName(element.Name.LocalName); foreach (var contentPart in site.ContentItem.Parts) { if (!String.Equals(contentPart.PartDefinition.Name, partName, StringComparison.OrdinalIgnoreCase)) { continue; } foreach (var attribute in element.Attributes()) { SetSetting(attribute, contentPart); } } } recipeContext.Executed = true; }
/* * <ContentRedactions> * <add Regex="Production" Placeholder="EnvironmentName" ReplaceWith="Local" /> * </ContentRedactions> */ // Add a set of redactions public void ExecuteRecipeStep(RecipeContext recipeContext) { if (!String.Equals(recipeContext.RecipeStep.Name, "ContentRedactions", StringComparison.OrdinalIgnoreCase) && !String.Equals(recipeContext.RecipeStep.Name, "Redactions", StringComparison.OrdinalIgnoreCase)) //this check is for legacy reasons { return; } _realtimeFeedbackService.Info(T("Starting 'Content Redactions' step")); var redactions = recipeContext.RecipeStep.Step.Descendants().Where(f => f.Name == "add"); foreach (var redaction in redactions) { var placeholder = redaction.Attribute("Placeholder").Value; var regex = redaction.Attribute("Regex").Value; var replaceWith = redaction.Attribute("ReplaceWith").Value; _realtimeFeedbackService.Info(T("Adding content redaction {0} to match regex {1} and relace with {2}", placeholder, regex, replaceWith)); _textRedactionService.AddRedaction(new RedactionRecord { Placeholder = placeholder, Regex = regex, ReplaceWith = replaceWith, }); } _realtimeFeedbackService.Info(T("Step 'Content Redactions' has finished")); recipeContext.Executed = true; }
public IActionResult Edit(int id) { var db = new RecipeContext(); var ingredient = db.ingredients.Find(id); return(View(ingredient)); }
public async Task <List <string> > ExecuteAsync() { using (RecipeContext context = new RecipeContext(_appSettingsProvider.ConnectionString)) { return(await context.Categories.Select(x => x.Name).ToListAsync()); } }
public UserService(IOptions <AppSettings> appSettings, IOptions <JWT_Settings> jwtSettings, ILogger <UserService> logger, IOptions <URLs> urls, IOptions <EmailSettings> emailSettings, RecipeContext context, ITokenBuilder tokenBuilder, IHostEnvironment env) { _jwtSettings = jwtSettings.Value; _appSettings = appSettings.Value; _emailSettings = emailSettings.Value; _urls = urls.Value; _logger = logger; _context = context; _tokenBuilder = tokenBuilder; _passwordHasher = new PasswordHasher <Users>(); _emailService = new Mail(this._emailSettings.NameOfSender, this._emailSettings.Sender, this._emailSettings.SenderPassword, this._emailSettings.Host, this._emailSettings.Port); if (env.IsDevelopment()) { this.url = this._urls.Development; } else if (env.IsStaging()) { this.url = this._urls.Staging; } else if (env.IsProduction()) { this.url = this._urls.Production; } }
public void ExecuteRecipeStep(RecipeContext recipeContext) { if (!String.Equals(recipeContext.RecipeStep.Name, "ThemeSettings", StringComparison.OrdinalIgnoreCase)) { return; } foreach (var themeElement in recipeContext.RecipeStep.Step.Elements()) { var themeName = themeElement.Attr <string>("Name"); foreach (var profileElement in themeElement.Elements()) { var profileName = profileElement.Attr <string>("Name"); var profile = _themeSettingsService.GetProfile(profileName) ?? new ThemeProfile(); profile.Name = profileElement.Attr <string>("Name"); profile.Description = profileElement.Attr <string>("Description"); profile.Theme = themeName; profile.IsCurrent = profileElement.Attr <bool>("IsCurrent"); profile.Settings = _themeSettingsService.DeserializeSettings(profileElement.Value); _themeSettingsService.SaveProfile(profile); } } recipeContext.Executed = true; }
public RecipeRepository() { _dbContext = new RecipeContext(); _dbContext.Ingredients.Load(); _dbContext.RecipeIngredients.Load(); _dbContext.Recipes.Load(); }
public LoginController(ILogger <LoginController> logger, RecipeContext context, AccountService accountService, LoginService loginService) { this.logger = logger; this.context = context; this.accountService = accountService; this.loginService = loginService; }
public void ExecuteRecipeStep(RecipeContext recipeContext) { if (!String.Equals(recipeContext.RecipeStep.Name, "AuditTrail", StringComparison.OrdinalIgnoreCase)) { return; } if (!_authorizer.Authorize(Permissions.ImportAuditTrail)) { Logger.Warning("Blocked {0} from importing an audit trail because this user does not have the ImportauditTrail permission.", _wca.GetContext().CurrentUser.UserName); recipeContext.Executed = false; return; } foreach (var eventElement in recipeContext.RecipeStep.Step.Elements()) { var record = new AuditTrailEventRecord { EventName = eventElement.Attr <string>("Name"), FullEventName = eventElement.Attr <string>("FullName"), Category = eventElement.Attr <string>("Category"), UserName = eventElement.Attr <string>("User"), CreatedUtc = eventElement.Attr <DateTime>("CreatedUtc"), EventFilterKey = eventElement.Attr <string>("EventFilterKey"), EventFilterData = eventElement.Attr <string>("EventFilterData"), Comment = eventElement.El("Comment"), EventData = eventElement.Element("EventData").ToString(), }; _auditTrailEventRepository.Create(record); } recipeContext.Executed = true; }
public async Task ExecuteRecipeStepAsync(RecipeContext recipeContext) { var recipeExecutionSteps = _serviceProvider.GetServices <IRecipeExecutionStep>(); var executionStep = recipeExecutionSteps .FirstOrDefault(x => x.Names.Contains(recipeContext.RecipeStep.Name, StringComparer.OrdinalIgnoreCase)); if (executionStep != null) { var recipeExecutionContext = new RecipeExecutionContext { ExecutionId = recipeContext.ExecutionId, RecipeStep = recipeContext.RecipeStep }; if (_logger.IsEnabled(LogLevel.Information)) { _logger.LogInformation("Executing recipe step '{0}'.", recipeContext.RecipeStep.Name); } await executionStep.ExecuteAsync(recipeExecutionContext); if (_logger.IsEnabled(LogLevel.Information)) { _logger.LogInformation("Finished executing recipe step '{0}'.", recipeContext.RecipeStep.Name); } recipeContext.Executed = true; } }
private void addDefaultKey() { using (var db = new RecipeContext()) { Key key = new Key { Name = configuration[nameof(key.Name)], Role = configuration[nameof(key.Role)], ExpirationDate = new DateTime(2999, 12, 31) }; if (db.Keys.Where(a => a.Name == key.Name).Count() == 0) { db.Keys.Add(key); db.SaveChanges(); } } }
public async Task Test_AddRecipe() { using var context = new RecipeContext(ContextOptions); var recipeService = new RecipeService(context, _mapper, _logger); var recipe = new RecipeDTO { Name = "Chips", Ingredients = new List <IngredientDTO> { new() { Name = "Potato" }, new() { Name = "Oil" } } }; var recipeResult = await recipeService.AddRecipe(recipe); Assert.NotNull(recipeResult); Assert.Equal("Chips", recipeResult); var isItInDb = await recipeService.GetRecipeByName("Chips"); Assert.NotNull(isItInDb); Assert.Equal("Chips", isItInDb.Name); Assert.Collection(isItInDb.Ingredients, item => Assert.Equal("Potato", item.Name), item => Assert.Equal("Oil", item.Name)); }
public async Task <List <Measurement> > ExecuteAsync() { using (RecipeContext context = new RecipeContext(_appSettingsProvider.ConnectionString)) { return(await context.Measurements.ToListAsync()); } }
/* * <RedactedSiteSettings> * <SiteSettingsPart PageSize="30" /> * <CommentSettingsPart ModerateComments="true" /> * </RedactedSiteSettings> */ // Set site and part settings. public void ExecuteRecipeStep(RecipeContext recipeContext) { if (!String.Equals(recipeContext.RecipeStep.Name, "RedactedSiteSettings", StringComparison.OrdinalIgnoreCase)) { return; } _realtimeFeedbackService.Info(T("Entering the 'Redacted Site Settings' step")); var site = _siteService.GetSiteSettings(); foreach (var element in recipeContext.RecipeStep.Step.Elements()) { var partName = XmlConvert.DecodeName(element.Name.LocalName); foreach (var contentPart in site.ContentItem.Parts) { if (!String.Equals(contentPart.PartDefinition.Name, partName, StringComparison.OrdinalIgnoreCase)) { continue; } foreach (var attribute in element.Attributes()) { SetSetting(attribute, contentPart); } } } _realtimeFeedbackService.Info(T("Site settings have been updated")); recipeContext.Executed = true; }
public IActionResult Edit(int id) { var db = new RecipeContext(); var category = db.categories.Find(id); return(View(category)); }
public static void Initialize(RecipeContext context) { if (context.Recipes.Any()) { return; } var recipes = new Recipe[] { new Recipe { Name = "spaghetti", Ingredients = "water, spaghetti", Instructions = "just read the packet" }, new Recipe { Name = "meatballs", Ingredients = "microwave meal meatballs", Instructions = "read the packet and just shove it in the microwave" }, new Recipe { Name = "brownies", Ingredients = "shoes, socks, clothes, local shop", Instructions = "use google to find a local shop and go for a walk to buy some..." }, new Recipe { Name = "Chips", Ingredients = "frozen chips", Instructions = "put a portion on a baking tray in a preheated oven till browned and crispy" }, new Recipe { Name = "Pizza", Ingredients = "a smart phone, tablet, or computer", Instructions = "place an order with just eat and enjoy a nice chilled night in" }, }; foreach (Recipe recipe in recipes) { context.Recipes.Add(recipe); } context.SaveChanges(); }
public void ExecuteRecipeStepTest() { _folders.Manifests.Add("SuperWiki", @" Name: SuperWiki Version: 1.0.3 OrchardVersion: 1 Features: SuperWiki: Description: My super wiki module for Orchard. "); IShellDescriptorManager shellDescriptorManager = _container.Resolve<IShellDescriptorManager>(); // No features enabled shellDescriptorManager.UpdateShellDescriptor(0, Enumerable.Empty<ShellFeature>(), Enumerable.Empty<ShellParameter>()); ModuleRecipeHandler moduleRecipeHandler = _container.Resolve<ModuleRecipeHandler>(); RecipeContext recipeContext = new RecipeContext { RecipeStep = new RecipeStep { Name = "Module", Step = new XElement("SuperWiki") } }; recipeContext.RecipeStep.Step.Add(new XAttribute("packageId", "Orchard.Module.SuperWiki")); recipeContext.RecipeStep.Step.Add(new XAttribute("repository", "test")); IFeatureManager featureManager = _container.Resolve<IFeatureManager>(); IEnumerable<FeatureDescriptor> enabledFeatures = featureManager.GetEnabledFeatures(); Assert.That(enabledFeatures.Count(), Is.EqualTo(0)); moduleRecipeHandler.ExecuteRecipeStep(recipeContext); var availableFeatures = featureManager.GetAvailableFeatures().Where(x => x.Id == "SuperWiki").FirstOrDefault(); Assert.That(availableFeatures.Id, Is.EqualTo("SuperWiki")); Assert.That(recipeContext.Executed, Is.True); }
public IActionResult Edit(int id) { var db = new RecipeContext(); var recipe = db.recipes.Find(id); return(View(recipe)); }
/* * <EnabledFeatures> * <Feature Id="Orchard.ImportExport" /> */ //Enable any features that are in the list, disable features that aren't in the list public void ExecuteRecipeStep(RecipeContext recipeContext) { if (!String.Equals(recipeContext.RecipeStep.Name, "FeatureSync", StringComparison.OrdinalIgnoreCase)) { return; } var features = recipeContext.RecipeStep.Step.Descendants(); var featureIds = features.Where(f => f.Name == "Feature").Select(f => f.Attribute("Id").Value).ToList(); //we now have the list of features that are enabled on the remote site //next thing to do is add and remove features to and from this list based on our feature redactions var featureRedactions = _featureRedactionService.GetRedactions().ToList(); featureIds.AddRange(featureRedactions.Where(r => r.Enabled).Select(r => r.FeatureId)); //adding features that need to be enabled featureIds.RemoveAll(f => featureRedactions.Where(r => !r.Enabled).Select(r => r.FeatureId).Contains(f)); //removing features that need to be disabled //adding redactions may have caused duplicity featureIds = featureIds.Distinct().ToList(); var availableFeatures = _featureManager.GetAvailableFeatures(); var enabledFeatures = _featureManager.GetEnabledFeatures().ToList(); var featuresToDisable = enabledFeatures.Where(f => !featureIds.Contains(f.Id)).Select(f => f.Id).ToList(); var featuresToEnable = availableFeatures .Where(f => featureIds.Contains(f.Id)) //available features that are in the list of features that need to be enabled .Where(f => !enabledFeatures.Select(ef => ef.Id).Contains(f.Id)) //remove features that are already enabled .Select(f => f.Id) .ToList(); _featureManager.DisableFeatures(featuresToDisable, true); _featureManager.EnableFeatures(featuresToEnable, true); recipeContext.Executed = true; }
public void ExecuteRecipeStep(RecipeContext recipeContext) { if (!String.Equals(recipeContext.RecipeStep.Name, "Roles", StringComparison.OrdinalIgnoreCase)) { return; } var installedPermissions = _roleService.GetInstalledPermissions().SelectMany(p => p.Value).ToList(); foreach (var roleElement in recipeContext.RecipeStep.Step.Elements()) { var roleName = roleElement.Attribute("Name").Value; var role = _roleService.GetRoleByName(roleName); if (role == null) { _roleService.CreateRole(roleName); role = _roleService.GetRoleByName(roleName); } var permissions = roleElement.Attribute("Permissions").Value.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); // only import permissions for currenlty installed modules var permissionsValid = permissions.Where(permission => installedPermissions.Any(x => x.Name == permission)).ToList(); // union to keep existing permissions _roleService.UpdateRole(role.Id, role.Name, permissionsValid.Union(role.RolesPermissions.Select(p => p.Permission.Name))); } recipeContext.Executed = true; }
/* * <Command> * command1 * command2 * command3 * </Command> */ // run Orchard commands. public void ExecuteRecipeStep(RecipeContext recipeContext) { if (!String.Equals(recipeContext.RecipeStep.Name, "Command", StringComparison.OrdinalIgnoreCase)) { return; } var commands = recipeContext.RecipeStep.Step.Value .Split(new[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries) .Select(commandEntry => commandEntry.Trim()); foreach (var command in commands) { if (!String.IsNullOrEmpty(command)) { var commandParameters = _commandParser.ParseCommandParameters(command); var input = new StringReader(""); var output = new StringWriter(); _commandManager.Execute(new CommandParameters { Arguments = commandParameters.Arguments, Input = input, Output = output, Switches = commandParameters.Switches }); } } recipeContext.Executed = true; }
public static void EnsureDatabaseSeeded(this RecipeContext context) { context.Database.Migrate(); var rp1 = new Recipe() { RecipeId = 1, Name = "Pasta", Description = "Pasta med kødsovs", Ingrediens = "Pasta", }; var rp2 = new Recipe() { RecipeId = 2, Name = "Pizza", Description = "Pizza med skinke og ost", Ingrediens = "Dej, ost, skinke", }; var rp3 = new Recipe() { RecipeId = 3, Name = "Rugbrød", Description = "Rugbrød med hamburgeryg", Ingrediens = "Rugbrød, smør, hamburgeryg", }; context.Add(rp1); context.Add(rp2); context.Add(rp3); context.SaveChanges(); }
public static void Initialize(IServiceProvider serviceProvider) { using (var context = new RecipeContext( serviceProvider.GetRequiredService < DbContextOptions <RecipeContext> >())) { // Look for any movies. if (context.Recipe.Any()) { return; // DB has been seeded } context.Recipe.AddRange( new Recipe { Name = "When Harry Met Sally", Time = 30, Difficulty = "4", NumberOfLikes = 24, Ingredients = "apple, egg", Process = "123", TipsAndTricks = "..." }, new Recipe { Name = "Ghostbusters ", Time = 30, Difficulty = "4", NumberOfLikes = 24, Ingredients = "apple, egg", Process = "123", TipsAndTricks = "..." }, new Recipe { Name = "Ghostbusters 2", Time = 30, Difficulty = "4", NumberOfLikes = 24, Ingredients = "apple, egg", Process = "123", TipsAndTricks = "..." }, new Recipe { Name = "Rio Bravo", Time = 30, Difficulty = "4", NumberOfLikes = 24, Ingredients = "apple, egg", Process = "123", TipsAndTricks = "..." } ); context.SaveChanges(); } }
// <Data /> // Import Data public void ExecuteRecipeStep(RecipeContext recipeContext) { if (!String.Equals(recipeContext.RecipeStep.Name, "Rules", StringComparison.OrdinalIgnoreCase)) { return; } foreach (var rule in recipeContext.RecipeStep.Step.Elements()) { var ruleRecord = _rulesServices.CreateRule(rule.Attribute("Name").Value); ruleRecord.Enabled = bool.Parse(rule.Attribute("Enabled").Value); ruleRecord.Actions = rule.Element("Actions").Elements().Select(action => new ActionRecord { Type = action.Attribute("Type").Value, Category = action.Attribute("Category").Value, Position = int.Parse(action.Attribute("Position").Value), Parameters = action.Attribute("Parameters").Value, RuleRecord = ruleRecord }).ToList(); ruleRecord.Events = rule.Element("Events").Elements().Select(action => new EventRecord { Type = action.Attribute("Type").Value, Category = action.Attribute("Category").Value, Parameters = action.Attribute("Parameters").Value, RuleRecord = ruleRecord }).ToList(); } recipeContext.Executed = true; }
public RecipeRepository(RecipeContext context) { _context = context; }
public CategoryRepository(RecipeContext context) { _context = context; }