Mvc creating route attribute - c#

I want to create a route attribute in the Porosi controller, in the detaje method that takes as a DatePorosie (DatePorosie is the date) on parameter. The method must display from Porosi.cs class EmriPorosise, DatePorosie, TotaliPorosise according to the date that comes as a parameter in url. (sending date value either by form or by link). I hope I explained it well. Can you help me please???
This is Porosi.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MvcProjektDb.Models
{
public class Porosi
{
public int PorosiId { get; set; }
public string EmriPorosise { get; set; }
public DateTime DatePorosie { get; set; }
public int TotaliPorosise { get; set; }
public int? KlienteId { get; set; }
public virtual Kliente Kliente { get; set; }
}
}
This is PorosiController.cs but I don't know what to do here
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcProjektDb.Migrations;
using MvcProjektDb.Models;
namespace MvcProjektDb.Controllers
{
public class PorosiController : Controller
{
private ApplicationDbContext _db;
public PorosiController()
{
_db = new ApplicationDbContext();
}
protected override void Dispose(bool disposing)
{
_db.Dispose();
}
// GET: Porosi
public ActionResult Index()
{
return View();
}
[Route("Porosi/detaje/{dateporosie?}")]
public ActionResult detaje(DateTime? dateporosie)
{
var x = _db.porosi.Where(p => p.DatePorosie == dateporosie).ToList();
return View(x);
}
}
}

Related

InvalidOperationException: Unable to resolve service

first sorry if my english isn't good enough XD. Second, I'm programing on ASP.NET Core 2.0. And when i launch my webapp i get the next error when i try to go to the "Clases" web page of my App.
InvalidOperationException: Unable to resolve service for type 'EduCloud.Data.IClassInfo' while attempting to activate 'EduCloud.Controllers.UnitsController'.
Before all, sorry if it is too much code. The code for the Model involve is
using System;
using System.Collections.Generic;
using System.Text;
namespace EduCloud.Data.Models
{
public class ClassInfo
{
public int Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string ClassVideoUrl { get; set; }
public string ClassHomeworkUrl { get; set; }
public string TestUrl { get; set; }
public virtual ApplicationUser User { get; set; }
public virtual Forum Forum { get; set; }
}
}
This Model has 1 level of abstraction with the class
using EduCloud.Data.Models;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace EduCloud.Data
{
public interface IClassInfo
{
ClassInfo GetById(int id);
IEnumerable<ClassInfo> GetAll();
IEnumerable<ClassInfo> GetFilteredClasses(Forum forum, string searchQuery);
IEnumerable<ClassInfo> GetFilteredClasses(string searchQuery);
IEnumerable<ClassInfo> GetClassesByForum(int id);
Task Add(ClassInfo classInfo);
Task Delete(int id);
Task EditClassContent(int id, string newContent);
}
}
Next, the methods of the this IClass are in the next class
using EduCloud.Data;
using EduCloud.Data.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EduCloud.Service
{
public class ApplicationClassService : IUnit
{
private readonly ApplicationDbContext _context;
public ApplicationClassService(ApplicationDbContext context)
{
_context = context;
}
public async Task Create(ClassInfo classInfo)
{
_context.Add(classInfo);
await _context.SaveChangesAsync();
}
public Task Delete(int classId)
{
throw new NotImplementedException();
}
public IEnumerable<Forum> GetAll()
{
return _context.Forums
.Include(forum => forum.Classes);
}
public Forum GetById(int id)
{
var forum = _context.Forums.Where(f => f.Id == id)
.Include(f => f.Classes ).ThenInclude(p => p.User)
//.Include(f => f.Classes).ThenInclude(p => p.Replies).ThenInclude(r => r.User)
.FirstOrDefault();
return forum;
}
public Task UpdateForumTitle(int classId, string newTitle)
{
throw new NotImplementedException();
}
}
}
Finally the Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using EduCloud.Data;
using EduCloud.Data.Models;
using EduCloud.Models.Classes;
using EduCloud.Models.Units;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
namespace EduCloud.Controllers
{
public class UnitsController : Controller
{
private readonly IUnit _unitService;
private readonly IForum _forumService;
private readonly IClassInfo _classService;
public UnitsController(IUnit unitService, IForum forumService, IClassInfo classService)
{
_unitService = unitService;
_forumService = forumService;
_classService = classService;
}
public IActionResult Index()
{
var units = _unitService.GetAll()
.Select(forum => new UnitsListingModel
{
Id = forum.Id,
Name = forum.Title,
});
var model = new UnitsIndexModel
{
UnitList = units
};
return View(model);
}
}
}
And the code of the view that i try to run when i go to the "Clases" link
#model EduCloud.Models.Units.UnitsIndexModel
<h1>Unidades de Aprendizaje</h1>
<table class="table table-hover" id="forumIndexTable">
<tbody>
#foreach (var forum in Model.UnitList)
{
<tr>
<td>
<a asp-controller="Units" asp-action="ClassesList" asp-route-id="#forum.Id">
#forum.Name
</a>
</td>
</tr>
}
</tbody>
</table>

