locked
Converting a 3-Tier ASP.net Web Forms App to Core RRS feed

  • Question

  • User1658625817 posted

    I have an existing ASP.net Web Forms app with three tiers (Presentation, BLL, & DAL), the latter two being class libraries.  I also make heavy use of stored procedures to query my data.

    I'm trying to figure out where to start in brainstorming a new solution architecture.  Obviously, the UI would be MVC/Razor.  I'd probably use entity framework (although I'm a bit hesitant because my current app makes very heavy use of caching at the business layer).

    Outside of that, I'm not really sure where to start.  Do I convert all of my BLL methods to Web API calls?  Keep my DAL in a separate class but make it use entity?

    Friday, June 8, 2018 3:12 PM

Answers

  • User1120430333 posted

    You could go with a Layered architecture. 

    https://docs.microsoft.com/en-us/previous-versions/msp-n-p/ee658117(v=pandp.10)

    https://programmingwithmosh.com/asp-net/layered-architecture/

    Presentation layer

    Service layer WebAPI

    Data Access Layer using the DAO pattern and also use the DTO pattern. 

    https://www.tutorialspoint.com/design_pattern/data_access_object_pattern.htm

    https://www.codeproject.com/Articles/1050468/Data-Transfer-Object-Design-Pattern-in-Csharp

    You don't have to use EF at the DAL. You can use ADO.NET, SQL Command Objects, parametrized inline T-SQL,  parametrized sproc, a datareader and creating a single DTO  on a List<T> of DTO(s) retuned by the DAL. The DAL would be using DTO(s) for CRUD operations with the database.

    All DTO(s) would be in a classlib project called Entities and all projects would have project reference to Entities and know about the DTO(s).

    The one thing I would make sure that was implemented is the MVC pattern is where the model object has the control. It would be the model object that made the calls for CRUD to the service layer and not the controller. It would be the model object that had business logic in working with the viewmodel object that had data annotation that also implemented data validation business logic too along with the model object's business logic.

    <copied>

    An MVC model contains all of your application logic that is not contained in a view or a controller. The model should contain all of your application business logic, validation logic, and database access logic. 

    A view should contain only logic related to generating the user interface. A controller should only contain the bare minimum of logic required to return the right view or redirect the user to another action (flow control). Everything else should be contained in the model.

    In general, you should strive for fat models and skinny controllers. Your controller methods should contain only a few lines of code. If a controller action gets too fat, then you should consider moving the logic out to a new class in the Models folder. The caching would be done at the controller MVC controller, and it could also be done at the WebAPI controller too.

    <end>

    https://www.c-sharpcorner.com/UploadFile/56fb14/understanding-separation-of-concern-and-Asp-Net-mvc/

    You see the architectural style being implemented to some degree with just  the PL and DAL only without the service layer. Ye3s, EF is being used, but has you can see the mapping is with the DTO and the DTO is sent through the layers.

    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.Web.Mvc;
    
    namespace MVC.Models
    {
        public class ProjectViewModels
        {
            public class Project
            {
                public int ProjectId { get; set; }
    
                [Required(ErrorMessage = "Client Name is required")]
                [StringLength(50)]
                public string ClientName { get; set; }
    
                [Required(ErrorMessage = "Project Name is required")]
                [StringLength(50)]
                public string ProjectName { get; set; }
    
                [Required(ErrorMessage = "Technology is required")]
                [StringLength(50)]
                public string Technology { get; set; }
    
                [Required(ErrorMessage = "Project Type is required")]
                public string ProjectType { get; set; }
    
                [Required(ErrorMessage = "Start Date is required")]
                [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM-dd-yyyy}")]
                public DateTime? StartDate { get; set; }
    
                [Required(ErrorMessage = "End Date is required")]
                [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM-dd-yyyy}")]
                public DateTime? EndDate { get; set; }
    
                [Required(ErrorMessage = "Cost is required")]
                public decimal? Cost { get; set; }
    
                public List<SelectListItem> ProjectTypes { get; set; }
            }
    
            public List<Project> Projects { get; set; }
            
        }
    }
    
    -------------------------------------------------------------
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web.Mvc;
    using DAL;
    using Entities;
    
    
    namespace MVC.Models
    {
        public class ProjectModels : IProjectModels
        {
            public ProjectViewModels GetProjectsByUserId(string userid)
            {
                var vm = new ProjectViewModels {Projects = new List<ProjectViewModels.Project>()};
                
                var dtos = new DaoProject().GetProjectsByUserId(userid);
    
                vm.Projects.AddRange(dtos.Select(dto => new ProjectViewModels.Project()
                {
                    ProjectId = dto.ProjectId,
                    ClientName = dto.ClientName,
                    ProjectName = dto.ProjectName,
                    Technology = dto.Technology,
                    ProjectType = dto.ProjectType,
                    StartDate = dto.StartDate,
                    EndDate = dto.EndDate,
                    Cost = dto.Cost
                }).ToList());
    
                return vm;
            }
    
            public ProjectViewModels.Project GetProjectById(int id)
            {
                var dto = new DaoProject().GetProjectById(id);
    
                var project = new ProjectViewModels.Project
                { 
                    ProjectId = dto.ProjectId,
                    ClientName = dto.ClientName,
                    ProjectName = dto.ProjectName,
                    Technology = dto.Technology,
                    ProjectType = dto.ProjectType,
                    StartDate = dto.StartDate,
                    EndDate = dto.EndDate,
                    Cost = dto.Cost
                };
       
                return project;
            }
    
            public ProjectViewModels.Project Create()
            {
                var project = new ProjectViewModels.Project();
                return PopulateSelectedList(project);
            }
    
            public void Create(ProjectViewModels.Project project, string userid)
            {
                var dto = new DtoProject
                {
                    ProjectId = project.ProjectId,
                    ClientName = project.ClientName,
                    ProjectName = project.ProjectName,
                    ProjectType = project.ProjectType,  
                    Technology = project.Technology,
                    UserId = userid,
                    StartDate = (DateTime) project.StartDate,
                    EndDate = (DateTime) project.EndDate,
                    Cost = (decimal) project.Cost
                };
    
                new DaoProject().CreateProject(dto);
            }
    
            public ProjectViewModels.Project Edit(int id)
            {
                var dto = new DaoProject().GetProjectById(id);
    
                var project = new ProjectViewModels.Project
                { 
                    ProjectId = dto.ProjectId,
                    ClientName = dto.ClientName,
                    ProjectName = dto.ProjectName,
                    Technology = dto.Technology,
                    ProjectType = dto.ProjectType,
                    StartDate = dto.StartDate,
                    EndDate = dto.EndDate,
                    Cost = dto.Cost
                };
    
                project = PopulateSelectedList(project);
    
                return project;
            }
    
            public void Edit(ProjectViewModels.Project project, string userid)
            {
                var dto = new DtoProject
                {
                    ProjectId = project.ProjectId,
                    ClientName = project.ClientName,
                    ProjectName = project.ProjectName,
                    ProjectType = project.ProjectType,
                    Technology = project.Technology,
                    UserId = userid,
                    StartDate = (DateTime) project.StartDate,
                    EndDate = (DateTime) project.EndDate,
                    Cost = (decimal) project.Cost
                };
    
                new DaoProject().UpdateProject(dto);
            }
    
            public void Delete(int id)
            {
                new DaoProject().DeleteProject(id);
            }
    
            public ProjectViewModels.Project PopulateSelectedList(ProjectViewModels.Project project)
            {
                project.ProjectTypes = new List<SelectListItem>
                {
                    new SelectListItem {Value = "1", Text = "Fixed Price"},
                    new SelectListItem {Value = "2", Text = "Time & Material"}
                };
    
                var selected = (from a in project.ProjectTypes.Where(a => a.Value == project.ProjectType) select a)
                    .SingleOrDefault();
    
                if (selected != null)
                    selected.Selected = true;
    
                return project;
            }
        }
    }
    
    ---------------------------------------------------------------------
    
    using System;
    using System.Linq;
    using System.Web.Mvc;
    using MVC.Models;
    using Microsoft.AspNet.Identity;
    
    namespace MVC.Controllers
    {
        public class ProjectController : BaseController
        {
            // GET: Project
            [Authorize]
            public ActionResult Index()
            {
                return View(new ProjectModels().GetProjectsByUserId(User.Identity.GetUserId()));
            }
    
            [Authorize]
            public ActionResult Details(int id = 0)
            {
                return id == 0 ? null : View(new ProjectModels().Edit(id));
            }
    
            [Authorize]
            public ActionResult Create()
            {
                return View(new ProjectModels().Create());
            }
    
            [Authorize]
            [HttpPost]
            public ActionResult Create(ProjectViewModels.Project project, string submit)
            {
                if (submit == "Cancel") return RedirectToAction("Index");
    
                ValidateddlProjectTypes();
    
                project.ProjectType = (Request.Form["ddlProjectTypes"]);
    
                if (new ModelsHelper().IsEndDateLessThanStartDate(project, "Project"))
                    ModelState.AddModelError(string.Empty, "End Date cannot be less than Start Date.");
    
                if (!ModelState.IsValid) return View(new ProjectModels().PopulateSelectedList(project));
    
                new ProjectModels().Create(project, User.Identity.GetUserId());
                return RedirectToAction("Index");
            }
    
            [Authorize]
            public ActionResult Edit(int id = 0)
            {
                return id == 0 ? null : View(new ProjectModels().Edit(id));
            }
    
            [Authorize]
            [HttpPost]
            public ActionResult Edit(ProjectViewModels.Project project, string submit)
            {
                if (submit == "Cancel") return RedirectToAction("Index");
    
                if (new ModelsHelper().IsEndDateLessThanStartDate(project, "Project"))
                    ModelState.AddModelError(String.Empty, "End Date cannot be less than Start Date.");
    
                if (!ModelState.IsValid) return View(new ProjectModels().PopulateSelectedList(project));
    
                var theproject = new ProjectViewModels.Project();
    
                theproject = project;
    
                theproject.ProjectType = Request.Form["ProjectType"];
    
                new ProjectModels().Edit(theproject, User.Identity.GetUserId());
                return RedirectToAction("Index");
            }
    
            public ActionResult Delete(int id = 0)
            {
                if (id > 0) new ProjectModels().Delete(id);
    
                return RedirectToAction("Index");
            }
       
            public ActionResult Cancel()
            {
                return RedirectToAction("Index", "Home");
            }
    
            public ActionResult UploadFile(int id)
            {
                return RedirectToAction("UploadFile", "Upload", new { id = id, type = "PM" });
            }
    
            private void ValidateddlProjectTypes()
            {
                if (Request.Form["ddlProjectTypes"] == string.Empty)
                {
                    ModelState.AddModelError("ProjectType", "Project Type is required");
                }
                else
                {
                    foreach (var key in ModelState.Keys.ToList().Where(key => ModelState.ContainsKey(key)))
                    {
                        if (key == "ProjectType")
                            ModelState[key].Errors.Clear();
                    }
                }
            }
        }
    }
    
    ==============================================================
    
    @model MVC.Models.ProjectViewModels.Project
    
    <!DOCTYPE html>
    
    <style type="text/css">
        .editor-field > label {
            float: left;
            width: 150px;
        }
        .txtbox {
            font-family: Arial, Helvetica, sans-serif;
            font-size: 12px;
            background: white;
            color: black;
            cursor: text;
            border-bottom: 1px solid #104A7B;
            border-right: 1px solid #104A7B;
            border-left: 1px solid #104A7B;
            border-top: 1px solid #104A7B;
            padding-top: 10px;
        }       
    </style>
    <html>
    <head>
        <title>Edit</title>
    </head>
    
    <body>
        <h1>Project</h1>
    
        @using (Html.BeginForm())
        {
    
            @Html.ValidationSummary(false, "", new { @class = "text-danger" })
    
        <fieldset>
    
            <legend>Edit</legend>
    
            @Html.HiddenFor(model => model.ProjectId)
    
            <div class="editor-field">
                @Html.Label("Project Name:")
                @Html.TextBoxFor(model => model.ProjectName, new { @Cssclass = "txtbox" })
                @Html.ValidationMessageFor(model => model.ProjectName)
            </div>
            <br />
            <div class="editor-field">
                @Html.Label("Client Name:")
                @Html.TextBoxFor(model => model.ClientName, new { @Cssclass = "txtbox" })
                @Html.ValidationMessageFor(model => model.ClientName)
            </div>
            <br />
            <div class="editor-field">
                @Html.Label("Technology:")
                @Html.TextBoxFor(model => model.Technology, new { @Cssclass = "txtbox" })
                @Html.ValidationMessageFor(model => model.Technology)
            </div>
            <br />
            <div class="editor-field">
                @Html.Label("Start Date:")
                @Html.TextBoxFor(model => model.StartDate, new { @Cssclass = "txtbox" })
                @Html.ValidationMessageFor(model => model.StartDate)
            </div>
            <br />
            <div class="editor-field">
                @Html.Label("End Date:")
                @Html.TextBoxFor(model => model.EndDate, new { @Cssclass = "txtbox" })
                @Html.ValidationMessageFor(model => model.EndDate)
            </div>
            <br />
            <div class="editor-field">
                @Html.Label("Cost:")
                @Html.TextBoxFor(model => model.Cost, new { @Cssclass = "txtbox" })
                @Html.ValidationMessageFor(model => model.Cost)
            </div>
            <br />
            <div class="editor-field">
                @Html.Label("Project Type:")
                @Html.DropDownListFor(model => model.ProjectType, Model.ProjectTypes)
            </div>
            <br />
            <p>
                <input type="submit" name="submit" value="Save" />
                <input type="submit" name="submit" value="Cancel" />
            </p>
    
        </fieldset>
        }
    
    </body>
    </html>
    
    -------------------------------------------------------------
    
    using System.Collections.Generic;
    using System.Data.Entity;
    using System.Linq;
    using System.Transactions;
    using Entities;
    using DAL.Model;
    
    namespace DAL
    {
        public class DaoProject : IDaoProject
        {
            public DtoProject GetProjectById(int id)
            {
                var dto = new DtoProject();
    
                using (var context = new ProjectMgmntEntities())
                {
                    var project = (context.Projects.Where(a => a.ProjectId == id)).SingleOrDefault();
    
                    if (project == null) return dto;
                    dto.ProjectId = project.ProjectId;
                    dto.ClientName = project.ClientName;
                    dto.ProjectName = project.ProjectName;
                    dto.Technology = project.Technology;
                    dto.ProjectType = project.ProjectType;
                    dto.UserId = project.UserID;
                    dto.StartDate = project.StartDate;
                    dto.EndDate = project.EndDate;
                    dto.Cost = project.Cost;
                }
    
                return dto;
            }
    
            public List<DtoProject> GetProjectsByUserId(string userid)
            {
                var dtos = new List<DtoProject>();
    
                using (var context = new ProjectMgmntEntities())
                {
    
                    dtos = (from a in context.Projects.Where(a => a.UserID.Contains(userid))
                        select new DtoProject
                        {
                            ProjectId = a.ProjectId,
                            ClientName = a.ClientName,
                            ProjectName = a.ProjectName,
                            Technology = a.Technology,
                            ProjectType = a.ProjectType,
                            UserId = a.UserID,
                            StartDate = a.StartDate,
                            EndDate = a.EndDate,
                            Cost = a.Cost
                        }).ToList();
                }
    
                return dtos;
            }
    
            public void CreateProject(DtoProject dto)
            {
                using (var context = new ProjectMgmntEntities())
                {
                    var project = new Project
                    {
                        ClientName = dto.ClientName,
                        ProjectName = dto.ProjectName,
                        Technology = dto.Technology,
                        ProjectType = dto.ProjectType,
                        UserID = dto.UserId,
                        StartDate = dto.StartDate,
                        EndDate = dto.EndDate,
                        Cost = dto.Cost
                    };
    
                    context.Projects.Add(project);
                    context.SaveChanges();
                }
            }
    
            public void UpdateProject(DtoProject dto)
            {
                var project = new Project();
    
                using (var context = new ProjectMgmntEntities())
                {
                    project = (context.Projects.Where(a => a.ProjectId == dto.ProjectId)).SingleOrDefault();
                }
    
                if (project != null)
                {
                    project.ClientName = dto.ClientName;
                    project.ProjectName = dto.ProjectName;
                    project.Technology = dto.Technology;
                    project.ProjectType = dto.ProjectType;
                    project.UserID = dto.UserId;
                    project.StartDate = dto.StartDate;
                    project.EndDate = dto.EndDate;
                    project.Cost = dto.Cost;
                }
    
                using (var dbcontext = new ProjectMgmntEntities())
                {
                    if (project == null) return;
                    dbcontext.Entry(project).State = EntityState.Modified;
                    dbcontext.SaveChanges();
                }
            }
    
            public void DeleteProject(int id)
            {
                Project project;
    
                using (var context = new ProjectMgmntEntities())
                {
                    project = (context.Projects.Where(a => a.ProjectId == id)).SingleOrDefault();
                }
    
                if (project == null) return;
    
                using (var newContext = new ProjectMgmntEntities())
                {
                    var tasks = new DaoTask().GetTasksByProjectId(project.ProjectId);
                    using (TransactionScope scope = new TransactionScope())
                    {
                        foreach (var task in tasks)
                        {
                            new DaoTask().DeleteTask(task.TaskId);
                        }
    
                        newContext.Entry(project).State = EntityState.Deleted;
                        newContext.SaveChanges();
    
                        scope.Complete();
                    }
                }
            }
        }
    }
    
    =======================================
    using System;
    
    namespace Entities
    {
        public class DtoProject
        {
            public int ProjectId { get; set; }
            public string ClientName { get; set; }
            public string ProjectName { get; set; }
            public string Technology { get; set; }
            public string ProjectType { get; set; }
            public string UserId { get; set; }
            public DateTime StartDate { get; set; }
            public DateTime EndDate { get; set; }
            public decimal Cost { get; set; }
        }
    }
    
    
    
    
    

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, June 9, 2018 3:49 AM

All replies

  • User1120430333 posted

    You could go with a Layered architecture. 

    https://docs.microsoft.com/en-us/previous-versions/msp-n-p/ee658117(v=pandp.10)

    https://programmingwithmosh.com/asp-net/layered-architecture/

    Presentation layer

    Service layer WebAPI

    Data Access Layer using the DAO pattern and also use the DTO pattern. 

    https://www.tutorialspoint.com/design_pattern/data_access_object_pattern.htm

    https://www.codeproject.com/Articles/1050468/Data-Transfer-Object-Design-Pattern-in-Csharp

    You don't have to use EF at the DAL. You can use ADO.NET, SQL Command Objects, parametrized inline T-SQL,  parametrized sproc, a datareader and creating a single DTO  on a List<T> of DTO(s) retuned by the DAL. The DAL would be using DTO(s) for CRUD operations with the database.

    All DTO(s) would be in a classlib project called Entities and all projects would have project reference to Entities and know about the DTO(s).

    The one thing I would make sure that was implemented is the MVC pattern is where the model object has the control. It would be the model object that made the calls for CRUD to the service layer and not the controller. It would be the model object that had business logic in working with the viewmodel object that had data annotation that also implemented data validation business logic too along with the model object's business logic.

    <copied>

    An MVC model contains all of your application logic that is not contained in a view or a controller. The model should contain all of your application business logic, validation logic, and database access logic. 

    A view should contain only logic related to generating the user interface. A controller should only contain the bare minimum of logic required to return the right view or redirect the user to another action (flow control). Everything else should be contained in the model.

    In general, you should strive for fat models and skinny controllers. Your controller methods should contain only a few lines of code. If a controller action gets too fat, then you should consider moving the logic out to a new class in the Models folder. The caching would be done at the controller MVC controller, and it could also be done at the WebAPI controller too.

    <end>

    https://www.c-sharpcorner.com/UploadFile/56fb14/understanding-separation-of-concern-and-Asp-Net-mvc/

    You see the architectural style being implemented to some degree with just  the PL and DAL only without the service layer. Ye3s, EF is being used, but has you can see the mapping is with the DTO and the DTO is sent through the layers.

    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using System.Web.Mvc;
    
    namespace MVC.Models
    {
        public class ProjectViewModels
        {
            public class Project
            {
                public int ProjectId { get; set; }
    
                [Required(ErrorMessage = "Client Name is required")]
                [StringLength(50)]
                public string ClientName { get; set; }
    
                [Required(ErrorMessage = "Project Name is required")]
                [StringLength(50)]
                public string ProjectName { get; set; }
    
                [Required(ErrorMessage = "Technology is required")]
                [StringLength(50)]
                public string Technology { get; set; }
    
                [Required(ErrorMessage = "Project Type is required")]
                public string ProjectType { get; set; }
    
                [Required(ErrorMessage = "Start Date is required")]
                [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM-dd-yyyy}")]
                public DateTime? StartDate { get; set; }
    
                [Required(ErrorMessage = "End Date is required")]
                [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM-dd-yyyy}")]
                public DateTime? EndDate { get; set; }
    
                [Required(ErrorMessage = "Cost is required")]
                public decimal? Cost { get; set; }
    
                public List<SelectListItem> ProjectTypes { get; set; }
            }
    
            public List<Project> Projects { get; set; }
            
        }
    }
    
    -------------------------------------------------------------
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web.Mvc;
    using DAL;
    using Entities;
    
    
    namespace MVC.Models
    {
        public class ProjectModels : IProjectModels
        {
            public ProjectViewModels GetProjectsByUserId(string userid)
            {
                var vm = new ProjectViewModels {Projects = new List<ProjectViewModels.Project>()};
                
                var dtos = new DaoProject().GetProjectsByUserId(userid);
    
                vm.Projects.AddRange(dtos.Select(dto => new ProjectViewModels.Project()
                {
                    ProjectId = dto.ProjectId,
                    ClientName = dto.ClientName,
                    ProjectName = dto.ProjectName,
                    Technology = dto.Technology,
                    ProjectType = dto.ProjectType,
                    StartDate = dto.StartDate,
                    EndDate = dto.EndDate,
                    Cost = dto.Cost
                }).ToList());
    
                return vm;
            }
    
            public ProjectViewModels.Project GetProjectById(int id)
            {
                var dto = new DaoProject().GetProjectById(id);
    
                var project = new ProjectViewModels.Project
                { 
                    ProjectId = dto.ProjectId,
                    ClientName = dto.ClientName,
                    ProjectName = dto.ProjectName,
                    Technology = dto.Technology,
                    ProjectType = dto.ProjectType,
                    StartDate = dto.StartDate,
                    EndDate = dto.EndDate,
                    Cost = dto.Cost
                };
       
                return project;
            }
    
            public ProjectViewModels.Project Create()
            {
                var project = new ProjectViewModels.Project();
                return PopulateSelectedList(project);
            }
    
            public void Create(ProjectViewModels.Project project, string userid)
            {
                var dto = new DtoProject
                {
                    ProjectId = project.ProjectId,
                    ClientName = project.ClientName,
                    ProjectName = project.ProjectName,
                    ProjectType = project.ProjectType,  
                    Technology = project.Technology,
                    UserId = userid,
                    StartDate = (DateTime) project.StartDate,
                    EndDate = (DateTime) project.EndDate,
                    Cost = (decimal) project.Cost
                };
    
                new DaoProject().CreateProject(dto);
            }
    
            public ProjectViewModels.Project Edit(int id)
            {
                var dto = new DaoProject().GetProjectById(id);
    
                var project = new ProjectViewModels.Project
                { 
                    ProjectId = dto.ProjectId,
                    ClientName = dto.ClientName,
                    ProjectName = dto.ProjectName,
                    Technology = dto.Technology,
                    ProjectType = dto.ProjectType,
                    StartDate = dto.StartDate,
                    EndDate = dto.EndDate,
                    Cost = dto.Cost
                };
    
                project = PopulateSelectedList(project);
    
                return project;
            }
    
            public void Edit(ProjectViewModels.Project project, string userid)
            {
                var dto = new DtoProject
                {
                    ProjectId = project.ProjectId,
                    ClientName = project.ClientName,
                    ProjectName = project.ProjectName,
                    ProjectType = project.ProjectType,
                    Technology = project.Technology,
                    UserId = userid,
                    StartDate = (DateTime) project.StartDate,
                    EndDate = (DateTime) project.EndDate,
                    Cost = (decimal) project.Cost
                };
    
                new DaoProject().UpdateProject(dto);
            }
    
            public void Delete(int id)
            {
                new DaoProject().DeleteProject(id);
            }
    
            public ProjectViewModels.Project PopulateSelectedList(ProjectViewModels.Project project)
            {
                project.ProjectTypes = new List<SelectListItem>
                {
                    new SelectListItem {Value = "1", Text = "Fixed Price"},
                    new SelectListItem {Value = "2", Text = "Time & Material"}
                };
    
                var selected = (from a in project.ProjectTypes.Where(a => a.Value == project.ProjectType) select a)
                    .SingleOrDefault();
    
                if (selected != null)
                    selected.Selected = true;
    
                return project;
            }
        }
    }
    
    ---------------------------------------------------------------------
    
    using System;
    using System.Linq;
    using System.Web.Mvc;
    using MVC.Models;
    using Microsoft.AspNet.Identity;
    
    namespace MVC.Controllers
    {
        public class ProjectController : BaseController
        {
            // GET: Project
            [Authorize]
            public ActionResult Index()
            {
                return View(new ProjectModels().GetProjectsByUserId(User.Identity.GetUserId()));
            }
    
            [Authorize]
            public ActionResult Details(int id = 0)
            {
                return id == 0 ? null : View(new ProjectModels().Edit(id));
            }
    
            [Authorize]
            public ActionResult Create()
            {
                return View(new ProjectModels().Create());
            }
    
            [Authorize]
            [HttpPost]
            public ActionResult Create(ProjectViewModels.Project project, string submit)
            {
                if (submit == "Cancel") return RedirectToAction("Index");
    
                ValidateddlProjectTypes();
    
                project.ProjectType = (Request.Form["ddlProjectTypes"]);
    
                if (new ModelsHelper().IsEndDateLessThanStartDate(project, "Project"))
                    ModelState.AddModelError(string.Empty, "End Date cannot be less than Start Date.");
    
                if (!ModelState.IsValid) return View(new ProjectModels().PopulateSelectedList(project));
    
                new ProjectModels().Create(project, User.Identity.GetUserId());
                return RedirectToAction("Index");
            }
    
            [Authorize]
            public ActionResult Edit(int id = 0)
            {
                return id == 0 ? null : View(new ProjectModels().Edit(id));
            }
    
            [Authorize]
            [HttpPost]
            public ActionResult Edit(ProjectViewModels.Project project, string submit)
            {
                if (submit == "Cancel") return RedirectToAction("Index");
    
                if (new ModelsHelper().IsEndDateLessThanStartDate(project, "Project"))
                    ModelState.AddModelError(String.Empty, "End Date cannot be less than Start Date.");
    
                if (!ModelState.IsValid) return View(new ProjectModels().PopulateSelectedList(project));
    
                var theproject = new ProjectViewModels.Project();
    
                theproject = project;
    
                theproject.ProjectType = Request.Form["ProjectType"];
    
                new ProjectModels().Edit(theproject, User.Identity.GetUserId());
                return RedirectToAction("Index");
            }
    
            public ActionResult Delete(int id = 0)
            {
                if (id > 0) new ProjectModels().Delete(id);
    
                return RedirectToAction("Index");
            }
       
            public ActionResult Cancel()
            {
                return RedirectToAction("Index", "Home");
            }
    
            public ActionResult UploadFile(int id)
            {
                return RedirectToAction("UploadFile", "Upload", new { id = id, type = "PM" });
            }
    
            private void ValidateddlProjectTypes()
            {
                if (Request.Form["ddlProjectTypes"] == string.Empty)
                {
                    ModelState.AddModelError("ProjectType", "Project Type is required");
                }
                else
                {
                    foreach (var key in ModelState.Keys.ToList().Where(key => ModelState.ContainsKey(key)))
                    {
                        if (key == "ProjectType")
                            ModelState[key].Errors.Clear();
                    }
                }
            }
        }
    }
    
    ==============================================================
    
    @model MVC.Models.ProjectViewModels.Project
    
    <!DOCTYPE html>
    
    <style type="text/css">
        .editor-field > label {
            float: left;
            width: 150px;
        }
        .txtbox {
            font-family: Arial, Helvetica, sans-serif;
            font-size: 12px;
            background: white;
            color: black;
            cursor: text;
            border-bottom: 1px solid #104A7B;
            border-right: 1px solid #104A7B;
            border-left: 1px solid #104A7B;
            border-top: 1px solid #104A7B;
            padding-top: 10px;
        }       
    </style>
    <html>
    <head>
        <title>Edit</title>
    </head>
    
    <body>
        <h1>Project</h1>
    
        @using (Html.BeginForm())
        {
    
            @Html.ValidationSummary(false, "", new { @class = "text-danger" })
    
        <fieldset>
    
            <legend>Edit</legend>
    
            @Html.HiddenFor(model => model.ProjectId)
    
            <div class="editor-field">
                @Html.Label("Project Name:")
                @Html.TextBoxFor(model => model.ProjectName, new { @Cssclass = "txtbox" })
                @Html.ValidationMessageFor(model => model.ProjectName)
            </div>
            <br />
            <div class="editor-field">
                @Html.Label("Client Name:")
                @Html.TextBoxFor(model => model.ClientName, new { @Cssclass = "txtbox" })
                @Html.ValidationMessageFor(model => model.ClientName)
            </div>
            <br />
            <div class="editor-field">
                @Html.Label("Technology:")
                @Html.TextBoxFor(model => model.Technology, new { @Cssclass = "txtbox" })
                @Html.ValidationMessageFor(model => model.Technology)
            </div>
            <br />
            <div class="editor-field">
                @Html.Label("Start Date:")
                @Html.TextBoxFor(model => model.StartDate, new { @Cssclass = "txtbox" })
                @Html.ValidationMessageFor(model => model.StartDate)
            </div>
            <br />
            <div class="editor-field">
                @Html.Label("End Date:")
                @Html.TextBoxFor(model => model.EndDate, new { @Cssclass = "txtbox" })
                @Html.ValidationMessageFor(model => model.EndDate)
            </div>
            <br />
            <div class="editor-field">
                @Html.Label("Cost:")
                @Html.TextBoxFor(model => model.Cost, new { @Cssclass = "txtbox" })
                @Html.ValidationMessageFor(model => model.Cost)
            </div>
            <br />
            <div class="editor-field">
                @Html.Label("Project Type:")
                @Html.DropDownListFor(model => model.ProjectType, Model.ProjectTypes)
            </div>
            <br />
            <p>
                <input type="submit" name="submit" value="Save" />
                <input type="submit" name="submit" value="Cancel" />
            </p>
    
        </fieldset>
        }
    
    </body>
    </html>
    
    -------------------------------------------------------------
    
    using System.Collections.Generic;
    using System.Data.Entity;
    using System.Linq;
    using System.Transactions;
    using Entities;
    using DAL.Model;
    
    namespace DAL
    {
        public class DaoProject : IDaoProject
        {
            public DtoProject GetProjectById(int id)
            {
                var dto = new DtoProject();
    
                using (var context = new ProjectMgmntEntities())
                {
                    var project = (context.Projects.Where(a => a.ProjectId == id)).SingleOrDefault();
    
                    if (project == null) return dto;
                    dto.ProjectId = project.ProjectId;
                    dto.ClientName = project.ClientName;
                    dto.ProjectName = project.ProjectName;
                    dto.Technology = project.Technology;
                    dto.ProjectType = project.ProjectType;
                    dto.UserId = project.UserID;
                    dto.StartDate = project.StartDate;
                    dto.EndDate = project.EndDate;
                    dto.Cost = project.Cost;
                }
    
                return dto;
            }
    
            public List<DtoProject> GetProjectsByUserId(string userid)
            {
                var dtos = new List<DtoProject>();
    
                using (var context = new ProjectMgmntEntities())
                {
    
                    dtos = (from a in context.Projects.Where(a => a.UserID.Contains(userid))
                        select new DtoProject
                        {
                            ProjectId = a.ProjectId,
                            ClientName = a.ClientName,
                            ProjectName = a.ProjectName,
                            Technology = a.Technology,
                            ProjectType = a.ProjectType,
                            UserId = a.UserID,
                            StartDate = a.StartDate,
                            EndDate = a.EndDate,
                            Cost = a.Cost
                        }).ToList();
                }
    
                return dtos;
            }
    
            public void CreateProject(DtoProject dto)
            {
                using (var context = new ProjectMgmntEntities())
                {
                    var project = new Project
                    {
                        ClientName = dto.ClientName,
                        ProjectName = dto.ProjectName,
                        Technology = dto.Technology,
                        ProjectType = dto.ProjectType,
                        UserID = dto.UserId,
                        StartDate = dto.StartDate,
                        EndDate = dto.EndDate,
                        Cost = dto.Cost
                    };
    
                    context.Projects.Add(project);
                    context.SaveChanges();
                }
            }
    
            public void UpdateProject(DtoProject dto)
            {
                var project = new Project();
    
                using (var context = new ProjectMgmntEntities())
                {
                    project = (context.Projects.Where(a => a.ProjectId == dto.ProjectId)).SingleOrDefault();
                }
    
                if (project != null)
                {
                    project.ClientName = dto.ClientName;
                    project.ProjectName = dto.ProjectName;
                    project.Technology = dto.Technology;
                    project.ProjectType = dto.ProjectType;
                    project.UserID = dto.UserId;
                    project.StartDate = dto.StartDate;
                    project.EndDate = dto.EndDate;
                    project.Cost = dto.Cost;
                }
    
                using (var dbcontext = new ProjectMgmntEntities())
                {
                    if (project == null) return;
                    dbcontext.Entry(project).State = EntityState.Modified;
                    dbcontext.SaveChanges();
                }
            }
    
            public void DeleteProject(int id)
            {
                Project project;
    
                using (var context = new ProjectMgmntEntities())
                {
                    project = (context.Projects.Where(a => a.ProjectId == id)).SingleOrDefault();
                }
    
                if (project == null) return;
    
                using (var newContext = new ProjectMgmntEntities())
                {
                    var tasks = new DaoTask().GetTasksByProjectId(project.ProjectId);
                    using (TransactionScope scope = new TransactionScope())
                    {
                        foreach (var task in tasks)
                        {
                            new DaoTask().DeleteTask(task.TaskId);
                        }
    
                        newContext.Entry(project).State = EntityState.Deleted;
                        newContext.SaveChanges();
    
                        scope.Complete();
                    }
                }
            }
        }
    }
    
    =======================================
    using System;
    
    namespace Entities
    {
        public class DtoProject
        {
            public int ProjectId { get; set; }
            public string ClientName { get; set; }
            public string ProjectName { get; set; }
            public string Technology { get; set; }
            public string ProjectType { get; set; }
            public string UserId { get; set; }
            public DateTime StartDate { get; set; }
            public DateTime EndDate { get; set; }
            public decimal Cost { get; set; }
        }
    }
    
    
    
    
    

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, June 9, 2018 3:49 AM
  • User1658625817 posted

    Thanks so much for the detailed response!

    Monday, June 11, 2018 2:23 PM