Call Api Service from HomeController - c#

I am trying to call a method in my Api Service:
public IQueryable Get(int UserId){
return UsersRepository.SelectAll().Where(ig => ig.Id == UserId);
}
from my HomeController:
UsersService.Get(UserId);
but I get this error: An object reference is required for the non-static field, method, or property 'CTHRC.Roti.Domain.Api.Services.UsersService.Get(int)'
What am I doing wrong? Here is my UserService:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CTHRC.Roti.Domain.Data.Repositories;
using CTHRC.Roti.Domain.Model;
namespace CTHRC.Roti.Domain.Api.Services
{
public class UsersService
{
protected readonly IUsersRepository UsersRepository;
public UsersService(IUsersRepository userRespository)
{
UsersRepository = userRespository;
}
public IQueryable Get(int UserId)
{
return UsersRepository.SelectAll().Where(ig => ig.Id == UserId);
}
}
}
and here is my Home Controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebMatrix.WebData;
using CTHRC.Roti.Domain.Model;
using CTHRC.Roti.Domain.Api.Services;
using CTHRC.Roti.Domain.Data.Repositories;
namespace CTHRC.Roti.Web.UI.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
if (!WebSecurity.IsAuthenticated)
{
Response.Redirect("~/account/login");
}
int UserId = 1;
UsersService.Get(UserId);
return View();
}
}
}
here is my IUsersRespository:
using System;
using System.Linq;
using CTHRC.Roti.Domain.Model;
namespace CTHRC.Roti.Domain.Data.Repositories
{
public interface IUsersRepository : IRepository<Users>
{
}
}

You are trying to call an instance method like a static method.
You have to instansiate UsersService in order to access the Get method:
public class HomeController : Controller
{
public ActionResult Index()
{
if (!WebSecurity.IsAuthenticated)
{
Response.Redirect("~/account/login");
}
int UserId = 1;
var service = new UsersService(userRepository);
service.Get(UserId);
return View();
}
}

Related

How to get Specific Columns from Sql server in Asp.Net Core MVC [duplicate]

