Программирование Баз данных

Автор работы: Пользователь скрыл имя, 09 Июня 2014 в 02:25, курсовая работа

Описание работы

Разработать систему публикации постов. Посты загружают зарегистрированные пользователи. При добавлении поста, пользователь может добавить к нему теги, возможность добавлять комментарии, есть только у зарегистрированных пользователей, также есть личный кабинет пользователя, в котором он может сменить пароль и загрузить аватар. Также пользователь может просмотреть последние добавленные посты других пользователей. Реализован поиск постов по тегам.

Содержание работы

ВВЕДЕНИЕ………………………………………………………………..…………………4
1. ОПИСАНИЕ ИСПОЛЬЗОВАННЫХ ТЕХНОЛОГИЙ ПРИ ПРОЕКТИРОВАНИИ……………………………………………………………...…….5
1.1 Архитектура модель-представление-контроллер……………………………..…….5
1.2 ASP.NET MVC Framework……………………………..…………………………….6
2. АНАЛИЗ ЗАДАЧИ……………………………………………………………………....9
3. ПРОЕКТИРОВАНИЕ БАЗЫ ДАННЫХ……………………………………….……..10
3.1 Структура таблиц…………………………………………………………………….10
3.2 Диаграмма отношений базы данных……………………………………………….12
4. АНАЛИЗ ЗАДАЧИ…………………………………………………………………......13
4.1 Структура сайта………………………………………………………………………13
4.2 Главная страница……………………………………………………………………13
4.3 Регистрация…………………………………………………………………….……..14
4.4 Авторизация…………………………………………………………………………..14
4.5 Страница добавления поста…………………………………………………………15
4.6 Страница просмотра поста…………………………………………………………..16
4.7 Страница просмотра постов по определенному тегу……………………………..16
5. ОСОБЕННОСТИ РЕАЛИЗАЦИИ……………………………………….…………….17
6. РЕАЛИЗАЦИЯ ФУНКЦИОНАЛЬНЫХ ВОЗМОЖНОСТЕЙ…………………….…18
6.1 Модели………………………………………………………………………………..18
6.2 Контроллеры…………………………………………………………………………20
ЗАКЛЮЧЕНИЕ………………………………………………………………………………21
БИБЛИОГРАФИЧЕСКИЙ СПИСОК….…………………………………………………...22
ПРИЛОЖЕНИЕ………………………………………………………………………………23
1. PostController.cs………………………………………………………………………23
2. UsetController.cs………………………………………………….......................……29
3. CustomMembershipProvider.cs………………………………....................................31
4. Классы для связи с базой данных………………………............................………...37

Файлы: 1 файл

kursovik_pvbd.docx

— 724.48 Кб (Скачать файл)

 

                Post post = new Post();

 

                post.PostText = PostText;

                post.UserID = userID;

                post.PostDate = DateTime.Now;

                post.PostDeleted = 0;

 

                _db.Posts.Add(post);

                _db.SaveChanges();

 

                int postID = _db.Posts.ToList<Post>().Last().PostID;

 

                foreach (var tg in Tags)

                {

                    var newtag = _db.Tags.FirstOrDefault(t => t.TagName == tg);

 

                    if (newtag == null)

                    {

                        _db.Tags.Add(new Tag() { TagName = tg });

                        _db.SaveChanges();

                    }

 

                    tagID = _db.Tags.FirstOrDefault(t => t.TagName == tg).TagID;

 

                    PostTag postTag = new PostTag();

                    postTag.PostID = postID;

                    postTag.TagID = tagID;

                    _db.PostTags.Add(postTag);

                    _db.SaveChanges();

                }

 

            }

 

            return RedirectToAction("PostPage", "Post");

        }

 

        [Authorize]

        public ActionResult GetAllPostByTagName(string tagName)

        {

            List<int> postIds = new List<int>();

 

            List<Post> posts = new List<Post>();

 

            //get all tag id by name

            using (DbProvider _db = new DbProvider())

            {

                var tag = _db.Tags.First(t => t.TagName == tagName);

 

                int tagID = tag.TagID;

 

                var postTags = _db.PostTags.ToList<PostTag>().Where(pt => pt.TagID == tagID);

 

                foreach (var id in postTags)

                {

                    postIds.Add(id.PostID);

 

                }

 

                foreach (var i in postIds)

                {

                    int postID = i;

 

                    posts.Add(_db.Posts.ToList<Post>().FirstOrDefault(p => p.PostID == i));

                }

 

                posts.Reverse();

 

                return View(posts);

            }

        }

 

 

        [Authorize]

        public ActionResult ShowPostInfo(int postID)

        {

            var model = new ViewPostModel();

 

            using (var db = new DbProvider())

            {

                Post post = db.Posts.First(p => p.PostID == postID);

                model.PostText = post.PostText;

                model.PostID = post.PostID;

                model.DataTime = post.PostDate;

                model.UserName = db.Users.First(u => u.UserID == post.UserID).UserName;

                List<int> tegsID = db.PostTags.Where(p => p.PostID == postID).Select(p => p.TagID).ToList<int>();

 

                model.Tags = new List<Tag>();

                foreach (var t in tegsID)

                {

                    var tag = db.Tags.First(tg => tg.TagID == t);

                    model.Tags.Add(tag);

                }

                model.Comments = new List<CommentModel>();//db.Comments.Where(c => c.PostID == postID).ToList<Comment>();

 

                foreach (var comment in db.Comments.Where(c => c.PostID == postID).ToList<Comment>())

                {

                    model.Comments.Add(new CommentModel()

                        {

                            Comment = comment,

                            UserName = db.Users.First(u => u.UserID == comment.UserID).UserName

                        });

                }

 

            }

            return View(model);

        }

 

 

        public bool IsPostDeleted(int PostID)

        {

            using (DbProvider _db = new DbProvider())

            {

                var post = _db.Posts.FirstOrDefault(p => p.PostID == PostID);

 

                if (post != null)

                {

                    if (post.PostDeleted == 1)

                    {

                        return true;

                    }

                    else

                    {

                        return false;

                    }

                }

                return false;

            }

        }

 

    }

}

 

