public void UpdateManyToMany_NoExisting_AddedElements()
        {
            using (var transaction = connection.BeginTransaction())
            {
                parent = new ParentClass();
                connection.Save(parent);

                var newChildren = new[] { new ChildDto {
                                              Test = "First"
                                          }, new ChildDto {
                                              Test = "Second"
                                          } };
                connection.UpdateManyToMany(parent, parent.Children, newChildren, mapper);

                connection.Cache.Clear();

                var newParent = connection.Load <ParentClass>(parent.Id);

                Assert.Equal(2, newParent.Children.Count);
                var children = newParent.Children;
                Assert.True(children.Any(c => c.Child.Test == "First"));
                Assert.True(children.Any(c => c.Child.Test == "Second"));
                transaction.Rollback();
            }
        }
Ejemplo n.º 2
0
        public async Task <IEnumerable <ChatView <TUserView> > > GetAll([FromQuery] int offset = 0)
        {
            var account = await userService.GetCurrentUserAsync();

            if (account != null && offset == 0)
            {
                using (var transaction = session.BeginTransaction())
                {
                    var myLastChat = await queryLastChatViewByAccount.Build(session, account).FirstOrDefaultAsync();

                    var lastChat = await queryLastChats.Build(session).FirstOrDefaultAsync();

                    if (myLastChat == null)
                    {
                        myLastChat = new LastChatView <TUser> {
                            Account = account, Chat = lastChat
                        };
                        await session.SaveAsync(myLastChat);

                        transaction.Commit();
                    }
                    else if (lastChat != myLastChat.Chat)
                    {
                        myLastChat.Chat = lastChat;
                        await session.UpdateAsync(myLastChat);

                        transaction.Commit();
                    }
                }
            }
            return((await queryChats.Build(session, offset).ToListAsync()).Select(c => chatDataMapping.ToChatDto(c)));
        }
Ejemplo n.º 3
0
        public async Task <CommentView <TUserView> > PostComment(TUser account, int newsId, CommentView <TUserView> value)
        {
            if (account == null)
            {
                return(null);
            }
            using (var transaction = session.BeginTransaction())
            {
                var news = await session.LoadAsync <TThread>(newsId);

                var comment = new Comment <TUser> {
                    Author = account, Text = value.Text, CreationDate = DateTime.UtcNow
                };
                await session.SaveAsync(comment);

                news.NumberOfComments++;
                await session.UpdateAsync(news);

                var commentInNews = new TCommentInThread {
                    Comment = comment, Commentable = news
                };
                await session.SaveAsync(commentInNews);

                transaction.Commit();
                return(commentMapping.ToCommentView(comment));
            }
        }
Ejemplo n.º 4
0
 // CRUD operations
 public Product Create(Product product)
 {
     using (var t = session.BeginTransaction())
     {
         session.Save(product);
         t.Commit();
         return(product);
     }
 }
Ejemplo n.º 5
0
        public async Task <IHttpActionResult <ExternalLinkView> > Post([FromBody] ExternalLinkView value)
        {
            using (var transaction = session.BeginTransaction())
            {
                var link = new ExternalLink {
                    Title = value.Title, Url = value.Url
                };
                await session.SaveAsync(link);

                transaction.Commit();
                return(Created("GetExternalLink", link.Id, miscDataMapping.ToExternalLinkDto(link)));
            }
        }
Ejemplo n.º 6
0
        public async Task <IHttpActionResult <ForumView> > Post([FromBody] ForumView value)
        {
            using (var transaction = session.BeginTransaction())
            {
                var forum = new Data.Forums.Forum {
                    Name = value.Name, ReadRole = value.ReadRole, WriteRole = value.WriteRole
                };
                await session.SaveAsync(forum);

                transaction.Commit();
                value = forumDataMapping.ToForumView(forum, 0);
            }
            return(Created("GetForum", value.Id, value));
        }
Ejemplo n.º 7
0
        public static IApplicationBuilder UseFolkeCore(
            this IApplicationBuilder app,
            IFolkeConnection connection,
            IHostingEnvironment env,
            RoleManager <Role> roleManager,
            UserManager <User> userManager,
            ApplicationPartManager applicationPartManager,
            Action <FolkeCoreOptions> optionsAction)
        {
            app.UseIdentity();
            app.UseDefaultFiles();
            app.UseStaticFiles();
            app.UseMvc();
            app.UseRequestLocalization();

            connection.UpdateIdentityUserSchema <int, User>();
            connection.UpdateIdentityRoleSchema <int, User>();
            connection.UpdateSchema(typeof(User).GetTypeInfo().Assembly);

            using (var transaction = connection.BeginTransaction())
            {
                var options = new FolkeCoreOptions();
                optionsAction(options);
                CreateAdministrator(roleManager, userManager, options).GetAwaiter().GetResult();
                transaction.Commit();
            }

            if (env.IsDevelopment())
            {
                CreateTypeScriptServices(applicationPartManager);
            }

            return(app);
        }