This question already has an answer here:
How to only select specific properties from an object graph in Entity Framework?
(1 answer)
Closed 2 years ago.
AppDbContext.cs
using Microsoft.EntityFrameworkCore;
namespace EduManSystems.Model
{
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options)
: base(options)
{
}
public DbSet<Course> Courses { get; set; }
public DbSet<Student> Student_master { get; set; }
}
}
IStudentRepository.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace EduManSystems.Model
{
public interface IStudentRepository
{
Student GetStudent(string id);
IEnumerable<Student> GetStudents();
//Student GetStudents();
Student Add(Student student);
}
}
SqlStudentRepository.cs
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Data.Common;
using Microsoft.AspNetCore.Mvc.Rendering;
namespace EduManSystems.Model
{
public class SqlStudentRepository : IStudentRepository
{
private readonly AppDbContext context;
public SqlStudentRepository(AppDbContext context)
{
this.context = context;
}
public Student GetStudent(string id)
{
return context.Student_master.Find(id);
}
public IEnumerable<Student> GetStudents()
{
return context.Student_master.FromSql("select * from student_master").ToList();
}
}
}
StudentController.cs
using EduManSystems.Model;
using EduManSystems.ViewModel;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace EduManSystems.Controllers
{
public class StudentController : Controller
{
private readonly IStudentRepository _studentRepository;
private readonly IHostingEnvironment hostingEnvironment;
public StudentController(IStudentRepository studentRepository,
IHostingEnvironment hostingEnvironment)
{
_studentRepository = studentRepository;
this.hostingEnvironment = hostingEnvironment;
}
[HttpGet]
public ViewResult Index()
{
var model = _studentRepository.GetStudents();
return View(model);
}
[HttpGet]
public JsonResult StudentList()
{
var model = _studentRepository.GetStudents();
return Json(model);
}
}
}
i tried this one, but i got error like this,
Hi Folks,
I need your help. Here, it retrieves all the data from SQL server(Raw sql queries or Linq). But, I need only specific columns like, select stud_first_name,stud_last_name from student_master;
The SQL query must return all the columns of the table. e.g. context.Student_Master.FromSql("Select Stud_First_Name, Stud_Last_Name from Student_Master).ToList() will throw an exception.
please help me
Thank You,
Use the sample below to get the property names of entity:
var names = typeof(User).GetProperties()
.Select(property => property.Name).ToArray();
public IEnumerable<Student> GetStudents()
{
return context.Student_master.Select(s => new Student { Stud_First_Name = s.Stud_First_Name, Stud_Last_Name = s.Stud_Last_Name });
}
now its working fine both View and Json
Thank you so much Guru Stron.....
First of all, if you have mapped you db structure right, you don't need .FromSql, just ToList should be sufficient enough, secondary you can do context.Student_master.Select(s=> ...).ToList()
UPD
From the comment:
You need to introduce new class which contains only needed subset of fields or (bad option) do .Select(s => new Student { Stud_First_Name = s.Stud_First_Name , Stud_Last_Name = s.Stud_Last_Name })

InvalidOperationException: Unable to resolve service for type while attempting to activate

I am creating ASP.NET CORE project using DI and Repository Pattern. When I run project I get this type of error
InvalidOperationException: Unable to resolve service for type
'AD.BLL.Servisi.IKorisnikServis' while attempting to activate
'AD.Web.Controllers.KorisnikController'.
Here is my interface class
using System;
using System.Collections.Generic;
using System.Text;
namespace AD.BLL.Interfejsi
{
public interface IKorisnik
{
public string VratiKorisnike();
}
}
And here is my Service class which call this interface
using AD.BLL.Interfejsi;
using AD.Web.Data;
using System;
using System.Collections.Generic;
using System.DirectoryServices;
using System.Linq;
using System.Reflection.PortableExecutable;
using System.Text;
namespace AD.BLL.Servisi
{
public class IKorisnikServis : IKorisnik
{
private ApplicationDbContext _db;
public IKorisnikServis(ApplicationDbContext db)
{
_db = db;
}
public string VratiKorisnike()
{
System.DirectoryServices.DirectoryEntry rootDSE = new System.DirectoryServices.DirectoryEntry("LDAP://RootDSE");
var defaultNamingContext = rootDSE.Properties["defaultNamingContext"].Value;
DirectorySearcher dssearch = new DirectorySearcher("LDAP://" + defaultNamingContext);
dssearch.Filter = "(sAMAccountName=ABCDEFGHI)";
SearchResult sresult = dssearch.FindOne();
System.DirectoryServices.DirectoryEntry dsresult = sresult.GetDirectoryEntry();
var Ime = dsresult.Properties["Ime"][0].ToString();
var Prezime = dsresult.Properties["Prezime"][0].ToString();
var LoginName = dsresult.Properties["LoginName"][0].ToString();
var Status = dsresult.Properties["Status"][0].ToString();
var AccountExpired = dsresult.Properties["AccountExpired"][0].ToString();
var PassNevExp = dsresult.Properties["PassNevExp"][0].ToString();
var DomenskaGrupa = dsresult.Properties["DomenskaGrupa"][0].ToString();
var Email = dsresult.Properties["Email"][0].ToString();
return Ime;
}
}
}
Here is my ApplicationDbContext class
using AD.Models.DbModels;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace AD.Web.Data
{
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
public DbSet<Korisnik> Korisnici { get; set; }
}
}
And here is my Controller action
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AD.BLL.Servisi;
using Microsoft.AspNetCore.Mvc;
namespace AD.Web.Controllers
{
public class KorisnikController : Controller
{
private IKorisnikServis _korisnikServis;
public KorisnikController(IKorisnikServis korisnikServis)
{
_korisnikServis = korisnikServis;
}
public IActionResult VratiKorisnike()
{
_korisnikServis.VratiKorisnike();
return View();
}
public IActionResult Index()
{
return View();
}
}
}
And in Startup.cs I register IKorisnik and IKorisnikServic
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddTransient<IKorisnik, IKorisnikServis>();
}
I checked everything but I cannot see where I made mistake. Any help ?
In your Controller you need to create the filed of type IKorisnik which is your interface instead of IKorisnikServis, So your constructor should be like this:
private IKorisnik _korisnikServis;
public KorisnikController(IKorisnik korisnikServis)
{
_korisnikServis = korisnikServis;
}
However, I would strongly recommend to consider another name for your IKorisnikServis class (KorisnikServis for example) as the prefix I is mostly using to indicate an interface, in this case it is also misleading and I believe that was the reason you have used it in your controller by mistake.