AccountController.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using System.Web.Security;

using Twitt.Models;

using Twitt.Providers;

 

namespace Twitt.Controllers

{

    [AllowAnonymous]

    public class AccountController : Controller

    {

        //

        // GET: /Account/

 

        public ActionResult Registration()

        {

            return View();

        }

 

        public ActionResult Login()

        {

            return View();

        }

       

        [HttpPost]

        public ActionResult Login(LogOnModel model, string returnUrl)

        {

            if (ModelState.IsValid)

            {

                if (Membership.ValidateUser(model.UserName, model.UserPassword))

                {

                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);

                    if (Url.IsLocalUrl(returnUrl))

                    {

                        return Redirect(returnUrl);

                    }

                    else

                    {

                        return RedirectToAction("PostPage", "Post");

                    }

                }

                else

                {

                    ModelState.AddModelError("", "Неправильный пароль или логин");

                }

            }

            return RedirectToAction("Login", "Account");

        }

 

        [HttpPost]

        public ActionResult Registration(RegistrationModel model)

        {

            if (ModelState.IsValid)

            {

                MembershipUser membershipUser = ((CustomMembershipProvider)Membership.Provider).CreateUser(model.UserName, model.UserPassword);

 

                if (membershipUser != null)

                {

                    FormsAuthentication.SetAuthCookie(model.UserName, false);

                    return RedirectToAction("Index", "Home");

                }

                else

                {

                    ModelState.AddModelError("", "Ошибка при регистрации");

                }

            }

            return View(model);

        }

 

        public ActionResult LogOut()

        {

            FormsAuthentication.SignOut();

 

            return RedirectToAction("Index", "Home");

        }

    }

}

 

  1. Код содержащийся  в файле “UsetController.cs”  (содержит методы для загрузки аватара, нахождения имени пользователя по ID)

using System;

using System.Collections.Generic;

using System.IO;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using System.Web.Security;

using Twitt.Models;

using Twitt.Providers;

 

namespace Twitt.Controllers

{

    public class UserController : Controller

    {

        //

        // GET: /User/

        [Authorize]

        public ActionResult Index()

        {

            return View();

        }

 

        [Authorize]

        public ActionResult EditProfile()

        {

            using (DbProvider _db = new DbProvider())

            {

                User user = _db.Users.FirstOrDefault(u => u.UserName == User.Identity.Name);

 

                if (user == null)

                {

                    return RedirectToAction("Index", "Home");

                }

 

                return View(user);

            }

        }

 

        [HttpPost]

        public ActionResult EditProfile(string userName, string oldPassword, string newPassword)

        {

            if (ModelState.IsValid)

            {

                MembershipUser membershipUser = ((CustomMembershipProvider)Membership.Provider).UpdatePassword(userName,

                    oldPassword, newPassword);

 

                if (membershipUser != null)

                {

                    return RedirectToAction("Index", "Home");

                }

            }

 

            return RedirectToAction("PostPage", "Post");

        }

 

        [Authorize]

        public ActionResult UploadAvatar()

        {

            using (DbProvider _db = new DbProvider())

            {

                User user = _db.Users.FirstOrDefault(u => u.UserName == User.Identity.Name);

 

                if (user == null)

                {

                    return RedirectToAction("Index", "Home");

                }

 

                return View(user);

            }

        }

 

        [Authorize]

        [HttpPost]

        public ActionResult UploadAvatar(IEnumerable<HttpPostedFileBase> userAvatarPath, string userName)

