I Create Class named RoleController.cs :
[Dynaphore(Id=2)]
[Dynaphore(Name="Role Module")]
[Dynaphore(Description="Role will Control Capability of user")]
public class RoleController : BaseController
{
[Dynaphore(Id = 20)]
[Dynaphore(Name = "List of Role")]
[Dynaphore(Description = "Show all role in list")]
public ActionResult Index()
{
return View();
}
[Dynaphore(Id = 21)]
[Dynaphore(Name = "Role Editor")]
[Dynaphore(Description = "Edit Role")]
public ActionResult Editor(Guid? id)
{
var role = dbIntegrated.Roles.Where(p => p.Id == id).FirstOrDefault();
if (role == null)
{
var cons = AccessLogic.GetAllCapabilities();
List<VMRoleCapabilityItem> model = new List<VMRoleCapabilityItem>();
foreach (var c in cons)
{
foreach (var a in c.Actions)
{
VMRoleCapabilityItem domain = new VMRoleCapabilityItem();
domain.Controller = c.Controller.Replace("Controller", "");
domain.Action = Util.PrettySplitter(a);
domain.IsActive = false;
VMRoleCapabilityItem result = new VMRoleCapabilityItem();
result = domain;
model.Add(domain);
}
}
return View(model);
}
else
{
var cons = AccessLogic.GetAllCapabilities();
List<VMRoleCapabilityItem> model = new List<VMRoleCapabilityItem>();
foreach (var c in cons)
{
foreach (var a in c.Actions)
{
VMRoleCapabilityItem domain = new VMRoleCapabilityItem();
domain.Controller = c.Controller.Replace("Controller", "");
domain.Action = Util.PrettySplitter(a);
var rc = dbIntegrated.RoleCapabilities
.Where(p => p.Controller == c.Controller)
.Where(p => p.Action == a)
.FirstOrDefault();
if (rc != null) domain.IsActive = true;
else domain.IsActive = false;
model.Add(domain);
}
}
return View(model);
}
}
[Dynaphore(Id = 22)]
[Dynaphore(Name = "Save Role")]
[Dynaphore(Description = "Save a role")]
public ActionResult Save(VMCapabilityItem domain)
{
return RedirectToAction("Index");
}
[Dynaphore(Id = 298)]
[Dynaphore(Name = "Soft Delete Role")]
[Dynaphore(Description = "Delete Role from view")]
public ActionResult SoftDelete(Guid id)
{
return Json(new { is_success = true });
}
[Dynaphore(Id = 299)]
[Dynaphore(Name = "Hard Delete Role")]
[Dynaphore(Description = "Delete Role permanently")]
public ActionResult HardDelete(Guid id)
{
return Json(new { is_success = true });
}
}
and this is my custom attribute class :
/// <summary>
///
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public class DynaphoreAttribute : Attribute
{
/// <summary>
/// String field.
/// </summary>
int _id;
String _name;
String _desc;
/// <summary>
/// Attribute constructor.
/// </summary>
public DynaphoreAttribute()
{
}
/// <summary>
/// Get and set.
/// </summary>
public int Id
{
get { return this._id; }
set { this._id = value; }
}
public String Name
{
get { return this._name; }
set { this._name = value; }
}
public String Description {
get { return this._desc; }
set { this._desc = value; }
}
}
How to get Id, Name and Description of class and method by class name and method name?
i create two methods for it.
first to get class id :
public static int GetDynaphoreClassId(String className)
{
return 0;
}
second, get method id
public static int GetDynaphoreMethodId(String className, String methodName)
{
return 0;
}
how to solve this problem?
Related
Below is the portion of code from Propertyware API that is consumed.
public OwnerLedger appendOwnerLedgerItems(OwnerLedger ownerLedger, Owner owner) {
object[] results = this.Invoke("appendOwnerLedgerItems", new object[] {
ownerLedger,
owner});
return ((OwnerLedger)(results[0]));
}
public partial class OwnerLedger : Ledger {
}
public abstract partial class Ledger : ClientDataContainer {
private LedgerItem[] itemsField;
/// <remarks/>
[System.Xml.Serialization.SoapElementAttribute(IsNullable=true)]
public LedgerItem[] items {
get {
return this.itemsField;
}
set {
this.itemsField = value;
}
}
}
public abstract partial class LedgerItem : FinancialTransaction {
}
public abstract partial class OwnerLedgerItem : LedgerItem {
}
public partial class OwnerContribution : OwnerLedgerItem {
private string commentsField;
private System.Nullable<System.DateTime> dateField;
private string paymentTypeField;
private string referenceNumberField;
/// <remarks/>
[System.Xml.Serialization.SoapElementAttribute(IsNullable=true)]
public string comments {
get {
return this.commentsField;
}
set {
this.commentsField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.SoapElementAttribute(IsNullable=true)]
public System.Nullable<System.DateTime> date {
get {
return this.dateField;
}
set {
this.dateField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.SoapElementAttribute(IsNullable=true)]
public string paymentType {
get {
return this.paymentTypeField;
}
set {
this.paymentTypeField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.SoapElementAttribute(IsNullable=true)]
public string referenceNumber {
get {
return this.referenceNumberField;
}
set {
this.referenceNumberField = value;
}
}
}
In the above code i need to use the "appendOwnerLedgerItems" method to create an owner contribution entry in Propertyware. For that i try to use the below logic but it fails. The error message is "java.lang.ClassCastException: [Lcom.realpage.propertyware.web.service.soap.AbstractLedgerItemDTO; cannot be cast to [Lcom.realpage.propertyware.web.service.soap.AbstractOwnerLedgerItemDTO;"
OwnerContribution oc = new OwnerContribution();
oc.amount = 10;
oc.comments = "Test Entry";
oc.date = System.DateTime.Now;
oc.paymentType = "Check";
oc.referenceNumber = "12345";
Owner ow = new Owner();
ow.ID = 12345;
LedgerItem[] li = new LedgerItem[1];
li[0] = oc;
OwnerLedger owl = new OwnerLedger();
owl.items = li;
OwnerLedger owl1 = client.appendOwnerLedgerItems(owl,ow); // This is where i get the cast error
How to solve this issue?
I don't know much about Propertyware but can you try this, basically change the order of objects passed to the invoke method:
public OwnerLedger appendOwnerLedgerItems(OwnerLedger ownerLedger, Owner owner) {
object[] results = this.Invoke("appendOwnerLedgerItems", new object[] {
owner, ownerLedger});
return ((OwnerLedger)(results[0]));
}
I can not update my database using EF (UpdateSpecified() method is not working). My Add() method works fine.
Edit: I observed the SaveChanges Method it always return 1 ,it let me confused because I updated 3 tables.
I discovered the RepositoryFactory's IQueryable code, it had changed:
My code:
public class GoodsModel
{
private IRepositoryFactory _repositoryFactory;
private IServiceFactory _serviceFactory;
private IGoodsService _goodsService;
private IGoodsTypeService _goodsTypeService;
private IUsersService _userService;
private IOrderService _orderService;
private IOrdersRepository orderRepo;
private IUsersRepository userRepo;
private IGoodsRepository goodsRepo;
public GoodsModel()
{
_repositoryFactory = new RepositoryFactory();
_repositoryFactory.OpenSession();
_serviceFactory = new ServiceFactory(_repositoryFactory);
_goodsService = _serviceFactory.CreateGoodsService();
_goodsTypeService = _serviceFactory.CreateGoodsTypeService();
_userService = _serviceFactory.CreateUsersService();
_orderService = _serviceFactory.CreateOrderService();
userRepo = _repositoryFactory.CreateUsersRepository();
orderRepo = _repositoryFactory.CreateOrdersRepository();
goodsRepo = _repositoryFactory.CreateGoodsRepository();
orderRepo = _repositoryFactory.CreateOrdersRepository();
}
public bool BuyProduct(BuyProductDto model)
{
string name = HttpContext.Current.User.Identity.Name;
// _repositoryFactory.OpenSession();
using (_repositoryFactory)
{
var user = _userService.Filter(x => x.UserName == name).FirstOrDefault();
var good = _goodsService.Filter(x => x.GoodNumber == model.GoodNumber).FirstOrDefault();
//var userRepo = _repositoryFactory.CreateUsersRepository();
//var goodRepo = _repositoryFactory.CreateGoodsRepository();
Users u = new Users();
Goods g = new Goods();
try
{
//substract when buy product.
int remainScore = user.UserScore - (int)good.GoodScore;
if (remainScore < 0)
{
return false;
}
u.UserId = user.UserId;
u.UserScore = remainScore;
userRepo.Attach(u);
userRepo.UpdateSpecified(u);
g.Id = good.Id;
//same as above syntax
g.GoodsQuantity = good.GoodsQuantity - 1;
goodsRepo.Attach(g);
goodsRepo.UpdateSpecified(g);
//orderRepo = _repositoryFactory.CreateOrdersRepository();
orderRepo.Add(new Orders
{
GoodId = good.Id,
InsertTime = DateTime.Now,
Status = 0,
UserId = user.UserId,
OrderNo = DateTime.Now.ToString("yyyyMMddss"),
UpdateTime = DateTime.Now
});
_repositoryFactory.Commit();
}
catch (Exception ex)
{
_repositoryFactory.RollBack();
return false;
}
}
return true;
}
}
The code of framework is here:
public void UpdateSpecified(T entity)
{
var type = entity.GetType();
if (type.IsPrimitive || type == typeof(string))
{
var props = type.GetProperties();
foreach (var prop in props)
{
string propValue = prop.GetValue(entity, null) != null ? prop.GetValue(entity, null).ToString() : string.Empty;
if (!string.IsNullOrEmpty(propValue))
{
DataContext.Entry<T>(entity).Property(prop.Name).IsModified = true;
}
else
{
DataContext.Entry<T>(entity).Property(prop.Name).IsModified = false;
}
}
}
}
public void Attach(T entity)
{
DataContext.Set<T>().Attach(entity);
}
}
The entity code like this, it contains the navigation attribute:
public class Users
{
public int UserId { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public DateTime InsertTime { get; set; }
public ICollection<UsersUserGroup> UsersUserGroups { get; set; }
public int UserScore { get; set; }
}
oaky.... I have solved it ,it is fool question ,I admit; Correct Code:
public void UpdateSpecified(T entity)
{
var props = entity.GetType().GetProperties();
foreach (var prop in props)
{
if (prop.PropertyType.IsPrimitive || prop.PropertyType == typeof(string))
{
string propValue = prop.GetValue(entity, null) != null ? prop.GetValue(entity, null).ToString() : string.Empty;
if (!string.IsNullOrEmpty(propValue))
{
DataContext.Entry<T>(entity).Property(prop.Name).IsModified = true;
}
else
{
DataContext.Entry<T>(entity).Property(prop.Name).IsModified = false;
}
}
}
}
I am using System.DirectoryServices.AccountManagement to manage my login user account.
I am able to get information for login user, but not able to get direct reports user id based on manager.
var context = new PrincipalContext(ContextType.Domain);
var principal = UserPrincipal.FindByIdentity(context, User.Identity.Name);
I have refer to this link: C# - Look up a users manager in active directory
But still didn't get any clue. Anyone can help me on this?
I managed to figure out the directory property for direct reports("directReports").
Just to add a new directory property as below:
// Create the "Direct Report" property.
[DirectoryProperty("directReports")]
public List<string> DirectReports
{
get
{
var directReportsName = new List<string>();
if (ExtensionGet("directReports").Length == 0)
return directReportsName;
for (int i = 0; i < ExtensionGet("directReports").Length; i++)
{
string userString = (string)ExtensionGet("directReports")[i];
//example of userString = CN=name,OU=Users,OU=department,OU=AP,OU=Software,DC=company,DC=priv,DC=company,DC=com
//split by comma
var tempCN = userString.Split(',').First();
var tempName = tempCN.Split('=');
var userName= tempName[1];
directReportsAlias.Add(userName);
}
return directReportsName;
}
}
I have designed class for active directory search.
This class support.
Search Employee By Same Account Name
Search Employee By Employee Id
Search Employee By Employee Code
Search Employee By Employee Email
Search Employee Manage
Search Team Member
CLASS CODE
using System;
using System.Collections.Generic;
using System.Text;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
namespace UAT.COMMON
{
#region RefranceHelpers
/*
//https://www.c-sharpcorner.com/article/active-directory-and-net/
//https://ianatkinson.net/computing/adcsharp.htm
//https://ianatkinson.net/computing/adcsharp.htm
*/
#endregion
public enum SearchBy
{
StartNTID=0,
}
public class ManageDirectoryServices : IDisposable
{
public ContextType contextType = ContextType.Domain;
public PrincipalContext Context { get; protected set; }
public UserPrincipal User { get; protected set; }
public UserPrincipal Manager { get; protected set; }
public bool IsManager { get; protected set; }
public List<UserPrincipal> DirectReports { get; protected set; }
public class AuthenticationResult
{
public AuthenticationResult()
{
IdentityError = new List<IdentityError>();
IsSuccess = IdentityError.Count > 0;
}
public List<IdentityError> IdentityError { get; private set; }
public String RoleName { get; private set; }
public Boolean IsSuccess { get; set; }
public ManageDirectoryServices Context { get; set; }
}
public ManageDirectoryServices()
{
Context = new PrincipalContext(contextType);
DirectReports = new List<UserPrincipal>();
}
public ManageDirectoryServices(string ntid)
{
Context = new PrincipalContext(contextType);
DirectReports = new List<UserPrincipal>();
GetEmployeeByNTID(NormalizeNTID(ntid));
}
/// <summary>
///
/// </summary>
/// <param name="ntid">This is SamAccountName</param>
/// <returns></returns>
public ManageDirectoryServices GetEmployeeByNTID(string ntid)
{
if (string.IsNullOrWhiteSpace(ntid)) return null;
UserPrincipal searchTemplate = new UserPrincipal(Context)
{
SamAccountName = ntid
};
PrincipalSearcher ps = new PrincipalSearcher(searchTemplate);
User = (UserPrincipal)ps.FindOne();
return this;
}
public ManageDirectoryServices GetEmployee(string strSearch,string prop)
{
if (string.IsNullOrWhiteSpace(strSearch)) return this;
if (string.IsNullOrWhiteSpace(prop)) return this;
DirectorySearcher search = new DirectorySearcher();
search.Filter = String.Format("(cn={0})", strSearch);
search.PropertiesToLoad.Add(prop);
var result = search.FindAll();
if (result != null)
{
int directReports = result.Count; //result.Properties["displayname"].Count;
if (directReports < 0) return null;
for (int counter = 0; counter < directReports; counter++)
{
var user = (string)result[counter].Properties["givenname"][counter];
var reporte = UserPrincipal.FindByIdentity(Context, IdentityType.DistinguishedName, user);
this.DirectReports.Add(reporte);
IsManager = true;
}
return this;
}
return null;
}
public ManageDirectoryServices GetEmployee(UserPrincipal searchTemplate)
{
if (searchTemplate == null) return null;
PrincipalSearcher ps = new PrincipalSearcher(searchTemplate);
User = (UserPrincipal)ps.FindOne();
return this;
}
/// <summary>
///
/// </summary>
/// <param name="NTID">This is SamAccountName</param>
/// <returns></returns>
public bool IsUserExist(string NTID)
{
var data = GetEmployeeByNTID(NormalizeNTID(NTID));
return !string.IsNullOrWhiteSpace(data?.User?.SamAccountName);
}
public bool IsUserExist()
{
var data = User;
return !string.IsNullOrWhiteSpace(data?.SamAccountName);
}
public ManageDirectoryServices GetEmployeeByEmail(string email)
{
if (string.IsNullOrWhiteSpace(email)) return null;
UserPrincipal searchTemplate = new UserPrincipal(Context)
{
EmailAddress = email
};
PrincipalSearcher ps = new PrincipalSearcher(searchTemplate);
User = (UserPrincipal)ps.FindOne();
return this;
}
public ManageDirectoryServices GetEmployeeByEmpId(string employeeId)
{
if (string.IsNullOrWhiteSpace(employeeId)) return null;
UserPrincipal searchTemplate = new UserPrincipal(Context)
{
EmployeeId = employeeId
};
PrincipalSearcher ps = new PrincipalSearcher(searchTemplate);
User = (UserPrincipal)ps.FindOne();
return this;
}
public ManageDirectoryServices GetManager()
{
if (this.User == null) return null;
DirectoryEntry ManagerDE = this.User.GetUnderlyingObject() as DirectoryEntry;
var manager = ManagerDE.Properties["manager"].Value.ToString();
UserPrincipal oManager = UserPrincipal.FindByIdentity(Context, IdentityType.DistinguishedName, manager);
this.Manager = oManager;
return this;
}
public ManageDirectoryServices GetDirectReports()
{
if (this.User == null) return this;
DirectorySearcher search = new DirectorySearcher();
search.Filter = String.Format("(cn={0})", this.User.SamAccountName);
search.PropertiesToLoad.Add("directReports");
SearchResult result = search.FindOne();
if (result != null)
{
int directReports = result.Properties["directReports"].Count;
if (directReports < 0) return null;
for (int counter = 0; counter < directReports; counter++)
{
var user = (string)result.Properties["directReports"][counter];
var reporte = UserPrincipal.FindByIdentity(Context, IdentityType.DistinguishedName, user);
this.DirectReports.Add(reporte);
IsManager = true;
}
return this;
}
return null;
}
public string NormalizeNTID(string Id)
{
if (string.IsNullOrWhiteSpace(Id)) return "";
return Id.Trim().ToUpper().Replace(#"\", "")
.Replace("\\", "")
.Replace("/", "")
.Replace("//", "")
.Replace("MS", "")
.Replace("MS//", "")
.Replace("MS\\", "");
}
public AuthenticationResult SignIn(string ntid, string password)
{
var NormalizeNTID = this.NormalizeNTID(ntid);
bool IsAuthenticated = false;
IdentityError identityError = new IdentityError();
ManageDirectoryServices context = null;
AuthenticationResult authenticationResult = new AuthenticationResult();
var IsSuccess = Context.ValidateCredentials(NormalizeNTID, password, ContextOptions.Negotiate);
context = GetEmployeeByNTID(NormalizeNTID);
if (IsSuccess)
{
if (context.User != null)
{
IsAuthenticated = true;
this.User = context.User;
authenticationResult.Context = context;
authenticationResult.IsSuccess = true;
}
}
else
{
if (!IsAuthenticated || User == null)
{
authenticationResult.IdentityError.Add(new IdentityError
{
Code = "InCorrectUserAndPassword",
Description = "Username or Password is not correct"
});
}
if (context.User.IsAccountLockedOut())
{
authenticationResult.IdentityError.Add(new IdentityError
{
Code = "YourAccountIsLocked",
Description = "Your account is locked."
});
}
if (context.User.Enabled.HasValue && User.Enabled.Value == false)
{
authenticationResult.IdentityError.Add(identityError = new IdentityError
{
Code = "YourAccountIsDisabled",
Description = "Your account is disabled"
});
}
else
{
authenticationResult.IdentityError.Add(new IdentityError
{
Code = "InvalidLogin",
Description = "In valid login!! Please try again"
});
}
}
return authenticationResult;
}
#region ************Async Envelope**************
public async Task<ManageDirectoryServices> GetEmployeeByNTIDAsync(string ntid)
{
return await Task.Run(() => GetEmployeeByNTID(ntid));
}
public async Task<ManageDirectoryServices> GetEmployeeByEmailAsync(string email)
{
return await Task.Run(() => GetEmployeeByEmail(email));
}
public async Task<ManageDirectoryServices> GetEmployeeByEmpIdAsync(string employeeId)
{
return await Task.Run(() => GetEmployeeByEmpId(employeeId));
}
public async Task<ManageDirectoryServices> GetManagerAsync()
{
return await Task.Run(() => GetManager());
}
public async Task<ManageDirectoryServices> GetDirectReportsAsync()
{
return await Task.Run(() => GetDirectReports());
}
public async Task<AuthenticationResult> SignInAsync(string ntid, string password)
{
return await Task.Run(() => SignIn(ntid, password));
}
#endregion
public void Dispose()
{
this.Dispose();
GC.Collect();
}
}
}
How To Use
[TestMethod]
public void ContractorInitialsSuccess()
{
ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices(MSID);
var context = manageDirectoryServices.User;
Assert.AreEqual(MSID, context.SamAccountName);
}
[TestMethod]
public void SignInSuccess()
{
ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices();
var context = manageDirectoryServices.SignIn(MSID,MSPASSWORD);
Assert.AreEqual(EMAIL, context.Context.User.EmailAddress);
}
[TestMethod]
public void GetEmployeeByNTIDSuccess()
{
ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices();
var context = manageDirectoryServices.GetEmployeeByNTID(MSID);
Assert.AreEqual(MSID, context.User.SamAccountName);
}
[TestMethod]
public void GetManagerSuccess()
{
ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices();
var context = manageDirectoryServices.GetEmployeeByNTID(MSID);
var manager = context.GetManager();
Assert.AreEqual(MANAGER_NTID, context.Manager.SamAccountName);
}
[TestMethod]
public void GetReportesSuccess()
{
ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices();
var context = manageDirectoryServices.GetEmployeeByNTID(MSID);
var repcontext = context.GetDirectReports();
var flag = repcontext.DirectReports.Count > 0 ? true : false;
Assert.AreEqual(true, flag);
}
[TestMethod]
public void GetEmployeeByEmailSuccess()
{
ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices();
var context = manageDirectoryServices.GetEmployeeByEmail(EMAIL);
Assert.AreEqual(EMAIL, context.User.EmailAddress);
}
[TestMethod]
public void GetEmployeeByEmployeeIdSuccess()
{
ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices();
var context = manageDirectoryServices.GetEmployeeByEmpId(EMPLOYEEID);
Assert.AreEqual(EMPLOYEEID, context.User.EmployeeId);
}
[TestMethod]
public void IsUserExistSuccess()
{
ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices();
var IsExist = manageDirectoryServices.IsUserExist(MSID);
Assert.AreEqual(true, IsExist);
}
[TestMethod]
public void IsUserExistFail()
{
ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices();
var IsExist = manageDirectoryServices.IsUserExist("invalidid");
Assert.AreEqual(false, IsExist);
}
[TestMethod]
public void GetEmployeeSuccess()
{
ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices();
var searchTemplate = new System.DirectoryServices.AccountManagement.UserPrincipal(manageDirectoryServices.Context) {
SamAccountName= MSID,
EmailAddress=EMAIL,
EmployeeId=EMPLOYEEID
};
var context = manageDirectoryServices.GetEmployee(searchTemplate);
Assert.AreEqual(MSID, context.User.SamAccountName);
}
[TestMethod]
public void GetEmployeeNameSuccess0()
{
ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices();
var repcontext = manageDirectoryServices.GetEmployee("abhishek", "givenname");
var flag = repcontext.DirectReports.Count > 0 ? true : false;
Assert.AreEqual(true, flag);
}
[TestMethod]
public void GetEmployeeNameSuccess1()
{
ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices();
var repcontext = manageDirectoryServices.GetEmployee("abhishek", "name");
var flag = repcontext.DirectReports.Count > 0 ? true : false;
Assert.AreEqual(true, flag);
}
[TestMethod]
public void GetEmployeeNameSuccess2()
{
ManageDirectoryServices manageDirectoryServices = new ManageDirectoryServices();
var repcontext = manageDirectoryServices.GetEmployee("abhishek", "displayname");
var flag = repcontext.DirectReports.Count > 0 ? true : false;
Assert.AreEqual(true, flag);
}
I have an issue with serialization. I understand that methods can not be serialized for good reason, so I created a factory class to convert my existing class into a more manageable class.
This is the original class:
using Assets.Components;
using Assets.Data;
using IO.Components;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace Assets
{
[Serializable]
public class Asset
{
#region Fields
Metadata _metadata;
string _fileName;
string _companyId;
#endregion
#region Properties
[Required]
public string DisplayName { get; set; }
public string Description { get; set; }
public string Tags { get; set; }
public int Id { get; set; }
public int CategoryId { get; set; }
public AssetType Type { get; set; }
public int LanguageId { get; set; }
public int StatusId { get; set; }
public DateTime DateCreated { get; set; }
public long DateCreatedMilliseconds { get { return DateCreated.ToJavaScriptMilliseconds(); } }
public int Views { get; set; }
public int Downloads { get; set; }
public string ThumbNail { get; set; }
public string Filename
{
set { _fileName = value; }
}
[Required]
public string CompanyId
{
set { _companyId = value; }
}
public string GetBaseDirectory
{
get { return "/Public/Uploads/" + this._companyId + "/0"; }
}
public double Rating
{
get
{
List<int> Score = new List<int>();
foreach (IRating oRating in this.Ratings())
{
Score.Add(oRating.Score);
}
return (Score.Count > 0) ? Score.Average() : 0;
}
}
public Metadata Metadata
{
get
{
if (_metadata == null)
{
_metadata = new Metadata(this.Id);
if (_metadata.AssetId == 0)
{
try
{
if (GetFilename() != null)
{
string path = System.IO.Path.Combine(HttpContext.Current.Server.MapPath(this.GetBaseDirectory), GetFilename());
if (!System.IO.File.Exists(path))
_metadata = new Metadata();
else
{
_metadata = MetadataExtractor.Create(path, this.Id);
_metadata.save();
}
}
else
{
_metadata = new Metadata();
}
}
catch
{
_metadata = new Metadata();
}
}
}
return _metadata;
}
}
public bool IsConverted { get; set; }
public string UserId { get; set; }
public DateTime DateModified { get; set; }
public long DateModifiedMilliseconds { get { return DateCreated.ToJavaScriptMilliseconds(); } }
public string Culture { get; set; }
public string Language { get; set; }
public string UserName { get; set; }
public string Email { get; set; }
public int CategoryCount { get; set; }
public int AssetCount { get; set; }
public bool IgnoreRights { get; set; }
#endregion
#region Contructors
/// <summary>
/// Default constructor
/// </summary>
public Asset()
{
}
/// <summary>
/// Get's the asset from the database, but set's the status to the profiles Requires Approval state.
/// </summary>
/// <param name="Id">Asset Id</param>
/// <param name="IsViewing">Boolean to update the reports table</param>
/// <param name="IsDownloading">Boolean to update the reports table</param>
public Asset(int Id, string UserId, string CompanyId, bool IsViewing, bool IsDownloading)
{
try
{
Asset oAsset = AssetData.GetAsset(Id, IsViewing, IsDownloading, UserId, CompanyId);
// Assign the values to this class
this.Id = oAsset.Id;
this.DisplayName = oAsset.DisplayName;
this.IsConverted = oAsset.IsConverted;
this.StatusId = oAsset.StatusId;
this.Type = oAsset.Type;
this.UserId = oAsset.UserId;
this.UserName = oAsset.UserName;
this.CompanyId = oAsset.GetCompanyId();
this.Description = oAsset.Description;
this.Tags = oAsset.Tags;
this.LanguageId = oAsset.LanguageId;
this.Culture = oAsset.Culture;
this.Language = oAsset.Language;
if (oAsset.ThumbNail != null) this.ThumbNail = oAsset.ThumbNail;
this.Filename = oAsset.GetFilename();
if (oAsset.Views != 0) this.Views = oAsset.Views;
if (oAsset.Downloads != 0) this.Downloads = oAsset.Downloads;
}
catch (Exception ex)
{
Stars.BLL.Error.Handling.LogError("Skipstone", "Asset", "Asset", ex.Message, ex.ToString()); // Record our error
}
}
/// <summary>
/// Used for executing some of the public methods
/// </summary>
/// <param name="Id">Id of the asset to retrieve</param>
/// <param name="CompanyId">The CompanyId of the company for the User</param>
public Asset(int Id, string CompanyId)
{
this.Id = Id;
this.CompanyId = CompanyId;
}
#endregion
#region Public methods
public string GetCompanyId()
{
return _companyId;
}
public string GetFilename()
{
return _fileName;
}
public string GetThumbnail()
{
return this.GetBaseDirectory + "/" + this.ThumbNail;
}
public string GetSmallThumbnail()
{
return this.GetBaseDirectory + "/sml_" + this.ThumbNail;
}
public Collection<IRating> Ratings()
{
Collection<IRating> oRatings = new Collection<IRating>();
try
{
oRatings = RatingData.get(this.Id);
}
catch
{
// record our error
}
return oRatings;
}
public Collection<IComment> Comments()
{
Collection<IComment> oComments = new Collection<IComment>();
try
{
oComments = CommentData.getAssetComments(this.Id);
}
catch (Exception ex)
{
// record our error
}
return oComments;
}
public void SaveMetadata()
{
}
public Collection<GenericType> Categories()
{
return MiscellaneousManager.AssetCategories(this.Id, GetCompanyId());
}
public void Save()
{
if (this.Id > 0)
{
AssetData.update(this);
}
else
{
Asset oAsset = AssetData.create(this);
this.Id = oAsset.Id;
this.DisplayName = oAsset.DisplayName;
this.Type = oAsset.Type;
this.UserId = oAsset.UserId;
this.CompanyId = oAsset.GetCompanyId();
this.Description = oAsset.Description;
this.Tags = oAsset.Tags;
this.LanguageId = oAsset.LanguageId;
this.Culture = oAsset.Culture;
this.Language = oAsset.Language;
if (oAsset.ThumbNail != null) this.ThumbNail = oAsset.ThumbNail;
this.Filename = oAsset.GetFilename();
if (oAsset.Views != 0) this.Views = oAsset.Views;
if (oAsset.Downloads != 0) this.Downloads = oAsset.Downloads;
}
}
public void delete()
{
AssetData.delete(this.Id);
AssetManager.RemoveFromCache(this);
}
#endregion
}
}
and this is my factory method:
private static SerialisedAsset AssetFactory(Assets.Asset Object)
{
SerialisedAsset FactoryObject = new SerialisedAsset()
{
Id = Object.Id,
Name = Object.DisplayName,
UserId = Object.UserId,
UserName = Object.UserName,
CompanyId = Object.GetCompanyId(),
Description = Object.Description,
Tags = Object.Tags,
DateCreated = Object.DateCreated,
Path = Object.GetBaseDirectory,
FileName = Object.GetFilename(),
ThumbnailName = Object.ThumbNail
};
return FactoryObject;
}
which is part of my audittrailmanager class:
using Assets;
using Core;
using Reports.Objects;
using System;
using System.IO;
using System.Xml.Serialization;
namespace Reports.Components
{
public static class AuditTrailManager
{
#region Public methods
public static Audit AuditTrailFactory(Profile Profile, Object Object, Event Event)
{
Audit Audit = new Audit(SerializeObject(Object))
{
UserId = Profile.UserId,
UserName = Profile.UserName,
CompanyId = Profile.CompanyId,
ObjectName = GetObjectNameFromType(Object.GetType().ToString()),
Event = Event
};
return Audit;
}
#endregion
#region Private methods
private static string GetObjectNameFromType(string Type)
{
switch (Type)
{
case "Assets.Asset": return "Asset";
case "Core.SiteSetting": return "CompanySettings";
}
return "";
}
private static string SerializeObject(Object Object)
{
string ObjectType = Object.GetType().ToString();
switch (ObjectType)
{
case "Assets.Asset": return Serialize(AssetFactory((Asset)Object));
}
return ""; // If we fail
}
private static string Serialize(Object Object)
{
XmlSerializer ser = new XmlSerializer(Object.GetType());
using (StringWriter Xml = new StringWriter())
{
ser.Serialize(Xml, Object);
return (Xml.ToString());
}
}
private static SerialisedAsset AssetFactory(Assets.Asset Object)
{
SerialisedAsset FactoryObject = new SerialisedAsset()
{
Id = Object.Id,
Name = Object.DisplayName,
UserId = Object.UserId,
UserName = Object.UserName,
CompanyId = Object.GetCompanyId(),
Description = Object.Description,
Tags = Object.Tags,
DateCreated = Object.DateCreated,
Path = Object.GetBaseDirectory,
FileName = Object.GetFilename(),
ThumbnailName = Object.ThumbNail
};
return FactoryObject;
}
#endregion
}
}
What I am trying to do is create an audit trail which records the object I am working on (in this case an asset) and I am serializing the class and inserting it into the database for use in reporting, etc.
My question is; is this the way to do it. Is there a better way?
When writing a unit test for an action that uses User.Identity, shows an error Unable to cast object of type 'Castle.Proxies.IIdentityProxy' to type 'MyApp.Web.Models.CurrentUser'.
Current user class :
[Serializable]
public class CurrentUser : IIdentity
{
public CurrentUser (){}
public CurrentUser (string name, string displayName, int userId)
{
this.Name = name;
this.DisplayName = displayName;
this.UserId = userId;
}
public CurrentUser (string name, string displayName, int userId,string roleName)
{
this.Name = name;
this.DisplayName = displayName;
this.UserId = userId;
this.RoleName = roleName;
}
public CurrentUser (string name, UserInfo userInfo)
: this(name, userInfo.DisplayName, userInfo.UserId,userInfo.RoleName)
{
if (userInfo == null) throw new ArgumentNullException("userInfo");
this.UserId = userInfo.UserId;
}
public CurrentUser (FormsAuthenticationTicket ticket)
: this(ticket.Name, UserInfo.FromString(ticket.UserData))
{
if (ticket == null) throw new ArgumentNullException("ticket");
}
public string Name { get; private set; }
public string AuthenticationType
{
get { return "GoalSetterForms"; }
}
public bool IsAuthenticated
{
get { return true; }
}
public string DisplayName { get; private set; }
public string RoleName { get; private set; }
public int UserId { get; private set; }
}
Controller Action
public PartialViewResult SomeList()
{
int userid = ((CurrentUser )(User.Identity)).UserId; //Error shows here
var list= listService.GetLists(userid);
return PartialView("ListView", list);
}
Unit Test
[Test]
public void SomeList_Test()
{
var controllerContext = new Mock<ControllerContext>();
var principal = new Moq.Mock<IPrincipal>();
ListController controller = new ListController (listService);
principal.SetupGet(x => x.Identity.Name).Returns("abc");
controllerContext.SetupGet(x => x.HttpContext.User).Returns(principal.Object);
controllerContext.SetupGet(p => p.HttpContext.Request.IsAuthenticated).Returns(true);
controller.ControllerContext = controllerContext.Object;
}
Thanks in advance,
Razack
I just ran into this same thing but a little different.
replace
principal.SetupGet(x => x.Identity.Name).Returns("abc");
with
principal.SetupGet(x => x.Identity).Returns(new CurrentUser("abc", "test", 123));