Variables is not being read by ApiController in C#

I just started learning c#, ASP.net, and I have this issue. This is the code. I have a model in the models folder called Role.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace xrakFRS.Models {
public class Role {
[Key]
public int ID { get; set; }
public string Rolename { get; set; }
public string Description { get; set; }
}
}
This is my RolesController
using xrakFRS.Data;
using xrakFRS.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;
namespace xrakFRS.Controllers {
[EnableCors("*", "*", "*"), RoutePrefix("api/roles")]
public class RolesController : ApiController{
[HttpGet]
[Route("getroles")]
public IHttpActionResult GetRoles() {
try {
using (var context = new AppDbContext()) {
var entries = context.Roles.ToList();
return Ok(entries);
}
} catch (Exception ex) {
return BadRequest(ex.Message);
}
}
[HttpPost]
[Route("postrole")]
public IHttpActionResult PostRole([FromBody] Role role) {
if (!ModelState.IsValid) return BadRequest(ModelState);
try {
using (var context = new AppDbContext()) {
context.Roles.Add(role);
context.SaveChanges();
return Ok("Entry was created");
}
} catch (Exception ex) {
return BadRequest(ex.Message);
}
}
When I try to call the api using Postman, I get this:
When I try to inspect the variables at the breakpoints, I get null values:
I get null values for "Rolename" and "Description". I am not sure why my data is not binding on the controller.
try sending raw body from Postman
{
"rolename": "Admin user for the application",
"description": "Administrator"
}
go to postman body-> select raw and from dropdown menu json
then go to body and add
{
"roleId":1,
"rolename":" bla bla",
"description" : " bla bla"
}
Try using x-www-form-urlencoded via postman and remove [FromBody] attribute. It will automatically map varriables to the object. The code will look like:
[HttpPost]
[Route("postrole")]
public IHttpActionResult PostRole(Role role) {
//Any logic here
}
How the request should look like in the Postman
Postman should look like this

Error while reading data from database in c#

I have an error in this code. I deserialize a JSON file and stored that data in the database now I want to show that data from my database.
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Web.Helpers;
using System.Web.Mvc;
using ReadingFromDb.Dto;
namespace ReadingFromDb.Controller
{
public class StudentController
{
[HttpGet]
[AllowAnonymous]
public async Task<JsonResult> GetStudents()
{
using (var context = new UNIEntities1())
{
var query = #"Select ";
var dbQuery = context.Database.SqlQuery<StudentDto>(query);
var list = await dbQuery.ToListAsync();
return Json(list,JsonRequestBehavior.AllowGet);
}
}
}
}
Error is:
JSON can not be used like method.
What should I do?
Your contoller must be extend the base class Controller in which the Json() virtual method is available:
public class StudentController : Controller
{
// your code
}
To resolve this error you can try as below
public class StudentController : Controller
{
// your code
}
[HttpGet]
[AllowAnonymous]
public async Task<JsonResult> GetStudents()
{
using (var context = new UNIEntities1())
{
var list = await context.StudentDto.ToListAsync();
return Json(list,JsonRequestBehavior.AllowGet);
}
}
What you need to do is to extend your StudentCotroller with Controller then put your code under that.
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Web.Helpers;
using System.Web.Mvc;
using ReadingFromDb.Dto;
namespace ReadingFromDb.Controller
{
public class StudentController:Controller
{
[HttpGet]
[AllowAnonymous]
public async Task<JsonResult> GetStudents()
{
using (var context = new UNIEntities1())
{
var query = #"Select ";
var dbQuery = context.Database.SqlQuery<StudentDto>(query);
var list = await dbQuery.ToListAsync();
return Json(list,JsonRequestBehavior.AllowGet);
}
}
}
}

Why is my C# MVC4 Session Wrapper Service not working?

I am trying to implement a wrapper for my session (Loose coupling so it is easy to make changes later) but I am having problems, either the storing into the session is failing, or the retrieval but I do not know which.
I would greatly appreciate it if you could take a look at my code and tell me if there is anything obviously wrong, or a better way of doing what I am trying to do. I basically want to display different things to different types of user, but when I try to access the user in the ViewContext it is null.
Any links to tutorials or examples would be gratefully accepted.
Here is my code:
User and WEB_USER_LEVEL have a one to many relationship
I have used Entity Framework to create models from my existing database
I am currently in the early stages of the project and the User is not coming from the database yet (as the structure will change) so I am creating a new User and populating it before using CurrentUserService.Login(user). i have tried pulling a user out of the data base and logging that user in but it still does not work.
ICurrentUserService.cs (in Infrastructure folder)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MyProject.Infrastructure
{
public interface ICurrentUserService
{
User CurrentUser { get; }
void SetCurrentUser(WEB_USER user);
void SetAdminStatus(bool type);
bool GetAdminStatus { get; }
void SetManagerStatus(bool type);
bool GetManagerStatus { get; }
void Login(User user);
void Logout();
int? TryGetCurrentUserId();
}
}
CurrentUserService.cs (in Infrastructure folder)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MyProject.Controllers;
using MyProject.Infrastructure.Filters;
namespace MyProject.Infrastructure
{
public class CurrentUserService : ICurrentUserService
{
public const string CurrentUserKey = "CurrentUser";
public const string CurrentUserIdKey = "CurrentUserId";
public const string IsAdminKey = "IsAdmin";
public const string IsManagerKey = "IsManager";
private readonly IDb _db;
public CurrentUserService() : this(new Db()) { }
public CurrentUserService(IDb db)
{
_db = db;
}
public User CurrentUser
{
get
{
return (User)HttpContext.Current.Items[CurrentUserKey];
}
}
public void SetCurrentUser(User user)
{
HttpContext.Current.Items[CurrentUserKey] = user;
}
public void SetAdminStatus(bool type)
{
HttpContext.Current.Session[IsAdminKey] = type;
}
public bool GetAdminStatus
{
get { return (bool)HttpContext.Current.Session[IsAdminKey]; }
}
public void SetManagerStatus(bool type)
{
HttpContext.Current.Session[IsManagerKey] = type;
}
public bool GetManagerStatus
{
get { return (bool)HttpContext.Current.Session[IsManagerKey]; }
}
public void Login(User user)
{
HttpContext.Current.Session[CurrentUserIdKey] = user.ID;
HttpContext.Current.Items[CurrentUserKey] = user;
SetManagerStatus(user.WEB_USER_LEVEL.IsManager);
SetAdminStatus(user.WEB_USER_LEVEL.RefID == 1 ? true : false);
}
public void Logout()
{
HttpContext.Current.Items[CurrentUserKey] = null;
HttpContext.Current.Session[CurrentUserIdKey] = null;
SetManagerStatus(false);
SetAdminStatus(false);
}
public int? TryGetCurrentUserId()
{
return HttpContext.Current.Session[CurrentUserIdKey] as int?;
}
}
}
Extensions.cs (in Infrastructure folder)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MyProject.Infrastructure
{
public static class Extensions
{
public static User CurrentUser(this ViewContext view)
{
return (User)view.HttpContext.Items[CurrentUserService.CurrentUserKey];
}
}
}
HomeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MyProject.Infrastructure;
using MyProject.Infrastructure.Filters;
using MyProject.ViewModels;
using MyProject.Models;
using System.Data.Objects;
namespace MyProject.Controllers
{
public class HomeController : BaseController
{
readonly IDb _db;
readonly ICurrentUserService _currentUserService;
readonly IErrorReporter _errorReporter;
public HomeController() : this(new Db(), new CurrentUserService(), new ErrorReporter()) { }
public HomeController(IDb db, ICurrentUserService currentUserService, IErrorReporter errorReporter)
{
_db = db;
_currentUserService = currentUserService;
_errorReporter = errorReporter;
}
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Login(FormCollection form)
{
// Create new user and populate
_currentUserService.Login(user);
return RedirectToAction("Home");
}
public ActionResult Home()
{
return View();
}
}
}
Trying to access in ViewContext in _Layout.cshtml when the Home view is loaded
#using MyProject.Infrastructure
#if (ViewContext.CurrentUser() != null && ViewContext.CurrentUser().WEB_USER_LEVEL.IsManager)
{
#RenderPage("~/Views/Shared/_Menu.cshtml")
}
But ViewContext.CurrentUser() is always null.
Thank you for your help!
Instead of creating an extension method on top of ViewContext, I would suggest that you create a ViewModel for your view and pass into it the data that your view needs. Remember, any external data that a view needs should be fed into it through a ViewModel. This makes for a clean one to one relationship that's easy to follow.

Categories

Resources