Ejemplo n.º 8
0
        // Configure is called after ConfigureServices is called.
        public void Configure(
            IApplicationBuilder app,
            IHostingEnvironment env,
            IFolkeConnection connection,
            RoleManager <Role> roleManager,
            UserManager <Account> userManager,
            ApplicationPartManager applicationPartManager)
        {
            app.UseIdentity();
            app.UseDefaultFiles();
            app.UseStaticFiles();
            app.UseMvc();
            app.UseRequestLocalization(new RequestLocalizationOptions {
                DefaultRequestCulture = new RequestCulture("fr-FR")
            });

            connection.UpdateIdentityUserSchema <int, Account>();
            connection.UpdateIdentityRoleSchema <int, Account>();
            connection.UpdateSchema(typeof(Account).GetTypeInfo().Assembly);
            connection.UpdateForumSchema <Account>();

            using (var transaction = connection.BeginTransaction())
            {
                CreateAdministrator(roleManager, userManager).GetAwaiter().GetResult();
                transaction.Commit();
            }

            if (env.IsDevelopment())
            {
                CreateTypeScriptServices(applicationPartManager);
            }
        }
Ejemplo n.º 9
0
        public async Task <IHttpActionResult <IEnumerable <ThreadView <TUserView> > > > GetFromForum(int forumId, [FromQuery] int offset = 0, [FromQuery] int limit = 10)
        {
            var forum = await session.LoadAsync <Data.Forums.Forum>(forumId);

            var account = await accountService.GetCurrentUserAsync();

            if (forum.ReadRole != null && !await accountService.HasRole(account, forum.ReadRole))
            {
                return(Unauthorized <IEnumerable <ThreadView <TUserView> > >());
            }

            if (account != null)
            {
                using (var transaction = session.BeginTransaction())
                {
                    var lastViewed = await session.SelectAllFrom <LastForumView <TUser> >().Where(l => l.Forum == forum && l.Account.Equals(account)).FirstOrDefaultAsync();

                    if (lastViewed == null)
                    {
                        lastViewed = new LastForumView <TUser> {
                            Account = account, Forum = forum, LastView = DateTime.UtcNow
                        };
                        await session.SaveAsync(lastViewed);
                    }
                    else
                    {
                        lastViewed.LastView = DateTime.UtcNow;
                        await session.UpdateAsync(lastViewed);
                    }
                    transaction.Commit();
                }

                var query = session.Select <ThreadBean>().All(x => x.Thread).All(x => x.LastViewed).All(x => x.Thread.Author).From(x => x.Thread).LeftJoin(x => x.LastViewed).On(x => x.Thread == x.LastViewed.Thread)
                            .AndOn(t => t.LastViewed.Account.Equals(account))
                            .LeftJoinOnId(x => x.Thread.Author)
                            .Where(t => t.Thread.Forum == forum).OrderBy(t => t.Thread.Sticky).Desc().OrderBy(t => t.Thread.CreationDate).Desc().Limit(offset, limit);

                var results = await query.ToListAsync();

                return(Ok(results.Select(b => forumsDataMapping.ToThreadView(b.Thread, b.LastViewed))));
            }
            else
            {
                var query = session.SelectAllFrom <Thread <TUser> >(x => x.Author).Where(t => t.Forum == forum).OrderBy(t => t.Sticky).Desc().OrderBy(t => t.CreationDate).Desc().Limit(offset, limit);
                return(Ok((await query.ToListAsync()).Select(t => forumsDataMapping.ToThreadView(t, null))));
            }
        }
Ejemplo n.º 10
0
        public async Task <IHttpActionResult <PollView <TUserView> > > Post([FromBody] PollView <TUserView> pollView)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest <PollView <TUserView> >(ModelState));
            }

            using (var transaction = session.BeginTransaction())
            {
                var account = await accountService.GetCurrentUserAsync();

                // First we create and save the poll
                // then we create the possible answers
                // attached to that poll.
                var poll = new Poll <TUser>()
                {
                    Author   = account,
                    Question = pollView.Question,
                    // For now open and close date are hard coded
                    // TODO: Add date picker
                    OpenDate  = DateTime.Now,
                    CloseDate = DateTime.Now.AddDays(7)
                };
                await session.SaveAsync(poll);

                var newAnswers = pollView.PossibleAnswers.Where(a => a.Text != null).ToList();

                foreach (var answerDto in newAnswers)
                {
                    answerDto.Text = answerDto.Text.Trim();
                    if (answerDto.Text.Length >= 1)
                    {
                        var possibleAnwer = pollDataMapping.FromPollDto(answerDto, poll);
                        await session.SaveAsync(possibleAnwer);
                    }
                }

                transaction.Commit();
                return(Created("GetPoll", poll.Id, pollDataMapping.ToPollDto(poll)));
            }
        }
        public async Task <IHttpActionResult <PollChosenAnswerView <TUserView> > > AddAnswer(int pollId, [FromBody] PollPossibleAnswerView value)
        {
            // Checks that provided Poll is visible
            var poll = await session.LoadAsync <Poll <TUser> >(pollId);

            if (poll.Deleted)
            {
                return(BadRequest <PollChosenAnswerView <TUserView> >("Deleted poll"));
            }

            var account = await accountService.GetCurrentUserAsync();

            // Checks that account hasn't voted yet
            var answers = await session.SelectAllFrom <PollChosenAnswer <TUser> >()
                          .Where(x => x.Account.Equals(account))
                          .SingleOrDefaultAsync();

            if (answers != null)
            {
                return(BadRequest <PollChosenAnswerView <TUserView> >("Already answered"));
            }

            using (var transaction = session.BeginTransaction())
            {
                var answer = await session.LoadAsync <PollPossibleAnswer <TUser> >(value.Id);

                if (answer.Poll != poll)
                {
                    return(BadRequest <PollChosenAnswerView <TUserView> >("Not a possible answer"));
                }

                var chosenAnswer = new PollChosenAnswer <TUser>
                {
                    Poll    = poll,
                    Answer  = answer,
                    Account = account
                };

                await session.SaveAsync(chosenAnswer);

                answer.Count++;
                await session.UpdateAsync(answer);

                transaction.Commit();

                return(Created("GetPollChosenAnswer", chosenAnswer.Id, pollDataMapping.ToPollChosenAnswerDto(chosenAnswer)));
            }
        }
