Tuesday, October 25, 2016

Manipulating and showing data using .NET MVC


Here is sample code for a form in which we can show and pass data in .NET using MVC architecture. This simple example will show you how to place our code in the right way by using Model View Controller architecture. Just copy paste the next code into your project and run it...

using System;  
 using System.ComponentModel.DataAnnotations;  
 using System.Collections.Generic;  
 using System.Web.Mvc;  
 namespace HelloWorldMvcApp  
 {  
      // Data models  
      public class Report  
      {  
           public int ID { get; set; }  
           public string Name { get; set; }  
      }  
      public class FileType  
      {  
           public int ID { get; set; }  
           public string Name { get; set; }  
      }  
      // View models  
      public class CronVM  
      {  
           public int ID { get; set; }  
           [Required(ErrorMessage = "Please select the name")]  
           public string Name { get; set; }  
           [Required(ErrorMessage = "Please select the frequency")]  
           [Display(Name = "Frequency")]  
           public string SelectedFrequency { get; set; }  
           public IEnumerable<SelectListItem> FrequencyList { get; set; }  
           public List<ReportVM> Reports { get; set; }  
           public IEnumerable<FileType> FileTypes { get; set; }  
      }  
      public class ReportVM  
      {  
           public int ID { get; set; }  
           public string Name { get; set; }  
           // Note you would apply a foolproof [RequiredIfTrue("IsSelected")]   
           // or similar attribute to this property  
           public int? SelectedFile { get; set; }  
           public bool IsSelected { get; set; }  
      }  
      public static class Repository  
      {  
           public static List<Report> FetchReports()  
           {  
                return new List<Report>()  
                {  
                     new Report(){ ID = 1, Name = "Report 1" },  
                     new Report(){ ID = 2, Name = "Report 2" },  
                     new Report(){ ID = 3, Name = "Report 3" }  
                };  
           }  
           public static List<FileType> FetchFileTypes()  
           {  
                return new List<FileType>()  
                {  
                     new FileType(){ ID = 1, Name = "File type 1" },  
                     new FileType(){ ID = 2, Name = "File type 2" },  
                };  
           }  
           public static List<string> FetchFrequencies()  
           {  
                return new List<string>(){ "Daily", "Weekly" };  
           }  
      }  
 }  


 using System;  
 using System.Web.Mvc;  
 using System.Collections.Generic;  
 using System.Linq;  
 namespace HelloWorldMvcApp  
 {  
      public class HomeController : Controller  
      {  
           [HttpGet]  
           public ActionResult Index()  
           {  
                var reports = Repository.FetchReports();  
                var fileTypes = Repository.FetchFileTypes();  
                var frequencies = Repository.FetchFrequencies();  
                var model = new CronVM()  
                {  
                     FileTypes = fileTypes,  
                     FrequencyList = new SelectList(frequencies),  
                     Reports = reports.Select(x => new ReportVM()  
                     {  
                          ID = x.ID,  
                          Name = x.Name,                           
                     }).ToList()  
                };  
                return View(model);  
           }  
           [HttpPost]  
           public ActionResult Index(CronVM model)  
           {  
                var selected = model.Reports.Where(x => x.IsSelected).Select(x => x.Name);  
                var message = string.Format("You selected reportss {0}", String.Join(" and ", selected));  
                return Content(message);  
           }  
      }  
  } 


 @model HelloWorldMvcApp.CronVM  
 @{  
      Layout = null;  
 }  
 <!DOCTYPE html>  
 <!-- template from http://getbootstrap.com/getting-started -->  
 <html lang="en">  
      <head>  
           <meta charset="utf-8">  
           <meta http-equiv="X-UA-Compatible" content="IE=edge">  
           <meta name="viewport" content="width=device-width, initial-scale=1">  
           <title>Bootstrap 101 Template</title>  
           <!-- CSS Includes -->  
           <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">  
           <style type="text/css">  
                .field-validation-error {  
                     color: #ff0000;  
                }  
                table {  
                     width: 100%;  
                }  
                td {  
                     padding: 2px 0;  
                }  
                td:first-child {  
                     width: 25px;  
                }  
                td:last-child {  
                     width: 150px;  
                }  
           </style>  
      </head>  
      <body>  
           <div class="container">  
                <div class="col-md-6 col-md-offset-3">  
                     <h1>Hello Big Bang Code</h1>  
                     @using (Html.BeginForm())  
                     {  
                          <div class="form-group">  
                               @Html.LabelFor(m => m.Name)  
                               @Html.TextBoxFor(m => m.Name, new { @class="form-control" })   
                               @Html.ValidationMessageFor(m => m.Name)  
                          </div>  
                          <div class="form-group">  
                               @Html.LabelFor(m => m.SelectedFrequency)  
                               @Html.DropDownListFor(m => m.SelectedFrequency, Model.FrequencyList, "-Please select-", new { @class="form-control" })   
                               @Html.ValidationMessageFor(m => m.SelectedFrequency)  
                          </div>  
                          <table>  
                               @for (int i = 0; i < Model.Reports.Count; i++)  
                               {  
                                    <tr>  
                                         <td>  
                                              @Html.HiddenFor(m => m.Reports[i].ID)  
                                              @Html.HiddenFor(m => m.Reports[i].Name)  
                                              @Html.CheckBoxFor(m => m.Reports[i].IsSelected)  
                                         </td>  
                                         <td>@Model.Reports[i].Name</td>  
                                         <td>  
                                              @Html.DropDownListFor(m => m.Reports[i].SelectedFile, new SelectList(Model.FileTypes, "ID", "Name"), "-Please select-", new { @class="form-control" })  
                                              @Html.ValidationMessageFor(m => m.Reports[i].SelectedFile)  
                                         </td>  
                                    </tr>  
                               }  
                          </table>  
                          <button type="submit" class="btn btn-success submit">Create</button>  
                     }  
                </div>  
           </div>  
           <!-- JS includes -->  
           <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>  
           <script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>  
           <script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>  
           <script src="//ajax.aspnetcdn.com/ajax/mvc/4.0/jquery.validate.unobtrusive.min.js"></script>  
           <script type="text/javascript">  
           </script>  
      </body>  
 </html>