CRUD WEB API with entity framework

I started develop my project - web application with Database. I used WEB API with entity framework
I need CRUD operations realize in my project.
Read - work fine
But I don't know how realize Create, Update, Delete; I don't have enough experience and be glad yours advice.
I tried realize good architecture of my application - using repository pattern and fabric pattern. If you have advice in architecture of my project , I'll be grateful you.
I don't know how realize it in value controller and repository, could you help please?
Attach my code:
Repository
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WebAPI
{
public class CustomerRepository
{
public IQueryable<Customer> GetAllCustomers()
{
DevelopersEntities dev = new DevelopersEntities();
return dev.Customers;
}
public IQueryable<Customer> GetAllCustomers(int id)
{
DevelopersEntities dev = new DevelopersEntities();
return dev.Customers.Where(c=>c.Id==id).Select(e=>e);
}
public IQueryable<Customer> DeleteCustomer(int id)
{
DevelopersEntities dev = new DevelopersEntities();
return dev.Customers.Remove(id);
}
public IQueryable<Customer> CreateCustomer()
{
DevelopersEntities dev = new DevelopersEntities();
}
public IQueryable<Customer> UpdateCustomer(int id)
{
DevelopersEntities dev = new DevelopersEntities();
}
}
}
Customer model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WebAPI;
namespace DevelopersWeb.Models
{
public class CustomerModel
{
public int CustomerId { get; set; }
public string CustomerName { get; set; }
public IEnumerable<HardwareModel> Hardware { get; set; }
public IEnumerable<SoftwareModel> Software { get; set; }
}
}
Harware Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace DevelopersWeb.Models
{
public class HardwareModel
{
public int HardwareId { get; set; }
public string HardwareName { get; set; }
}
}
Software Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace DevelopersWeb.Models
{
public class SoftwareModel
{
public int SoftwareId { get; set; }
public string SoftwareName { get; set; }
}
}
Model Factory
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WebAPI;
namespace DevelopersWeb.Models
{
public class ModelFactory
{
public CustomerModel Create(Customer customer)
{
return new CustomerModel()
{
CustomerId = customer.Id,
CustomerName = customer.Name,
Hardware = customer.HardWares.Select(h=>Create(h)),
Software = customer.Softwares.Select(c=>Create(c))
};
}
public HardwareModel Create(HardWare hardware)
{
return new HardwareModel()
{
HardwareId = hardware.HardWareId,
HardwareName = hardware.HardWareName,
};
}
public SoftwareModel Create(Software software)
{
return new SoftwareModel()
{
SoftwareId = software.SoftwareId,
SoftwareName = software.SoftwareName
};
}
}
}
Value Controller
using DevelopersWeb.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebAPI;
namespace DevelopersWeb.Controllers
{
public class ValuesController : ApiController
{
ModelFactory _modelFactory;
public ValuesController()
{
_modelFactory = new ModelFactory();
}
// GET api/values
public IEnumerable<CustomerModel> Get()
{
CustomerRepository cr = new CustomerRepository();
return cr.GetAllCustomers().ToList().Select(c=> _modelFactory.Create(c));
}
// GET api/values/5
public string Get(int id)
{
return "xxx";
}
// POST api/values
public void Post([FromBody]string value)
{
}
// PUT api/values/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
public void Delete(int id)
{
}
}
}
Here is how you should save customer object:
public void CreateCustomer(Customer customer)
{
DevelopersEntities dev = new DevelopersEntities();
dev.Customers.Add(customer)
dev.SaveChanges();
}
Here is you api action:
// POST api/values
public void Post([FromBody]CustomerModel customerModel)
{
//Here you should transform CustomerModel object to customerEntity
CustomerRepository cr = new CustomerRepository();
cr.CreateCusomer(customer);
return Ok();
}
You should think about using Dependency Injection pattern here as well.