Ejemplo n.º 12
0
        public async Task Put(int id, [FromBody] CommentView <TUserView> value)
        {
            var account = await userService.GetCurrentUserAsync();

            using (var transaction = session.BeginTransaction())
            {
                var comment = await session.LoadAsync <Comment <TUser> >(id);

                if (await userService.IsUser(account, comment.Author))
                {
                    comment.Text = value.Text;
                    await session.UpdateAsync(comment);

                    transaction.Commit();
                }
            }
        }
        public async Task <IHttpActionResult <PrivateMessageView <TUserView> > > Post([FromBody] PrivateMessageView <TUserView> value)
        {
            var account = await accountService.GetCurrentUserAsync();

            if (account == null)
            {
                return(Unauthorized <PrivateMessageView <TUserView> >());
            }
            if (value.AccountRecipients.Count == 0)
            {
                return(BadRequest <PrivateMessageView <TUserView> >("Aucun destinataire"));
            }
            using (var transaction = session.BeginTransaction())
            {
                var recipientAccounts = await accountService.GetUsersAsync(value.AccountRecipients);

                var html = await htmlSanitizerService.Sanitize(value.Text, account);

                var privateMessage = new PrivateMessage <TUser>
                {
                    Author = account,
                    Text   = html,
                    Title  = value.Title
                };

                session.Save(privateMessage);

                var recipients = new List <PrivateMessageRecipient <TUser> >();

                foreach (var recipientAccount in recipientAccounts)
                {
                    var recipient = new PrivateMessageRecipient <TUser>
                    {
                        PrivateMessage = privateMessage,
                        Recipient      = recipientAccount
                    };
                    recipients.Add(recipient);
                    await session.SaveAsync(recipient);
                }
                privateMessage.Recipients = recipients;
                transaction.Commit();
                return(Created("GetPrivateMessage", value.Id, forumsDataMapping.ToPrivateMessageView(privateMessage)));
            }
        }
Ejemplo n.º 14
0
        public async Task <IActionResult> Get(int imageId, string format)
        {
            int imageWidth;
            int imageHeight;

            switch (format)
            {
            case "thumb":
                imageWidth  = 256;
                imageHeight = 256;
                break;

            default:
                return(BadRequest("Unknown format"));
            }

            using (var transaction = session.BeginTransaction())
            {
                var photo = session.SelectAllFrom <Photo <TUser> >().SingleOrDefault(x => x.Original.Id == imageId && x.Width == imageWidth && x.Height == imageHeight);
                if (photo == null)
                {
                    var original = session.Load <Photo <TUser> >(imageId);
                    if (original.Original != null)
                    {
                        return(BadRequest());
                    }

                    var fileName = original.FileName.Replace(".", "." + format + ".");
                    using (var originalStream = imageStore.Load(original.FileName))
                    {
                        var fullSizeImage = new  Image(originalStream);
                        var resizedImage  = fullSizeImage.ResizeWithRatio(imageWidth, imageHeight);
                        using (var stream = new MemoryStream())
                        {
                            resizedImage.Save(stream);
                            ArraySegment <byte> buffer;
                            if (stream.TryGetBuffer(out buffer))
                            {
                                var url = await imageStore.SaveAsync(buffer.Array, stream.Length, fileName);

                                photo = new Photo <TUser>
                                {
                                    FileName     = fileName,
                                    CreationTime = DateTime.UtcNow,
                                    Height       = imageHeight,
                                    Width        = imageWidth,
                                    Original     = original,
                                    Length       = stream.Length,
                                    Url          = url,
                                    Uploader     = original.Uploader
                                };
                                await session.SaveAsync(photo);

                                transaction.Commit();
                            }
                        }
                    }
                }

                return(Redirect(photo.Url));
            }
        }