        {

            List<HttpPostedFileBase> images = userAvatarPath.ToList<HttpPostedFileBase>();

 

            string ext;

            string appData;

            string files;

            string path;

 

            using (DbProvider _db = new DbProvider())

            {

                if (images[0] != null)

                {

                    ext = images[0].FileName.Split('.').Last();

                    if (ext == "png" || ext == "gif" || ext == "jpg" || ext == "jpeg" || ext == "PNG")

                    {

                        appData = Server.MapPath("~/UploadedFiles/");

                        files = Path.Combine(appData, Path.GetFileName(images[0].FileName));

                        images[0].SaveAs(files);

 

                        path = "\\UploadedFiles\\" + images[0].FileName;

                        MembershipUser membershipUser = ((CustomMembershipProvider)Membership.Provider).UpdateAvatar(userName, path);

                    }

                }

            }

            return RedirectToAction("EditProfile", "User");

        }

 

        public ActionResult GetUserAvatar()

        {

            using (DbProvider _db = new DbProvider())

            {

                var user = _db.Users.FirstOrDefault(u => u.UserName == User.Identity.Name);

 

                if (user != null)

                {

                    return PartialView(user);

                }

                return RedirectToAction("PostPage", "Post");

            }

        }

 

        public ActionResult GetUserNameByID(int userID)

        {

            using (DbProvider _db = new DbProvider())

            {

                var user = _db.Users.FirstOrDefault(u => u.UserID == userID);

 

                if (user != null)

                {

                    return PartialView(user);

                }

                return RedirectToAction("PostPage", "Post");

            }

        }

    }

}

 

  1. Код содержащийся в файле “CustomMembershipProvider.cs” (для авторизации и регистрации пользователя)

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Security;

using System.Web.Helpers;

using System.Security.Cryptography;

using System.Web.WebPages;

using Microsoft.Internal.Web.Utils;

using Twitt.Models;

 

namespace Twitt.Providers

{

    public class CustomMembershipProvider : MembershipProvider

    {

        public override bool ValidateUser(string userName, string userPassword)

        {

            bool isValid = false;

 

            using (DbProvider _db = new DbProvider())

            {

                try

                {

                    User user = (from u in _db.Users

                                 where u.UserName == userName

                                 select u).FirstOrDefault();

 

                    if (user != null && Crypto.VerifyHashedPassword(user.UserPassword, userPassword))

                    {

                        isValid = true;

                    }

                }

                catch

                {

                    isValid = false;

                }

            }

 

            return isValid;

        }

 

        public override MembershipUser GetUser(string userName, bool userIsOnline)

        {

            try

            {

                using (DbProvider _db = new DbProvider())

                {

                    var users = from u in _db.Users

                                where u.UserName == userName

                                select u;

                    if (users.Count() > 0)

                    {

                        User user = users.First();

 

                        MembershipUser memberUser = new MembershipUser("MyMembershipProvider", user.UserName, null, null, null, null,

                                            false, false, user.UserRegDate, DateTime.MinValue, DateTime.MinValue, DateTime.MinValue, DateTime.MinValue);

                        return memberUser;

                    }

                }

            }

            catch

            {

                return null;

            }

 

            return null;

        }

       

        public MembershipUser CreateUser(string userName, string userPassword)

        {

            MembershipUser membershipUser = GetUser(userName, false);

 

            if (membershipUser == null)

            {

                try

                {

                    using (DbProvider _db = new DbProvider())

                    {

                        User user = new User();

                      

                        user.UserName = userName;

                        user.UserPassword = Crypto.HashPassword(userPassword);

                        user.UserRoleID = 2;

                        user.UserDeleted = 0;

                        user.UserRegDate = DateTime.Now;

                        user.UserAvatarPath = "";

                      

                        _db.Users.Add(user);

                        _db.SaveChanges();

                        membershipUser = GetUser(userName, false);

                      

                        return membershipUser;

                    }

                }

                catch

                {

                    return null;

                }

            }

            return null;

        }

 

        public MembershipUser UpdateUser(string userName, string userPassword, string userAvatarPath)

        {

            MembershipUser membershipUser = GetUser(userName, false);

 

            if (membershipUser != null)

            {

                try

                {

                    using (DbProvider _db = new DbProvider())

                    {

                        User user = _db.Users.FirstOrDefault(u => u.UserName == userName);

 

                       

                        user.UserPassword = Crypto.HashPassword(userPassword);

                       

                        user.UserRegDate = DateTime.Now;

 

                        if (userAvatarPath.IsEmpty())

                        {

                            user.UserAvatarPath = "";

                        }

                        else

                        {

                            user.UserAvatarPath = userAvatarPath;

                        }

 

                        _db.SaveChanges();

 

                        membershipUser = GetUser(userName, false);

 

                        return membershipUser;

                    }

                }

                catch

Информация о работе Программирование Баз данных