GetSnapshotAsync() never returning and I don't get any errors. How can I debug this issue?

I'm trying Firestore with the nugget package Google.Cloud.Firestore
I followed this intro CRUD with firestore
Using the debugger I can see that the execution of the program stops when trying to call the method Query.GetSnapshotAsync()
I want to get just a list of documents from a collection.
Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web.Http;
using System.Web.Http.Results;
using FirestoreAPI.Domain.Restaurants;
using FirestoreAPI.Repository.Restaurants;
using System.Threading.Tasks;
namespace FirestoreAPI.Controllers
{
[RoutePrefix("api")]
public class RestaurantsController : ApiController
{
public RestaurantsController() { }
[HttpGet]
[Route("restaurants")]
public IHttpActionResult GetAllRestaurants()
{
//var restAggregate = new RestaurantsAggregate();
var restaurantsRepo = new RestaurantsRepo();
return new NegotiatedContentResult<Task<List<Restaurant>>>(
HttpStatusCode.OK,
restaurantsRepo.GetAllRestaurants(),
this
); ;
}
}
}
DataLayer
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using Google.Cloud.Firestore;
namespace FirestoreAPI.Repository.Restaurants
{
public class RestaurantsRepo
{
//public FirestoreConn dbConn;
string projectId;
FirestoreDb firestoreDb;
public RestaurantsRepo()
{
//dbConn = new FirestoreConn();
string credentials = "C:\\Users\\ezequiel.lopez\\projects\\firestoredotnet\\FirestoreAPI\\firestoreapi-dca55-0be2f7d57f41.json";
Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", credentials);
projectId = "firestoreapi-dca55";
firestoreDb = FirestoreDb.Create(projectId);
}
public async Task<List<Restaurant>> GetAllRestaurants()
{
//FirestoreDb fsDB = dbConn.GetFSConnection();
//Query query = fsDB.Collection("restaurants").OrderByDescending("avgRating").Limit(50);
Query query = firestoreDb.Collection("restaurants").OrderByDescending("avgRating").Limit(50);
QuerySnapshot restSnaps = await query.GetSnapshotAsync();
List<Restaurant> restaurants = new List<Restaurant>();
return restSnaps.Documents
.Where<DocumentSnapshot>(ds => ds.Exists)
.Select(ds => ds.ConvertTo<Restaurant>()).ToList();
}
}
}
Restaurant
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Google.Cloud.Firestore;
namespace FirestoreAPI.Repository.Restaurants
{
[FirestoreData]
public class Restaurant
{
[FirestoreProperty]
public decimal avgRating { get; set; }
[FirestoreProperty]
public string category { get; set; }
[FirestoreProperty]
public string city { get; set; }
[FirestoreProperty]
public string name { get; set; }
[FirestoreProperty]
public int numRatings { get; set; }
[FirestoreProperty]
public int price { get; set; }
}
}
I was having the same issue. Thing is, I was calling an async method from a synchronous one. It didn't work until I've made my caller method async and awaited for it.