And this is how our app should look like...enjoy






Programming thought of the day:
  • In a world without fences and walls, who needs Gates and Windows?
  • =)

C# - Dependency Injection and Controllers in .NET 4 (MVC)


Dependency injection is a technique that follows the Dependency Inversion Principle, allowing for applications to be composed of loosely coupled modules. ASP.NET Core has built-in support for dependency injection, which makes applications easier to test and maintain.

ASP.NET Core’s built-in support for constructor-based dependency injection extends to MVC controllers. By simply adding a service type to your controller as a constructor parameter, ASP.NET Core will attempt to resolve that type using its built in service container. Services are typically, but not always, defined using interfaces. For example, if your application has business logic that depends on the current time, you can inject a service that retrieves the time (rather than hard-coding it), which would allow your tests to pass in implementations that use a set time.

For this exercise we are going to need Unity package installed in our Visual Studio.
Go to Tools -> NuGet Package Manager and browse for Unity and click "install"

Create a folder and name it "Interfaces", then create interface "IDateTime":
using System;

namespace ControllerDI.Interfaces
{
    public interface IDateTime
    {
        DateTime Now { get; }
    }
}
Create another folder and name it "Services".Add a class and name it "SystemDateTime"
using System;
using ControllerDI.Interfaces;

namespace ControllerDI.Services
{
    public class SystemDateTime : IDateTime
    {
        public DateTime Now
        {
            get { return DateTime.Now; }
        }
    }
}
With this in place, we can use the service in our controller. In this case, we have added some logic to the HomeController Index method to display a greeting to the user based on the time of day.
using ControllerDI.Interfaces;
using Microsoft.AspNetCore.Mvc;

namespace ControllerDI.Controllers
{
    public class HomeController : Controller
    {
        private readonly IDateTime _dateTime;

        public HomeController(IDateTime dateTime)
        {
            _dateTime = dateTime;
        }

        public IActionResult Index()
        {
            var serverTime = _dateTime.Now;
            if (serverTime.Hour < 12)
            {
                ViewData["Message"] = "It's morning here - Good Morning!";
            }
            else if (serverTime.Hour < 17)
            {
                ViewData["Message"] = "It's afternoon here - Good Afternoon!";
            }
            else
            {
                ViewData["Message"] = "It's evening here - Good Evening!";
            }
            return View();
        }
    } 
}
When we use dependency injection is important to remember that we need to "tell" the compiler that we need our object ready when we call our class. At the moment we installed Unity plugin, some files are created, find UnityConfig.cs and open it.
In "public static void RegisterTypes" method add: container.RegisterType<IDateTime, SystemDateTime>(); Save and compile your project. If you see any problem related to some UserManager initialization, you might need to the next lines under the code you just addedabove:
container.RegisterType<DbContext, ApplicationDbContext>(new HierarchicalLifetimeManager());
container.RegisterType<UserManager<ApplicationUser>>(new HierarchicalLifetimeManager());
container.RegisterType<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>(new HierarchicalLifetimeManager());
container.RegisterType<AccountController>(new InjectionConstructor());
Now, save and compile again. 





Programming Thought of the day

If you give someone a program, you will frustrate them for a day; if you teach
them how to program, you will frustrate them for a lifetime. =)