Beispiel #1
0
 public GenericRepository(RepoContext context, IPrincipalSecurityConcern security)
 {
     _context  = context;
     _dbSet    = context.Set <TModel>();
     _dbQuery  = context.Set <TModel>();
     _security = security;
 }
Beispiel #2
0
        public OutMessage Scope([Protect(UserScope.Admin)] Chat chat, User user, UserScope scope)
        {
            var me        = Context.GetMember(null, chat);
            var target    = Context.GetMember(user, chat);
            var localizer = Context.GetLocalizer();

            if (target == null)
            {
                return(OutMessage.FromCode(localizer["TargetNotFound"]));
            }
            if (!Context.GetUser().IsSuperUser &&
                (me.Scope < target.Scope ||
                 (me.Scope != UserScope.Owner &&
                  target.Scope >= UserScope.Admin &&
                  scope >= UserScope.Admin)))
            {
                return(OutMessage.FromCode(localizer["AccessDenied"]));
            }
            var db = new RepoContext();

            target.Scope = scope;
            db.Update(target);
            db.SaveChanges();
            return(OutMessage.FromCode(localizer["UserScopeUpdated"]));
        }
Beispiel #3
0
        public Task Consume(ConsumeContext <SaveData> context)
        {
            SaveData dataToSave = context.Message;

            using (var repoContext = new RepoContext())
            {
                foreach (var repo in context.Message.Repos)
                {
                    var original = repoContext.Repos.FirstOrDefault(r => r.full_name == repo.full_name);

                    if (original == null)
                    {
                        repoContext.Repos.Add(repo);
                    }
                    else
                    {
                        repo.id = original.id;
                        repoContext.Entry(original).CurrentValues.SetValues(repo);
                    }
                }

                repoContext.SaveChanges();
            }

            Console.WriteLine("Repos have been saved with the latest data. Details: ");
            Console.WriteLine("Count: " + dataToSave.Repos.Count);

            return(Task.FromResult(context.Message));
        }
Beispiel #4
0
        public async Task UpdateHostTest()
        {
            var e = new WatchEntity
            {
                Emails = Guid.NewGuid().ToString(),
                Host   = Guid.NewGuid().ToString(),
                PingIntervalSeconds = 5
            };
            await RepoContext.Insert(e);

            var e2 = new WatchEntity
            {
                WatchId             = e.WatchId,
                Emails              = Guid.NewGuid().ToString(),
                Host                = Guid.NewGuid().ToString(),
                PingIntervalSeconds = 2
            };

            await RepoContext.Update(e2);

            var e3 = await RepoContext.GetItem(e.WatchId);

            Assert.AreEqual(e.WatchId, e3.WatchId);
            Assert.AreEqual(e2.Emails, e3.Emails, "email does not match");
            Assert.AreEqual(e2.Host, e3.Host);
            Assert.AreEqual(e2.PingIntervalSeconds, e3.PingIntervalSeconds);
        }
Beispiel #5
0
        public OutMessage Notifications([Protect(UserScope.Admin)] Chat chat, bool value)
        {
            var db        = new RepoContext();
            var localizer = Context.GetLocalizer();

            chat.Notifications = value;
            db.Update(chat);
            db.SaveChanges();

            return(OutMessage.FromCode(value ? localizer["NotificationsEnabled"] : localizer["NotificationsDisabled"]));
        }
Beispiel #6
0
        public static ChatMember GetMember(this Context context, User user = null, Chat chat = null)
        {
            user ??= context.GetUser();
            chat ??= context.GetChat();
            if (user == null || chat == null)
            {
                return(null);
            }
            var db = new RepoContext();

            return(db.ChatMembers.FirstOrDefault(x => x.ChatId == chat.Id && x.UserId == user.Id));
        }
        public Meetings GetByID(int Id)
        {
            Meetings meeting = RepoContext.Meetings.FirstOrDefault(x => x.Id == Id);

            meeting.AttendeesIds = RepoContext.AttendeeMeeting.Where(x => x.MeetingId == Id).Select(attendee_meeting => attendee_meeting.AttendeeId).ToList();
            if (meeting != null)
            {
                RepoContext.Entry(meeting).State = EntityState.Detached;
                return(meeting);
            }
            return(null);
        }
Beispiel #8
0
        public MessageBuilder Desync([Protect(UserScope.Owner)] Route route)
        {
            var db        = new RepoContext();
            var localizer = Context.GetLocalizer();
            var routeS    = route.ToString();

            db.Remove(route);
            db.SaveChanges();
            return(new MessageBuilder()
                   .Set(MessageFlags.Code)
                   .AddText(localizer["RouteDestroyed"])
                   .AddText(routeS));
        }
