I've create a base class for my Views like this:
public abstract class BaseViewPage : WebViewPage
{
public virtual new CustomPrincipal User
{
get
{
if (base.User == null) return null;
return base.User as CustomPrincipal;
}
}
}
public abstract class BaseViewPage<TModel> : WebViewPage<TModel>
{
public virtual new CustomPrincipal User
{
get
{
if (base.User == null) return null;
return base.User as CustomPrincipal;
}
}
public override void Execute()
{
throw new NotImplementedException();
}
}
and in my model I have:
public class SecureAreaModel : BaseViewPage
{
public int MyUserID
{
get { return User.ID; }
private set { }
}
public SecureAreaModel(ControllerContext controllerContext)
{
}
public override void Execute()
{
throw new NotImplementedException();
}
}
I want to use the propertiy MyUserID but I receive this error:
Error
At this point the user is autenticated
protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
{
HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
if (authCookie != null)
{
FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
JavaScriptSerializer serializer = new JavaScriptSerializer();
CustomPrincipalSerializeModel serializeModel = serializer.Deserialize<CustomPrincipalSerializeModel>(authTicket.UserData);
CustomPrincipal customer = new CustomPrincipal(serializeModel.Email);
customer.ID = serializeModel.ID;
customer.Email = serializeModel.Email;
customer.FirstName = serializeModel.FirstName;
customer.LastName = serializeModel.LastName;
customer.Roles = serializeModel.Roles;
HttpContext.Current.User = customer;
}
else
{
HttpContext.Current.User = new CustomPrincipal(string.Empty);
}
}
Any help will be appreciated! Thx
Related
I am beginner with SignalR and SQLDepedency. I am trying to implement SignalR using EF Code First Approach. I am getting the error The sqlparameter is already contained by another sqlparametercollection if I am using where condition in LINQ class.
public class MessageHub : Hub
{
internal NotifierEntity NotifierEntity { get; private set; }
private MyDbContext db = new MyDbContext();
public void DispatchToClient()
{
Clients.All.broadcastMessage("Refresh");
}
public void Initialize(String userName)
{
if (!string.IsNullOrEmpty(userName))
{
NotifierEntity = db.GetNotifierEntity<Messages>(db.Messages.Where(x=>x.ApplicationUser.UserName== userName && !x.Status));
if (NotifierEntity == null)
return;
Action<String> dispatcher = (t) => { DispatchToClient(); };
PushSqlDependency.Instance(NotifierEntity, dispatcher);
}
}
}
The NotifierEntity Class
public class NotifierEntity
{
ICollection<SqlParameter> sqlParameters = new List<SqlParameter>();
public String SqlQuery { get; set; }
public String SqlConnectionString { get; set; }
public ICollection<SqlParameter> SqlParameters
{
get
{
return sqlParameters;
}
set
{
sqlParameters = value;
}
}
public static NotifierEntity FromJson(String value)
{
if (String.IsNullOrEmpty(value))
throw new ArgumentNullException("NotifierEntity Value can not be null!");
return new JavaScriptSerializer().Deserialize<NotifierEntity>(value);
}
}
public static class NotifierEntityExtentions
{
public static String ToJson(this NotifierEntity entity)
{
if (entity == null)
throw new ArgumentNullException("NotifierEntity can not be null!");
return new JavaScriptSerializer().Serialize(entity);
}
}
public class PushSqlDependency
{
static PushSqlDependency instance = null;
readonly SqlDependencyRegister sqlDependencyNotifier;
readonly Action<String> dispatcher;
public static PushSqlDependency Instance(NotifierEntity notifierEntity, Action<String> dispatcher)
{
if (instance == null)
instance = new PushSqlDependency(notifierEntity, dispatcher);
return instance;
}
private PushSqlDependency(NotifierEntity notifierEntity, Action<String> dispatcher)
{
this.dispatcher = dispatcher;
sqlDependencyNotifier = new SqlDependencyRegister(notifierEntity);
sqlDependencyNotifier.SqlNotification += OnSqlNotification;
}
internal void OnSqlNotification(object sender, SqlNotificationEventArgs e)
{
dispatcher("Refresh123");
}
}
public class SqlDependencyRegister
{
public event SqlNotificationEventHandler SqlNotification;
readonly NotifierEntity notificationEntity;
internal SqlDependencyRegister(NotifierEntity notificationEntity)
{
this.notificationEntity = notificationEntity;
RegisterForNotifications();
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security",
"CA2100:Review SQL queries for security vulnerabilities")]
void RegisterForNotifications()
{
using (var sqlConnection = new SqlConnection(notificationEntity.SqlConnectionString))
using (var sqlCommand = new SqlCommand(notificationEntity.SqlQuery, sqlConnection))
{
foreach (var sqlParameter in notificationEntity.SqlParameters)
{
sqlCommand.Parameters.Add(sqlParameter);
}
sqlCommand.Notification = null;
var sqlDependency = new SqlDependency(sqlCommand);
sqlDependency.OnChange += OnSqlDependencyChange;
if (sqlConnection.State == ConnectionState.Closed)
sqlConnection.Open();
sqlCommand.ExecuteNonQuery();
}
}
void OnSqlDependencyChange(object sender, SqlNotificationEventArgs e)
{
if (SqlNotification != null)
SqlNotification(sender, e);
RegisterForNotifications();
}
}
public delegate void SqlNotificationEventHandler(object sender, SqlNotificationEventArgs e);
If I am using the same query without any parameters, the code is working perfectly. I can see the database changes instantly in frontend. The issue is coming after added a parameter in Where clause.
I got this idea from below link
https://www.codeproject.com/Tips/1075852/ASP-NET-MVC-SignalR-SqlDependency-and-EntityFramew
Sourcecode link
we.tl/njwwLl8g36
protected void Application_PostAuthenticateRequest()
{
HttpCookie authoCookies = Request.Cookies[FormsAuthentication.FormsCookieName];
if (authoCookies != null)
{
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authoCookies.Value);
JavaScriptSerializer js = new JavaScriptSerializer();
User1 user = js.Deserialize<User1>(ticket.UserData);
MyIdentity myIdentity = new MyIdentity(user);
MyPrincipal myPrincipal = new MyPrincipal(myIdentity);
HttpContext.Current.User = myPrincipal; //here
}
}
Error is in the very last line...
Here is MyPrincipal class.
public class MyPrincipal
{
private readonly MyIdentity MyIdentity;
public MyPrincipal(MyIdentity _myIdentity)
{
MyIdentity = _myIdentity;
}
public IIdentity Identity
{
get { return MyIdentity; }
}
public bool IsInRole(string role)
{
return Roles.IsUserInRole(role);
}
}
What to do? I am following this tutorial
http://www.dotnetawesome.com/2015/06/part4-how-to-implement-custom-forms-authentication-in-aspnet-mvc.html
Your class MyPrincipal misses to declare the implemented interface IPricipal:
public class MyPrincipal : IPrincipal
{ //...
There is no duck typing in C#.
public class TableTypeRepository : ITableTypeRepository
{
private TrenStarEAMEntities db = new TrenStarEAMEntities();
Core.Domain.TableType ITableTypeRepository.GetTableType(short id)
{
using (TrenStarEAMEntities dbContext = new TrenStarEAMEntities.Data.TrenStarEAMEntities())
{
var HttpStatusCoderesult = dbContext.GetTableType(null);
Core.Domain.TableType tableType = db.TableTypes.Find(id);
if (tableType == null)
{
return HttpNotFound();
}
return View(tableType);
}
}
private Core.Domain.TableType View(Core.Domain.TableType tableType)
{
throw new NotImplementedException();
}
private Core.Domain.TableType HttpNotFound()
{
throw new NotImplementedException();
}
Core.Domain.TableType ITableTypeRepository.GetTableType(short id)
{
throw new NotImplementedException();
}
}
This is where the error is GetTableType(short id) can anyone help?
Can someone show me how to use the parameter in Customize AuthorizeAttribute?
Like this:
[Authorize(Role="Admin,Supervisor")]
[Authorize(User="Me,You")]
[Authorize(Action="abc,def")]
This is my code now and I dont have any idea yet how to add the parameter here.
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
ApplicationDbContext _context = new ApplicationDbContext();
public override void OnAuthorization(HttpActionContext actionContext)
{
if (AuthorizeRequest(actionContext))
{
return;
}
HandleUnauthorizedRequest(actionContext);
}
protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
{
if (((System.Web.HttpContext.Current.User).Identity).IsAuthenticated)
{
actionContext.Response = new HttpResponseMessage()
{
StatusCode = HttpStatusCode.Unauthorized,
Content = new StringContent("You are unauthorized to access this resource")
};
}
else
{
base.HandleUnauthorizedRequest(actionContext);
}
}
private bool AuthorizeRequest(HttpActionContext actionContext)
{
var action = actionContext.ActionDescriptor.ActionName;
var controller = actionContext.ControllerContext.ControllerDescriptor.ControllerName;
var currentUser = actionContext.RequestContext.Principal.Identity.GetUserId();
var user = _context.Users.Join(_context.UserAccesses, x => x.RoleId, y => y.RoleId, (x, y) =>
new { Id = x.Id, firstName = x.firstName, lastName = x.lastName, RoleId = x.RoleId, Controller = y.Controller,
Action = y.Action }).Where(z => z.Id == currentUser && z.Controller == controller && z.Action == action)
.SingleOrDefault();
if (user != null)
return true;
else
return false;
}
}
As you have extended the default implementation of Authorize, you need to use [CustomAuthorize(Role="Admin,Supervisor")]. This will set the roles. You can then access the Roles property directly in your code as they are contained in the parent AuthorizeAttribute which has been inherited.
public override void OnAuthorization(HttpActionContext actionContext)
{
var roles = Roles;
if (AuthorizeRequest(actionContext))
{
return;
}
HandleUnauthorizedRequest(actionContext);
}
Below is my code, and the issue is that the dispose method of my UnitOfWork class does not get called. For DI, I am using Unity v2.1.505 with Unity.Mvc3 v1.2 in Asp.net MVC3 Application
[assembly: PreApplicationStartMethod(typeof(Program), "Initialize")]
namespace Practice.DependencyResolution.Concrete
{
public class Program
{
private static IUnityContainer container;
public static void Initialize()
{
if (container == null) container = new UnityContainer();
string databaseSource = Settings.Default.DatabaseSource;
var dependencyMapperType = Type.GetType("Practice.DependencyResolution.Concrete." + databaseSource + "DependencyMapper", true);
var dependencyMapper = (IDependencyMapper)Activator.CreateInstance(dependencyMapperType);
var dependencyMapperContext = new DependencyMapperContext(dependencyMapper);
dependencyMapperContext.MapDependencies(container);
ControllerBuilder.Current.SetControllerFactory(new UnityControllerFactory(container));
var locator = new UnityServiceLocator(container);
ServiceLocator.SetLocatorProvider(() => locator);
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
}
}
}
internal class DependencyMapperContext
{
private IDependencyMapper dependencyMapper;
public DependencyMapperContext(IDependencyMapper dependencyMapper)
{
this.dependencyMapper = dependencyMapper;
}
public void MapDependencies(IUnityContainer container)
{
dependencyMapper.MapDependencies(container);
}
}
internal class AnyDependencyMapper : IDependencyMapper
{
public void MapDependencies(IUnityContainer container)
{
container.RegisterType<ISupplierRepository, SupplierRepository>();
container.RegisterType<IUnitOfWork, UnitOfWork>(new HierarchicalLifetimeManager());
}
}
public class UnitOfWork : IUnitOfWork
{
private readonly TransactionScope transactionScope;
private readonly ModelDataContext context;
private bool disposed = false;
public UnitOfWork()
{
transactionScope = new TransactionScope();
this.context = new ModelDataContext();
}
ModelDataContext IUnitOfWork.Context
{
get
{
Debug.WriteLine("context get called");
return context;
}
}
public void Commit()
{
if (disposed) throw new ObjectDisposedException("transactionScope");
transactionScope.Complete();
}
protected virtual void Dispose(bool disposing)
{
if (disposed == false)
{
if (disposing)
{
if (context != null)
{
context.Dispose();
}
if (transactionScope != null)
{
transactionScope.Dispose();
}
disposed = true;
}
}
}
public void Dispose()
{
Debug.WriteLine("Access dispose called");
if (HttpContext.Current != null && HttpContext.Current.Error != null)
{
//transaction transactionScope will be disposed automatically, do nothing
}
else
{
Commit();
}
Dispose(true);
GC.SuppressFinalize(this);
}
}
public class SupplierRepository : ISupplierRepository
{
private readonly IUnitOfWork unitOfWork;
private bool disposed = false;
public SupplierRepository(IUnitOfWork unitOfWork)
{
this.unitOfWork = unitOfWork;
}
public IList<SupplierItem> GetAll()
{
return unitOfWork.Context.SupplierItems.ToList();
}
public SupplierItem GetById(object id)
{
return unitOfWork.Context.SupplierItems.SingleOrDefault(a => a.SupplierID == (int)id);
}
public void Insert(SupplierItem entity)
{
unitOfWork.Context.SupplierItems.InsertOnSubmit(entity);
unitOfWork.Context.SubmitChanges();
}
public void Delete(object id)
{
var supplier = unitOfWork.Context.SupplierItems.SingleOrDefault(a => a.SupplierID == (int)id);
unitOfWork.Context.SupplierItems.DeleteOnSubmit(supplier);
unitOfWork.Context.SubmitChanges();
}
public void Delete(SupplierItem entityToDelete)
{
Delete(entityToDelete.SupplierID);
}
public void Update(SupplierItem entityToUpdate)
{
var supplier = unitOfWork.Context.SupplierItems.SingleOrDefault(a => a.SupplierID == entityToUpdate.SupplierID);
supplier.Address = entityToUpdate.Address;
supplier.City = entityToUpdate.City;
supplier.CompanyName = entityToUpdate.CompanyName;
supplier.ContactName = entityToUpdate.ContactName;
supplier.ContactTitle = entityToUpdate.ContactTitle;
supplier.Country = entityToUpdate.Country;
supplier.Fax = entityToUpdate.Fax;
supplier.HomePage = entityToUpdate.HomePage;
supplier.Phone = entityToUpdate.Phone;
supplier.PostalCode = entityToUpdate.PostalCode;
supplier.Region = entityToUpdate.Region;
unitOfWork.Context.SubmitChanges();
}
public SupplierItem GetDefault()
{
return new SupplierItem();
}
}
I am new to DI and Unity, thanks in advance.
I do read that you are using MVC 3. Nevertheless, if there is a possibility for you to update to MVC 4, then the new Unity 3 has support for MVC out of the box, and works with the HierarchicalLifetimeManager.
I am not familiar with the Unity.Mvc3 NuGet package (which is not supported by Microsoft) though.