Beispiel #1
0
        public void AddOrUpdateBlogPost(Post post, LunarUser user)
        {
            try
            {
                AddOrUpdateChildEntities(post);

                if (_context.Posts.Any(x => x.Id == post.Id))
                {
                    _context.Posts.Attach(post);
                    var oldPost = _context.Posts.FirstOrDefault(x => x.Id == post.Id);

                    //Almost there!!!!!!!!!! PostTags Not updating.
                    oldPost.PostTags = post.PostTags;
                    oldPost.Images   = post.Images;
                    oldPost.PostedBy = user;
                    oldPost.Modified = DateTime.Now;
                    _context.Posts.Update(oldPost);
                }
                else
                {
                    post.PostedBy = user;
                    post.PostedOn = DateTime.Now;
                    _context.Posts.Add(post);
                }


                _context.SaveChanges();
            }
            catch (Exception ex)
            {
                _logger.LogError($"Error", ex);
                throw ex;
            }
        }
 /// <summary>
 /// Executes the core work of the command.
 /// </summary>
 /// <param name="parameters">Any required parameters for this command.</param>
 /// <returns>A message to respond to the user with.</returns>
 protected override string Work(LunarUser sender, object[] parameters)
 {
     // In this sample, the user will ask us a question.
     // We don't really care what the question is.
     // We just need to return a random answer.
     return(_answers[_random.Next(0, _answers.Length - 1)]);
 }
 /// <summary>
 /// Executes the core work of the command.
 /// </summary>
 /// <param name="parameters">Any required parameters for this command.</param>
 /// <returns>A message to respond to the user with.</returns>
 protected override string Work(LunarUser sender, object[] parameters)
 {
     // In this sample, we're going to square and sum two parameters.
     // This sample only supports two parameters, no more, no less.
     if (parameters.Length != 2)
     {
         return($"The required number of parameters supplied to `{Key}` command was invalid.");
     }
     else
     {
         // Attempt to parse the first parameter.
         if (double.TryParse(parameters[0].ToString(), out double a))
         {
             // Attempt to parse the second parameter.
             if (double.TryParse(parameters[1].ToString(), out double b))
             {
                 // Return a message with the sum of a^2 and b^2.
                 return($"The sum of the squares of `{a}` and `{b}` is: {(a * a + b * b)}");
             }
             else
             {
                 return($"The second supplied parameter `{parameters[1]}` was invalid.");
             }
         }
         else
         {
             return($"The first supplied parameter `{parameters[0]}` was invalid.");
         }
     }
 }
        /// <summary>
        /// Executes the core work of the command and builds an embed object for Discord to consume.
        /// </summary>
        /// <param name="parameters">Any required parameters for this command.</param>
        /// <returns>An embed object for Discord consumption.</returns>
        protected override Embed WorkEmbed(LunarUser sender, object[] parameters)
        {
            EmbedBuilder embedBuilder = new EmbedBuilder();

            embedBuilder.Description  = _responseMessage;
            embedBuilder.Color        = Color.Purple;
            embedBuilder.ThumbnailUrl = "https://assets.codepen.io/2940219/Code+Brackets+and+Moon+%28Transparent%29.png";
            return(embedBuilder.Build());
        }
Beispiel #5
0
 /// <summary>
 /// Executes the core work of the command.
 /// </summary>
 /// <param name="parameters">Any required parameters for this command.</param>
 /// <returns>A message to respond to the user with.</returns>
 protected override string Work(LunarUser sender, object[] parameters)
 {
     // In this sample, we want to simply return what the user supplied.
     if (parameters.Length >= 1)
     {
         return(string.Join(" ", parameters));
     }
     else if (parameters.Length == 0)
     {
         return(parameters[0].ToString());
     }
     else
     {
         return("No input provided to echo.");
     }
 }
 /// <summary>
 /// Executes the core work of the command and builds an embed object for Discord to consume.
 /// </summary>
 /// <param name="parameters">Any required parameters for this command.</param>
 /// <returns>An embed object for Discord consumption.</returns>
 protected override Embed WorkEmbed(LunarUser sender, object[] parameters)
 {
     try {
         if (parameters.Length > 0)
         {
             string searchTerm = parameters[0].ToString();
             string result     = BasicWebServiceHelper.CallWebService($"https://api.giphy.com/v1/gifs/random?api_key=FSTxSjTCxxNkbiGenZrBpTzq6S3p2Y3q&tag={searchTerm}&rating=r");
             Dictionary <string, Dictionary <string, object> > data = JsonConvert.DeserializeObject <Dictionary <string, Dictionary <string, object> > >(result);
             EmbedBuilder embedBuilder = new EmbedBuilder();
             embedBuilder.ImageUrl    = data["data"]["image_original_url"].ToString();
             embedBuilder.Description = "Here's that GIF you requested!";
             embedBuilder.Color       = Color.Purple;
             return(embedBuilder.Build());
         }
     } catch { }
     return(null);
 }
        /// <summary>
        /// Executes the core work of the command.
        /// </summary>
        /// <param name="parameters">Any required parameters for this command.</param>
        /// <returns>A message to respond to the user with.</returns>
        protected override string Work(LunarUser sender, object[] parameters)
        {
            int result = _random.Next(1, 12000);

            if (result <= 5999)
            {
                return("Heads.");
            }
            else if (result <= 11998)
            {
                return("Tails.");
            }
            else
            {
                return("It's a draw!");
            }
        }