Beispiel #9
0
        public async Task <OutMessage> Init()
        {
            var localizer = Context.GetLocalizer();
            var chat      = Context.GetChat();
            var db        = new RepoContext();

            if (chat != null)
            {
                return(OutMessage.FromCode(localizer["ChatAlreadyInitialized"]));
            }

            chat = new Chat
            {
                Controller    = Controller.Name,
                ChatId        = Message.Chat.Id,
                Language      = Message.Sender.Language,
                Notifications = true
            };
            db.Update(chat);
            db.SaveChanges();

            var user = Context.GetUser();

            var result = $"{localizer["ChatInitialized"]}";

            var info = await Controller.GetChatInfo(chat.ChatId);

            if (info.Owner == 0)
            {
                user.AssignPermissions(chat, UserScope.Owner);
                result += $"\n{user.Username} {localizer["AssignedAsOwner"]}\n{localizer["UnableToAssignOwner"]}";
                return(OutMessage.FromCode(result));
            }

            var uinfo = await Controller.GetUserInfo(info.Owner);

            var owner = User.EnsureCreated(Controller.Name, uinfo);

            owner.AssignPermissions(chat, UserScope.Owner);

            if (owner.Id == user.Id)
            {
                result += $"\n{user.Username} {localizer["AssignedAsOwner"]}";
                return(OutMessage.FromCode(result));
            }

            user.AssignPermissions(chat, UserScope.Admin);

            result += $"\n{user.Username} {localizer["AssignedAsAdmin"]}\n{owner.Username} {localizer["AssignedAsOwner"]}";
            return(OutMessage.FromCode(result));
        }
Beispiel #10
0
        public MessageBuilder Sync([MinLength(2)][Protect(UserScope.Admin)] params Chat[] chats)
        {
            var db = new RepoContext();

            var user = Context.GetUser();

            var(created, route) = Route.Sync(user, chats.Distinct().ToArray());
            var localizer = Context.GetLocalizer();

            return(new MessageBuilder()
                   .Set(MessageFlags.Code)
                   .AddText(created ? localizer["RouteInitialized"] : localizer["RouteUpdated"])
                   .AddText(route.ToString()));
        }
Beispiel #11
0
        public async Task WriteReadHostTests()
        {
            var e = new WatchEntity {
                WatchId             = Guid.NewGuid(),
                Emails              = Guid.NewGuid().ToString(),
                Host                = Guid.NewGuid().ToString(),
                PingIntervalSeconds = 1000
            };
            var result = await RepoContext.AddAsync(e);

            await RepoContext.SaveChangesAsync();

            Assert.AreEqual(e.WatchId, result.Entity.WatchId);
        }
Beispiel #12
0
        public OutMessage Routes(int?page = null)
        {
            var db = new RepoContext();

            if (!page.HasValue)
            {
                var count = db.Routes.Count();
                return(OutMessage.FromCode($"Found {count} routes and {(count / 20) + 1} pages"));
            }
            var localizer = Context.GetLocalizer();
            var routes    = db.Routes.Skip(page.Value * 20).Take(20).ToList();

            return(OutMessage.FromCode($"{localizer["Routes"]} [{page}]:\n" + string.Join("\n", routes.Select(x => x.RenderInfo()))));
        }
Beispiel #13
0
        public async Task <OutMessage> Chats(int?page = null)
        {
            var db = new RepoContext();

            if (!page.HasValue)
            {
                var count = db.Chats.Count();
                return(OutMessage.FromCode($"Found {count} chats and {(count / 20) + 1} pages"));
            }
            var localizer = Context.GetLocalizer();
            var chats     = db.Chats.Skip(page.Value * 20).Take(20).ToList();

            return(OutMessage.FromCode($"{localizer["Chats"]} [{page}]:\n" + string.Join("\n",
                                                                                         await chats.SelectAsync(async x => $"[{x.FormattedId}] [{x.Controller}] {(await x.GetInfo()).Title}"))));
        }
Beispiel #14
0
        // public void Info(User user = null)
        //     => this.EnterView("user", user ?? Context.GetUser());

        public OutMessage Mute(Chat chat = null)
        {
            var me        = Context.GetMember(null, chat);
            var localizer = Context.GetLocalizer();

            if (me.Mute > MuteState.None)
            {
                return(OutMessage.FromCode(localizer["YouAlreadyMuted"]));
            }
            var db = new RepoContext();

            me.Mute = MuteState.Muted;
            db.Update(me);
            db.SaveChanges();
            return(OutMessage.FromCode(localizer["YouMuted"]));
        }
Beispiel #15
0
        public OutMessage Destroy([Protect(UserScope.Owner)] Chat chat = null)
        {
            var localizer = Context.GetLocalizer();
            var db        = new RepoContext();

            chat ??= Context.GetChat();
            if (chat == null)
            {
                return(OutMessage.FromCode(localizer["ChatNotFound"]));
            }
            var routes = chat.Routes.Select(x => x.Route).ToList();

            db.Remove(chat);
            db.SaveChanges();
            routes.ForEach(x => x.DeleteIfNotUsed());
            return(OutMessage.FromCode(localizer["ChatDestroyed"]));
        }