Null entry for parameter Id/Can't add data from other model into view

I'm new to learning asp.net and I'm trying to output table data from two different tables in one view. I'm getting the following error
The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Details(Int32)' in 'Vidly12.Controllers.CustomerController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
Parameter name: parameters
This line of code is triggering the error
#Model.MembershipType.MembershipName
in the Details.cshtml
I can't figure out how integrate this table and its data into table. The MembershipName outputs correctly in the CustomerView.chtml so it's associating the customer to the membership name correctly for that view, but not in the Details.cshtml view. Any help is appreciated. Let me know if any additional information is needed
Details.cshtml
#model Vidly12.Models.Customer
#using Vidly12.Models
#{
ViewBag.Title = "Details";
}
<h2>#Model.Name</h2>
<ul>
<li>#Model.MembershipType.MembershipName</li>
<li>#Model.BirthDate</li>
</ul>
CustomerController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Vidly12.Models;
using System.Data.Entity;
using Vidly12.ViewModel;
namespace Vidly12.Controllers
{
public class CustomerController : Controller
{
private ApplicationDbContext _context;
public CustomerController()
{
_context = new ApplicationDbContext();
}
public ActionResult CustomerView()
// GET: Customeriew(int id)
{
var customer = _context.Customer.Include(c => c.MembershipType).ToList();
return View(customer);
}
public ActionResult Details(int id)
{
var customer = _context.Customer.SingleOrDefault(c => c.Id == id);
if (customer == null)
return HttpNotFound();
return View(customer);
}
protected override void Dispose(bool disposing)
{
_context.Dispose();
}
}
}
Customer.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Vidly12.Models
{
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime BirthDate { get; set; }
public MembershipType MembershipType { get; set; }
}
}
MembershipType.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Vidly12.Models
{
public class MembershipType
{
public byte Id { get; set; }
public string MembershipName { get; set; }
public byte Duration { get; set; }
public byte DiscountRate { get; set; }
}
}
CustomerView.cshtml
In your Details.cshtml view, you have this line of code:
#Model.MembershipType.MembershipName
But you are passing this as the model to the above view:
var customer = _context.Customer.SingleOrDefault(c => c.Id == id);
The MembershipType property is null so you are getting the error. You need to do this to eagerly load the MembershipType property:
var customer = _context.Customer.Include(
c => c.MembershipType).SingleOrDefault(c => c.Id == id);

Didn't show data from database

I would like to show all data from database.
But it doesn't work.
My Web.config file
<connectionStrings>
<add name="EFDbContext" providerName="System.Data.SqlClient"
connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=NewsList;Integrated Security=True"/>
Controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NewsList.Domain.Abstract;
using NewsList.Domain.Entities;
namespace NewsList.WebUI1.Controllers
{
public class NewsController : Controller
{
//
// GET: /News/
private INewsRepository repository;
public NewsController(INewsRepository newsRepository)
{
this.repository = newsRepository;
}
public ViewResult List()
{
return View(repository.NewsList);
}
public ActionResult Index()
{
return View();
}
}
}
Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NewsList.Domain.Entities
{
public class News
{
public int NewsID { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string Text { get; set; }
}
}
View
#model IEnumerable<NewsList.Domain.Entities.News>
#{
ViewBag.Title = "News";
}
#foreach (var p in Model)
{
<div class="item">
<h3>#p.Title</h3>
#p.Description
<h4>#p.Text</h4>
</div>
}
And now I haven't got any exeptions. Only clear while browser page.
Just as an example:
public class NewsRepository : INewsRepository
{
private YourDbContext db = null;
public List<NewsList> NewsList
{
return this.db.NewsList.ToList();
}
public NewsRepository()
{
this.db = new NewsRepository();
}
}
public class YourDbContext : DbContext
{
public DbSet<NewsList> NewsList {get; set;}
}

Categories

Resources