Code
using System.Web;
abstract class CookieHandler
{
public CookieHandler(string domain)
{
CookieDomain = domain;
}
public string CookieDomain { get; set; }
public abstract void SetCookie(HttpContextBase context, CookieHandler value);
}
HttpContextBase gives me the error "type or namespace HttpContextBase cannot be found" Same error when i try HttpContext. I am trying to figure out why I cannot take in this object anymore.
I am using .NET Framework 4.5.2 and have it has a Library class project.
Per recommendation from user comment, the issue was I had to reference the assembly system.web.dll
Related
I need to make a custom implementation for the input field, so I created the following class:
[HtmlTargetElement("input", Attributes = "tm-for", TagStructure = TagStructure.WithoutEndTag)]
public class TmInputTagHelper : InputTagHelper
{
public TmInputTagHelper(IHtmlGenerator generator) : base(generator)
{
}
[HtmlAttributeName("tm-for")]
public ModelExpression TmFor
{
get => For;
set => For = value;
}
public override void Process(TagHelperContext context, TagHelperOutput output)
{
base.Process(context, output);
string fullName = NameAndIdProvider.GetFullHtmlFieldName(ViewContext, For.Name);
if (ViewContext.ViewData.ModelState.TryGetValue(fullName, out var entry) && entry.Errors.Count > 0)
{
output.AddClass("is-invalid", HtmlEncoder.Default);
output.RemoveClass("input-validation-error", HtmlEncoder.Default);
}
}
}
However, I can't find the reference for this class: NameAndIdProvider:
string fullName = NameAndIdProvider.GetFullHtmlFieldName(ViewContext, For.Name);
I have the following usings:
using Microsoft.AspNetCore.Mvc.TagHelpers;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;
using System.Text.Encodings.Web;
Well, I don't know how I can get past that anymore!
You may use asp.net core 3 or higher, but NameAndIdProvider is an assembly below 2.2, which is the source code.
The scope of Internal is limited to a certain assembly, but the assembly here is different, so it cannot be referenced. A better way is to customize this function in current project according to above GetFullHtmlFieldName.
This is my first ever project in ASP.NET MVC 5 and C# in general. I'm trying to make a simple CRM web app.
When I try to set roles in my seed method I get the following error after executing the Update-Database command:
The entity type IdentityRole is not part of the model for the current context.
I've searched a lot but didn't find a solution yet.
Configuration.cs
using System.Collections.Generic;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using simpleCRM.Models;
namespace simpleCRM.Migrations
{
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
internal sealed class Configuration : DbMigrationsConfiguration<simpleCRM.DAL.crmContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
ContextKey = "simpleCRM.DAL.crmContext";
}
protected override void Seed(simpleCRM.DAL.crmContext context) //Takes our context as input
{
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
//Creating the admin role
if (!roleManager.RoleExists("Director"))
{
//Admin role
var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole("Director");
roleManager.Create(role);
}
context.SaveChanges();
}
}
crmContext.cs
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using simpleCRM.Models;
/*A class that coordinates the Entity Framework functionality for a given data model.
It derives from System.Data.Entity.DbContext class*/
namespace simpleCRM.DAL
{
public class crmContext: DbContext
{
public crmContext() : base("crmContext")//Passing the connection string to the constructor
{
}
public DbSet<Customer> Customers { get; set; }
public DbSet<Call> Calls { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingEntitySetNameConvention>();
}
}
}
What might be the cause of the error?
I have the following problem with the .NET Core and Entity Framework.
I created myself the .NET Core project, I added DbContext and all the rest. My problem is that I can download the data without the slightest problem, unfortunately I can not save them, i.e. I have the Add method, but I do not have the SaveChanges method.
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using CRM.Model.Entities;
namespace CRM.Model.Concrete
{
public abstract class ApplicationContext : IdentityDbContext<ApplicationUser>
{
public ApplicationContext(DbContextOptions<ApplicationContext> options) : base(options)
{
}
public DbSet<Category> Categories { get; set; }
public DbSet<Subcategory> Subcategories { get; set; }
public DbSet<SubcategoryL2> SubcategoriesL2 { get; set; }
public DbSet<Event> Events { get; set; }
public DbSet<ApplicationUser> Users { get; set; }
public DbSet<Coupon> Coupons { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<SubcategoryL2>().ToTable("Subs");
#region "Seed Data"
builder.Entity<IdentityRole>().HasData(
new { Id = "1", Name = "Admin", NormalizedName = "ADMIN" },
new { Id = "2", Name = "User", NormalizedName = "USER" }
);
#endregion
}
}
}
ICouponRepository
using System.Threading.Tasks;
using CRM.Model.Concrete;
namespace CRM.Repository.Abstract
{
public interface ICouponRepository
{
Task AddCoupon(Coupon coupon);
}
}
CouponRepository
using System.Threading.Tasks;
using CRM.Model.Concrete;
using CRM.Repository.Abstract;
namespace CRM.Repository.Concrete
{
public class CouponRepository : ICouponRepository
{
private readonly ApplicationContext _applicationContext;
public CouponRepository(ApplicationContext applicationContext)
{
_applicationContext = applicationContext;
}
public async Task AddCoupon(Coupon coupon)
{
await _applicationContext.Coupons.AddAsync(coupon);
await _applicationContext.SaveChangesAsync();
}
}
}
And the problem is here in CouponRepository, i.e.
I have no idea how I can fix it and why it does not work :(
CS1061 The "ApplicationContext" element does not contain the
definition of "SaveChangesAsync" and the available "SaveChangesAsync"
extension method was not found, which takes the first argument of the
"ApplicationContext" type (does not the using directive or the kit
reference?).
Second error
CS0012 C # The "IdentityDbContext <>" type is defined in an
unreferenced set. You must add a reference to the set
"Microsoft.AspNetCore.Identity.EntityFrameworkCore, Version = 2.2.0.0,
Culture = neutral, PublicKeyToken = adb9793829ddae60"
My project is divided into several smaller ones, that is, the main CRM project. In it there are several smaller ones:
CRM.Core
CRM.Services
CRM.Repository
CRM.Resources
CRM.Model
The problem is that without the slightest problem I use the ApplicationContext to retrieve data from the database, unfortunately I can not save any data with it, because the error pops up like in the picture.
when i change
public abstract class ApplicationContext :
IdentityDbContext
to
public abstract class ApplicationContext : DbContext
then all is Ok, but then Identity will not work for me
Solution:
The solution to my problem was to install the Microsoft.AspNetCore.Identity.EntityFrameworkCore package through the NuGet Package.
First of all you need to be calling SaveChangesAsync against the context, not the DbSet, so you should be writing this:
await _applicationContext.SaveChangesAsync();
Secondly, as a bonus, you shouldn't be using AddAsync unless you really need to, you should be doing this:
_applicationContext.Coupons.Add(coupon);
The docs state:
This method is async only to allow special value generators, such as the one used by 'Microsoft.EntityFrameworkCore.Metadata.SqlServerValueGenerationStrategy.SequenceHiLo', to access the database asynchronously. For all other cases the non async method should be used.
From the second error message it is clear what you have to do. Install Microsoft.AspNetCore.Identity.EntityFrameworkCore nuget package to the project where CouponRepository is located as follows:
PM> Install-Package Microsoft.AspNetCore.Identity.EntityFrameworkCore -Version 2.2.0
Or you can also add Microsoft.AspNetCore.App meta-package to your CouponRepository project by adding the following item.
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>
The error should go away now!
I'm using Visual Studio 2015 and have the below code in my MVC project:
using Microsoft.AspNet.Mvc;
using Microsoft.Owin.Security;
using System.Web;
// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860
namespace Site.Controllers
{
public class AccountController : Controller
{
private IAuthenticationManager AuthenticationManager
{
get
{
return HttpContext.GetOwinContext().Authentication;
}
}
// GET: /<controller>/
public IActionResult Login()
{
return View();
}
}
}
I keep getting an error stating:
The name 'HttpContext' does not exist in the current context MySolution.DNX 4.5.1
I've added the following Nuget packages:
Microsoft.AspNet.Identity.Owin
Microsoft.Owin.Host.SystemWeb
Microsoft.Owin.Security
Is there anyway around this?
If your using Asp.Net 6 (vNext):
private readonly IHttpContextAccessor contextAccessor;
public MyComponent(IHttpContextAccessor contextAccessor) {
this.contextAccessor = contextAccessor;
}
public string GetDataFromSession() {
return contextAccessor.HttpContext.Session.GetString(*KEY*);
}
You now access the HttpContext in this manner. I hope this helps.
I have three asp.net mvc 5 projects in one solution. The solution is called Bank24 so the assembly too. Project Application_layer is main project. Also there is 2 more projects. There are BusinessLogic_layer where I'm working with database and Data layer where I'm creating database.
When I attempting to use class from BusinessLogic_layer in Application_layer I'm getting runtime server error -
Could not load type "BusinessLogic_layer.Services.DataService" from assembly "Bank24, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=null"
Project Application_layer already has reference to BusinessLogic_layer. Directory that contains needed class already linked with Using directive. So I don't know why it doesen't loading.
Here is code of Controller MainController. I need to use desired class in method Register. It is linked with using BusinessLogic_layer.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using Application_layer.Models;
using BusinessLogic_layer.Services;
namespace Application_layer.Controllers
{
[Authorize]
public class MainController : Controller
{
...
public UserManager<ApplicationUser> UserManager { get; private set; }
[HttpGet]
[AllowAnonymous]
//[ValidateAntiForgeryToken]
public void Register()
{
var user = new ApplicationUser() { UserName = "Admin" };
var result = UserManager.Create(user, "q1w2e3");
if (result.Succeeded)
{
DataService dataWorker = new DataService();
dataWorker.CreateUser("Admin", "Суренко Иван Васильевич", 0);
RedirectToAction("Login", "Authorization");
}
}
}
}
Here is code of DataService class which is in Services folder of another project
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using BusinessLogic_layer.Models;
using Data_layer.DataAccess;
using Data_layer.Models;
namespace BusinessLogic_layer.Services
{
public class DataService
{
...
public void CreateUser(string login, string name, byte role)
{
bool isEmployee = false;
if (role == 0)
isEmployee = true;
BankContext db = new BankContext();
db.Users.Add(new User() { Login = login, Name = name, Role = role, IsEmployee = isEmployee });
db.SaveChanges();
}
...
}
}
P.S. I have Visual Studio 2013
I've solved this problem. I started new project and begun testing. After a couple of hours I found several things. 1. Projects must be in different assemblys nevertheless they can be in one solution. I don't know why CLR could not load type when they are in same assembly. 2. It follows from 1 - all projects except main project must have empty project type.