Beispiel #16
0
        public OutMessage Unmute([Protect(UserScope.Moderator)] Chat chat, User user)
        {
            var localizer = Context.GetLocalizer();
            var target    = Context.GetMember(user, chat);

            if (target == null)
            {
                return(OutMessage.FromCode(localizer["TargetNotFound"]));
            }

            var db = new RepoContext();

            target.Mute = MuteState.None;
            db.Update(target);
            db.SaveChanges();
            return(OutMessage.FromCode(localizer["UserUnmuted"]));
        }
Beispiel #17
0
        public Task Consume(ConsumeContext <ListRepos> context)
        {
            Console.WriteLine("The following repositories are in the database: ");
            Console.WriteLine();

            using (var repoContext = new RepoContext())
            {
                foreach (var repo in repoContext.Repos)
                {
                    var row = RepoToString(repo);

                    Console.WriteLine(row);
                }
            }

            return(Task.FromResult(context.Message));
        }
Beispiel #18
0
        public override string TryConvert(Context context, string origin, out Route result)
        {
            var localizer = context.GetLocalizer();

            if (int.TryParse(origin, out var id))
            {
                var db = new RepoContext();
                result = db.Routes.Find(id);
                if (result == null)
                {
                    return(localizer["RouteNotFound"]);
                }
                var user = context.GetUser();
                return(null);
            }
            result = null;
            return(localizer["ChatIdExpected"]);
        }
        public bool Update(Meetings mtng)
        {
            Meetings oldMeetingdata = GetByID(mtng.Id);

            if (oldMeetingdata != null)
            {
                RepoContext.AttendeeMeeting.RemoveRange(RepoContext.AttendeeMeeting.Where(x => x.MeetingId == oldMeetingdata.Id));
                RepoContext.AttendeeMeeting.AddRange(mtng.AttendeesIds.Select(id => new AttendeeMeeting {
                    AttendeeId = id, MeetingId = mtng.Id
                }));
                oldMeetingdata.Subject    = mtng.Subject;
                oldMeetingdata.UpdateDate = DateTime.Now;
                oldMeetingdata.Agenda     = mtng.Agenda;
                oldMeetingdata.DateTime   = mtng.DateTime;
            }

            RepoContext.Entry(oldMeetingdata).State = EntityState.Modified;
            RepoContext.SaveChanges();

            return(true);
        }
Beispiel #20
0
        public override string TryConvert(Context context, string origin, out User user)
        {
            var db        = new RepoContext();
            var localizer = context.GetLocalizer();

            if (!int.TryParse(origin, out var id))
            {
                user = db.Users.FirstOrDefault(x => x.Username == origin);
                if (user == null)
                {
                    return(localizer["UserNotFound"]);
                }
                return(null);
            }
            user = db.Users.FirstOrDefault(x => x.Id == id || x.Accounts.Exists(y => y.UserId == id));
            if (user == null)
            {
                return(localizer["UserNotFound"]);
            }
            return(null);
        }
Beispiel #21
0
        public override string TryConvert(Context context, string origin, out Chat result)
        {
            if (origin == "this" || origin == "here")
            {
                result = context.GetChat();
                return(null);
            }
            var localizer = context.GetLocalizer();

            if (int.TryParse(origin, out var id))
            {
                var db = new RepoContext();
                result = db.Chats.Find(id);
                if (result == null)
                {
                    return(localizer["ChatNotFound"]);
                }
                return(null);
            }
            result = null;
            return(localizer["ChatIdExpected"]);
        }
Beispiel #22
0
        public OutMessage Unmute(Chat chat = null)
        {
            var me        = Context.GetMember(null, chat);
            var localizer = Context.GetLocalizer();

            if (me.Mute == MuteState.Blocked)
            {
                return(OutMessage.FromCode(localizer["CantUnmute"]));
            }

            if (me.Mute == MuteState.None)
            {
                return(OutMessage.FromCode(localizer["NotMuted"]));
            }

            var db = new RepoContext();

            me.Mute = MuteState.None;
            db.Update(me);
            db.SaveChanges();
            return(OutMessage.FromCode(localizer["YouUnmuted"]));
        }
Beispiel #23
0
        public async Task DeleteHostTests()
        {
            var e = new WatchEntity
            {
                WatchId             = Guid.NewGuid(),
                Emails              = Guid.NewGuid().ToString(),
                Host                = Guid.NewGuid().ToString(),
                PingIntervalSeconds = 1000
            };

            var result = await RepoContext.AddAsync(e);

            await RepoContext.SaveChangesAsync();

            Assert.AreEqual(e.WatchId, result.Entity.WatchId);

            await RepoContext.Remove(e.WatchId);

            var e2 = await RepoContext.GetItem(e.WatchId);

            Assert.IsNull(e2);
        }