Beispiel #8
0
        public async Task <IActionResult> Register(RegisterViewModel model, IFormFile profileImage, string returnUrl = null)
        {
            ViewData["ReturnUrl"] = returnUrl;
            if (ModelState.IsValid)
            {
                var user = new LunarUser {
                    UserName = model.UserName, Email = model.Email, FirstWords = model.FirstWords
                };
                var image = new Image {
                    File = profileImage
                };
                var fileName  = ContentDispositionHeaderValue.Parse(image.File.ContentDisposition).FileName.Trim('"');
                var container = _cloudService.GetStorageContainer("profileimages");
                await image.File.SaveInAzureAsync(container, fileName);

                user.ProfileImage = new ImageDescription
                {
                    ContainerName    = container.Name,
                    ContentType      = image.File.ContentType,
                    CreatedTimestamp = DateTime.Now,
                    Description      = image.Id,
                    FileName         = image.File.FileName
                };

                var result = await _userManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    //await _signInManager.SignInAsync(user, isPersistent: false);

                    // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                    // Send an email with this link
                    string code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    var callbackUrl = Url.Action("ConfirmEmail", "Auth", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
                    await _emailService.SendEmailAsync(model.Email, _authMail, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                    return(View("RegisterConfirmation", model.Email));
                }

                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
        protected override Embed WorkEmbed(LunarUser sender, object[] parameters)
        {
            Dictionary <string, object> drinkData = GetRandomDrink();

            List <string> ingredients = new List <string>();

            for (int i = 1; i < 15; i++)
            {
                string measurement = drinkData[$"strMeasure{i}"]?.ToString();
                string ingredient  = drinkData[$"strIngredient{i}"]?.ToString();
                string result      = $"{(string.IsNullOrWhiteSpace(measurement) ? string.Empty : measurement)} {(string.IsNullOrWhiteSpace(ingredient) ? string.Empty : ingredient)}";
                if (!string.IsNullOrWhiteSpace(result))
                {
                    ingredients.Add(result);
                }
            }

            EmbedAuthorBuilder authorBuilder = new EmbedAuthorBuilder();

            authorBuilder.Name = "The Cocktail DB";
            authorBuilder.Url  = "https://www.thecocktaildb.com/api.php";

            EmbedFooterBuilder footerBuilder = new EmbedFooterBuilder();

            footerBuilder.Text = drinkData["strAlcoholic"].ToString();

            EmbedBuilder embedBuilder = new EmbedBuilder();

            embedBuilder.ThumbnailUrl = drinkData["strDrinkThumb"].ToString();
            embedBuilder.ImageUrl     = "https://www.thecocktaildb.com/images/logo.png";
            embedBuilder.Author       = authorBuilder;
            embedBuilder.Footer       = footerBuilder;
            embedBuilder.Color        = Color.Purple;
            embedBuilder.Description  = $@"{drinkData["strDrink"]}
**Ingredients**:
```{string.Join(Environment.NewLine, ingredients.ToArray())}```
**Instructions**:
{drinkData["strInstructions"]}";

            return(embedBuilder.Build());
        }
        protected override Embed WorkEmbed(LunarUser sender, object[] parameters)
        {
            Dictionary <string, double> globalStats   = GetCovidSummary();
            EmbedAuthorBuilder          authorBuilder = new EmbedAuthorBuilder();

            authorBuilder.Name = "Global COVID-19 Statistics";
            authorBuilder.Url  = "https://covid19api.com/";

            EmbedFooterBuilder footerBuilder = new EmbedFooterBuilder();

            footerBuilder.Text = "Data sourced from COVID-19 API.";

            List <EmbedFieldBuilder> fields = new List <EmbedFieldBuilder>();

            fields.Add(new EmbedFieldBuilder()
            {
                Name  = "Cases",
                Value = $"There are **{globalStats["NewConfirmed"]:N0}** new of **{globalStats["TotalConfirmed"]:N0}** total."
            });
            fields.Add(new EmbedFieldBuilder()
            {
                Name  = "Deaths",
                Value = $"There are **{globalStats["NewDeaths"]:N0}** new of **{globalStats["TotalDeaths"]:N0}** total."
            });
            fields.Add(new EmbedFieldBuilder()
            {
                Name  = "Recoveries",
                Value = $"There are **{globalStats["NewRecovered"]:N0}** new of **{globalStats["TotalRecovered"]:N0}** total."
            });

            EmbedBuilder embedBuilder = new EmbedBuilder();

            embedBuilder.Color        = Color.Red;
            embedBuilder.ThumbnailUrl = "https://styles.redditmedia.com/t5_2f4l19/styles/communityIcon_s9svsk6xmcg41.jpg?width=256&format=pjpg&s=bcbf2d8ea8657792d0ebe9eed38ce729d874d5b5";
            embedBuilder.Timestamp    = DateTime.UtcNow;
            embedBuilder.Author       = authorBuilder;
            embedBuilder.Fields       = fields;
            embedBuilder.Footer       = footerBuilder;
            return(embedBuilder.Build());;
        }
 /// <summary>
 /// Executes the core work of the command.
 /// </summary>
 /// <param name="parameters">Any required parameters for this command.</param>
 /// <returns>A message to respond to the user with.</returns>
 protected override string Work(LunarUser sender, object[] parameters) => RandomHelper.GetRandomValue(Flavors);
 /// <summary>
 /// Executes the core work of the command.
 /// </summary>
 /// <param name="parameters">Any required parameters for this command.</param>
 /// <returns>A message to respond to the user with.</returns>
 protected override string Work(LunarUser sender, object[] parameters)
 {
     // In this sample, we don't require any parameters.
     // We're simply going to say hello.
     return("Hello World!");
 }
        protected override string Work(LunarUser sender, object[] parameters)
        {
            Dictionary <string, object> drinkData = GetRandomDrink();

            return($"You should drink a {drinkData["strDrink"]}.");
        }
 /// <summary>
 /// Executes the core work of the command.
 /// </summary>
 /// <param name="parameters">Any required parameters for this command.</param>
 /// <returns>A message to respond to the user with.</returns>
 protected override string Work(LunarUser sender, object[] parameters) => Prefabs.NotSupportedOutsideOfDiscord;
Beispiel #15
0
        public async Task EnsureSeedDataAsync()
        {
            if (await _userManager.FindByEmailAsync("*****@*****.**") == null)
            {
                var user = new LunarUser
                {
                    Email          = "*****@*****.**",
                    FirstWords     = "Every one needs a hobby",
                    UserName       = "******",
                    EmailConfirmed = true
                };

                await _userManager.CreateAsync(user, "P@ssw0rd!");
            }

            if (!_context.Posts.Any())
            {
                var sampleTags = new List <Tag>
                {
                    new Tag {
                        Description = "About Travel", Name = "Travel", UrlSlug = "travel"
                    },
                    new Tag {
                        Description = "About Careers", Name = "Career", UrlSlug = "career"
                    },
                    new Tag {
                        Description = "About Programming", Name = "Programming", UrlSlug = "programming"
                    },
                    new Tag {
                        Description = "About Lifestyle", Name = "Lifestyle", UrlSlug = "lifestyle"
                    },
                    new Tag {
                        Description = "About ASP.NET", Name = "ASP.NET", UrlSlug = "asp_net"
                    },
                };

                var sampleCategory = new Category
                {
                    Description = "Some posts about Home Improvement",
                    Name        = "Home Improvement",
                    UrlSlug     = "home_improvement"
                };

                var sampleCategory2 = new Category
                {
                    Description = "Some posts about Software Development",
                    Name        = "Software Development",
                    UrlSlug     = "software_development"
                };

                var samplePosts = new List <Post>
                {
                    new Post {
                        Title            = "Building this site",
                        UrlSlug          = "building_this_site",
                        Description      = "Step by step process of builing this site.",
                        Category         = sampleCategory2,
                        Meta             = "mvc, asp.net",
                        Published        = true,
                        ShortDescription = "Step by Step process about building the site.",
                        PostedOn         = DateTime.Today,
                        PostTags         = new List <PostTag>
                        {
                            new PostTag {
                                Tag = sampleTags.FirstOrDefault()
                            },
                            new PostTag {
                                Tag = sampleTags.LastOrDefault()
                            }
                        },
                        PostedBy = await _userManager.FindByEmailAsync("*****@*****.**")
                    }
                };

                _context.Tags.AddRange(sampleTags);
                _context.Categories.AddRange(sampleCategory, sampleCategory2);
                _context.Posts.AddRange(samplePosts);

                await _context.SaveChangesAsync();
            }
        }
 /// <summary>
 /// Executes the core work of the command.
 /// </summary>
 /// <param name="parameters">Any required parameters for this command.</param>
 /// <returns>A message to respond to the user with.</returns>
 protected override string Work(LunarUser sender, object[] parameters) => _responseMessage;
 /// <summary>
 /// Executes the core work of the command.
 /// </summary>
 /// <param name="parameters">Any required parameters for this command.</param>
 /// <returns>A message to respond to the user with.</returns>
 protected override string Work(LunarUser sender, object[] parameters) => $"On this day in history: {GetRandomHistoryFact()}";
        protected override string Work(LunarUser sender, object[] parameters)
        {
            Dictionary <string, double> globalStats = GetCovidSummary();

            return($@"There are {globalStats["NewConfirmed"].ToString("N")} new cases out of {globalStats["TotalConfirmed"].ToString("N")} total. There are {globalStats["NewDeaths"].ToString("N")} new cases out of {globalStats["TotalDeaths"].ToString("N")} total. There are {globalStats["NewRecovered"].ToString("N")} new cases out of {globalStats["TotalRecovered"].ToString("N")} total. - Data sourced from COVID-19 API.");
        }