Beispiel #24
0
        public OutMessage CreateChat(string controller, long chatId, User owner = null)
        {
            var db = new RepoContext();

            if (db.Chats.Any(x => x.ChatId == chatId && x.Controller == controller))
            {
                return(OutMessage.FromCode("Already exists"));
            }
            owner ??= Context.GetUser();
            var chat = new Chat {
                Controller = controller, ChatId = chatId
            };
            var member = new ChatMember
            {
                Scope = UserScope.Owner,
                User  = owner,
                Chat  = chat
            };

            db.Update(member);
            db.SaveChanges();
            return(OutMessage.FromCode("Chat created " + chat.Id));
        }
Beispiel #25
0
 public ListItems(RepoContext context)
 {
     _context = context;
 }
Beispiel #26
0
 public AuthRepository(RepoContext context)
 {
     _context = context;
 }
Beispiel #27
0
 public RepositoryWrapper(RepoContext context)
 {
     _repoContext = context;
 }
Beispiel #28
0
 public RegionRepo(RepoContext context)
     : base(context)
 {
 }
 public LookupRepository(RepoContext context, IMapper mapper)
 {
     _context = context;
     _mapper  = mapper;
 }
 public AccountRepository(RepoContext repoContext) : base(repoContext)
 {
 }
Beispiel #31
0
        public static void SeedSoupDataIfNotExists(RepoContext context)
        {
            SoupRecipe recipe = context.SoupRecipes.Where(w => w.RecipeName == "French Onion Soup").FirstOrDefault();
            if (recipe == null)
            {
                //Source: http://www.foodnetwork.com/recipes/tyler-florence/french-onion-soup-recipe2/index.html
                recipe = new SoupRecipe()
                {
                    RecipeName = "French Onion Soup",
                    PrepTime = "15 min",
                    CookTime = "55 min",
                    PrepInstructions = @"Melt the stick of butter in a large pot over medium heat. Add the onions, garlic, bay leaves, thyme, and salt and pepper and cook until the onions are very soft and caramelized, about 25 minutes. Add the wine, bring to a boil, reduce the heat and simmer until the wine has evaporated and the onions are dry, about 5 minutes. Discard the bay leaves and thyme sprigs. Dust the onions with the flour and give them a stir. Turn the heat down to medium low so the flour doesn't burn, and cook for 10 minutes to cook out the raw flour taste. Now add the beef broth, bring the soup back to a simmer, and cook for 10 minutes. Season, to taste, with salt and pepper.

            When you're ready to eat, preheat the broiler. Arrange the baguette slices on a baking sheet in a single layer. Sprinkle the slices with the Gruyere and broil until bubbly and golden brown, 3 to 5 minutes.

            Ladle the soup in bowls and float several of the Gruyere croutons on top.

            Alternative method: Ladle the soup into bowls, top each with 2 slices of bread and top with cheese. Put the bowls into the oven to toast the bread and melt the cheese.
            ",
                    NumOfServings = "4 to 6",
                    Ingredients = new List<RecipeIngredient>()
                    {
                        new RecipeIngredient()
                        {
                            Name = "Unsalted butter",
                            Quantity = "1/2 cup"
                        },
                        new RecipeIngredient()
                        {
                            Name = "Onions, sliced",
                            Quantity = "4"
                        },
                        new RecipeIngredient()
                        {
                            Name = "garlic cloves, chopped",
                            Quantity = "2"
                        },
                        new RecipeIngredient()
                        {
                            Name = "bay leaves",
                            Quantity = "2"
                        },
                        new RecipeIngredient()
                        {
                            Name = "fresh thyme sprigs",
                            Quantity = "2"
                        },
                        new RecipeIngredient()
                        {
                            Name = "Kosher salt and freshly ground black pepper",
                            Quantity = "To Taste"
                        },
                        new RecipeIngredient()
                        {
                            Name = "red wine",
                            Quantity = "1/2 Cup"
                        },
                        new RecipeIngredient()
                        {
                            Name = "all-purpose flour",
                            Quantity = "3 heaping tablespoons "
                        },
                        new RecipeIngredient()
                        {
                            Name = "beef broth",
                            Quantity = "2 quarts"
                        },
                        new RecipeIngredient()
                        {
                            Name = "baguette, sliced",
                            Quantity = "1"
                        },
                        new RecipeIngredient()
                        {
                            Name = "grated Gruyere",
                            Quantity = "1/2 pound"
                        },
                    }

                };
                context.SoupRecipes.Add(recipe);
            }

            context.SaveChanges();
        }