I moved to web application from web site to improve it, I have profile in my web site.
My profile didn't work, so I implement System.Web.ProfileProvider and create a class ProfileCommon inherit ProfileBase I use HttpContext.Current.Profile.SetPropertyValue and GetPropertyValue. it works but the problem is it has a logically bug because HttpContext.Current.Profile doesn't call my ProfileProvider method How I can repair this ? or maybe is there any other implementation for profile in web application ?
public class ProfileCommon : ProfileBase
{
public string FirstName
{
get
{
return HttpContext.Current.Profile.GetPropertyValue("FirstName").ToString();
}
set
{
HttpContext.Current.Profile.SetPropertyValue("FirstName", value);
}
}
}
in the web.config
<profile inherits="BaniBookWebApp.Code.Core.ProfileCommon">
<providers>
<add name="CustomProfileProvider" type="BaniBookWebApp.Code.Core.CustomProfileProvider"/>
</providers>
</profile>
CustomProfileProvider :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using eLearn2Model;
using System.Collections;
using System.Configuration;
namespace AccessControl
{
public class ProfileProvider : System.Web.Profile.ProfileProvider
{
public ProfileProvider()
{
}
public override int DeleteInactiveProfiles(System.Web.Profile.ProfileAuthenticationOption authenticationOption, DateTime userInactiveSinceDate)
{
int res = -1;
using (var db = new eLearn2Entities())
{
List<Profile> profiles = (from m in db.Profiles
where (m.LastUpdatedDate.CompareTo(userInactiveSinceDate) < 0)
select m).ToList();
foreach (Profile profile in profiles)
{
if (profile != null)
{
db.Profiles.DeleteObject(profile);
res = db.SaveChanges();
}
}
}
return res;
}
public override int DeleteProfiles(string[] usernames)
{
int res = -1;
using (var db = new eLearn2Entities())
{
foreach (string username in usernames)
{
Profile profile = (from m in db.Profiles
join n in db.Users on m.UserId equals n.UserId
where n.UserName == username
select m).SingleOrDefault();
if (profile != null)
{
db.Profiles.DeleteObject(profile);
res = db.SaveChanges();
}
}
}
return res;
}
public override int DeleteProfiles(System.Web.Profile.ProfileInfoCollection profiles)
{
throw new NotImplementedException();
}
public override System.Configuration.SettingsPropertyValueCollection GetPropertyValues(System.Configuration.SettingsContext context, System.Configuration.SettingsPropertyCollection collection)
{
System.Configuration.SettingsPropertyValueCollection spvc = new System.Configuration.SettingsPropertyValueCollection();
lock (collection.SyncRoot)
{
foreach (object item in collection)
{
SettingsProperty sp = (SettingsProperty)item;
SettingsPropertyValue spv = new SettingsPropertyValue(sp);
spvc.Add(spv);
}
}
return spvc;
}
public override void SetPropertyValues(System.Configuration.SettingsContext context, System.Configuration.SettingsPropertyValueCollection collection)
{
string PropertyNames_ = string.Empty;
string PropertyValuesString_ = string.Empty;
string userID = string.Empty;
lock (collection.SyncRoot)
{
foreach (object item in collection)
{
SettingsPropertyValue spv = (SettingsPropertyValue)item;
if (spv.PropertyValue != null)
{
if (!string.IsNullOrEmpty(spv.PropertyValue.ToString()))
{
if (spv.Name.Equals("UserID"))
{
userID = spv.PropertyValue.ToString();
}
else
{
PropertyNames_ += spv.Name + ";";
PropertyValuesString_ += spv.PropertyValue.ToString() + ";";
}
}
}
}//foreach
}//lock
try
{
using (var db = new eLearn2Entities())
{
bool isAuthenticated = bool.Parse(context["IsAuthenticated"].ToString());
Profile profile = new Profile()
{
UserId = Guid.Parse(userID),
PropertyValuesString = PropertyValuesString_,
PropertyNames = PropertyNames_,
LastUpdatedDate = DateTime.UtcNow
};
db.Profiles.AddObject(profile);
db.SaveChanges();
}
}
catch
{
using (var db = new eLearn2Entities())
{
//bookmark gives me an error said multiple record
Guid myID = Guid.Parse(userID);
Profile existed_profile = db.Profiles.Where
(item => item.UserId == myID).SingleOrDefault() as Profile;
existed_profile.PropertyValuesString = PropertyValuesString_;
existed_profile.PropertyNames = PropertyNames_;
existed_profile.LastUpdatedDate = DateTime.UtcNow;
db.Profiles.ApplyOriginalValues(existed_profile);
db.SaveChanges();
}
}
}
}
}
have you tried adding enabled="true" on the web.config?
<profile inherits="BaniBookWebApp.Code.Core.ProfileCommon" enabled="true">
Related
I'm working on the upgrade of an application from net framework to .net core 3.0. I am using windows presentation foundation Wpf and I want to implement ValueInjecter in its last version 3.2... The application is currently running on version 2.4 of ValueInjecter help please!. There is not much documentation on the web.
How would this code look?
My CloneInjection.cs:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Omu.ValueInjecter;
namespace Infrastructure.Data.Injection
{
public class CloneInjection : ConventionInjection
{
protected override bool Match(ConventionInfo c)
{
return c.SourceProp.Name == c.TargetProp.Name && c.SourceProp.Value != null;
}
protected override object SetValue(ConventionInfo c)
{
//for value types and string just return the value as is
if (c.SourceProp.Type.IsValueType || c.SourceProp.Type == typeof(string))
return c.SourceProp.Value;
//handle arrays
if (c.SourceProp.Type.IsArray)
{
var arr = c.SourceProp.Value as Array;
var clone = arr.Clone() as Array;
for (int index = 0; index < arr.Length; index++)
{
var a = arr.GetValue(index);
if (a.GetType().IsValueType || a is string) continue;
clone.SetValue(Activator.CreateInstance(a.GetType()).InjectFrom<CloneInjection>(a), index);
}
return clone;
}
if (c.SourceProp.Type.IsGenericType)
{
//handle IEnumerable<> also ICollection<> IList<> List<>
if (c.SourceProp.Type.GetGenericTypeDefinition().GetInterfaces().Contains(typeof(IEnumerable)))
{
var t = c.SourceProp.Type.GetGenericArguments()[0];
if (t.IsValueType || t == typeof(string)) return c.SourceProp.Value;
var tlist = typeof(List<>).MakeGenericType(t);
var list = Activator.CreateInstance(tlist);
var addMethod = tlist.GetMethod("Add");
foreach (var o in c.SourceProp.Value as IEnumerable)
{
var e = Activator.CreateInstance(t).InjectFrom<CloneInjection>(o);
addMethod.Invoke(list, new[] { e }); // in 4.0 you can use dynamic and just do list.Add(e);
}
return list;
}
//unhandled generic type, you could also return null or throw
return c.SourceProp.Value;
}
//for simple object types create a new instace and apply the clone injection on it
return Activator.CreateInstance(c.SourceProp.Type)
.InjectFrom<CloneInjection>(c.SourceProp.Value);
}
}
}
My EntityInjection.cs:
using System.Collections;
using System.Diagnostics;
using System.Linq;
using Omu.ValueInjecter;
namespace Infrastructure.Data.Injection
{
public class EntityInjection : ConventionInjection
{
protected override bool Match(ConventionInfo c)
{
var propertyMatch = c.SourceProp.Name == c.TargetProp.Name;
var sourceNotNull = c.SourceProp.Value != null;
bool targetPropertyIdWritable = !(propertyMatch && c.TargetProp.Name == "Id" && !(c.Target.Value is IEntityClass));
return propertyMatch && sourceNotNull && targetPropertyIdWritable;
}
protected override object SetValue(ConventionInfo c)
{
if (c.SourceProp.Type.IsValueType || c.SourceProp.Type == typeof(string))
return c.SourceProp.Value;
if (c.SourceProp.Type.IsGenericType)
{
var td = c.SourceProp.Type.GetGenericTypeDefinition();
if (td != null && td.GetInterfaces().Contains(typeof(IEnumerable)))
{
var targetChildType = c.TargetProp.Type.GetGenericArguments()[0];
if (targetChildType.IsValueType || targetChildType == typeof(string)) return c.SourceProp.Value;
if (targetChildType.GetInterfaces().Any(x => x == typeof(IValueClass)))
{
var deleteMethod = c.TargetProp.Value.GetType().GetMethod("Remove");
var rmvItems = (c.TargetProp.Value as IEnumerable).Cast<IValueClass>()
.Where(x => x.Id > 0 && !(c.SourceProp.Value as IEnumerable).Cast<IValueClass>().Any(y => y.Id == x.Id));
rmvItems.ToList().ForEach(x => deleteMethod.Invoke(c.TargetProp.Value, new[] { x }));
rmvItems = (c.TargetProp.Value as IEnumerable).Cast<IValueClass>()
.Where(x => !(c.SourceProp.Value as IEnumerable).Cast<IValueClass>().Contains(x));
rmvItems.ToList().ForEach(x => deleteMethod.Invoke(c.TargetProp.Value, new[] { x }));
var sourceCollection = (c.SourceProp.Value as IEnumerable).Cast<IValueClass>();
foreach (var s in sourceCollection)
{
var sv = s;
var target = (c.TargetProp.Value as IEnumerable).Cast<IValueClass>().SingleOrDefault(z => z.Id == sv.Id && z.Id != 0);
if (target != null) target.InjectFrom<EntityInjection>(sv);
else if (!(c.TargetProp.Value as IEnumerable).Cast<IValueClass>().Contains(sv))
{
if (!(sv is IEntityClass))
{
sv = Activator.CreateInstance(targetChildType) as IValueClass;
Debug.Assert(sv != null);
sv.InjectFrom<EntityInjection>(s);
sv.Id = 0;
}
var addMethod = c.TargetProp.Value.GetType().GetMethod("Add");
addMethod.Invoke(c.TargetProp.Value, new[] { sv });
}
}
}
}
return c.TargetProp.Value;
}
if (c.SourceProp.Value is IEntityClass)
{
return c.SourceProp.Value;
}
if (c.TargetProp.Value == null)
{
try
{
c.TargetProp.Value = Activator.CreateInstance(c.TargetProp.Type);
}
catch (Exception)
{
return null;
}
}
return c.TargetProp.Value.InjectFrom<EntityInjection>(c.SourceProp.Value);
}
}
}
if you can't switch to LoopInjection you could also try to add this class into your project:
public abstract class ConventionInjection : ValueInjection
{
protected abstract bool Match(ConventionInfo c);
protected virtual object SetValue(ConventionInfo c)
{
return c.SourceProp.Value;
}
protected override void Inject(object source, object target)
{
var sourceProps = source.GetProps();
var targetProps = target.GetProps();
var ci = new ConventionInfo
{
Source =
{
Type = source.GetType(),
Value = source
},
Target =
{
Type = target.GetType(),
Value = target
}
};
for (var i = 0; i < sourceProps.Count; i++)
{
var s = sourceProps[i];
ci.SourceProp.Name = s.Name;
ci.SourceProp.Value = s.GetValue(source);
ci.SourceProp.Type = s.PropertyType;
for(var j=0; j < targetProps.Count; j++)
{
var t = targetProps[j];
ci.TargetProp.Name = t.Name;
ci.TargetProp.Value = t.GetValue(target);
ci.TargetProp.Type = t.PropertyType;
if (Match(ci))
t.SetValue(target, SetValue(ci));
}
}
}
}
public class ConventionInfo
{
public ConventionInfo()
{
Source = new TypeInfo();
Target = new TypeInfo();
SourceProp = new PropInfo();
TargetProp = new PropInfo();
}
public TypeInfo Source { get; set; }
public TypeInfo Target { get; set; }
public PropInfo SourceProp { get; set; }
public PropInfo TargetProp { get; set; }
public class PropInfo
{
public string Name { get; set; }
public Type Type { get; set; }
public object Value { get; set; }
}
public class TypeInfo
{
public Type Type { get; set; }
public object Value { get; set; }
}
}
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;
}
}
}
}
In my application, I would like to check whether or not a particular user is logged in or not so I can display a status saying that that user is either "online" or "offline" to another user. This question is not about authenticating a user, only about getting the authentication status of a user.
How would I go about achieving this?
I think an option is to use some real-time solutions. SignalR for example.
When a user logs in , you connect it to the hub. OnConnected() action save its state.Then OnDisconnected() remove from "OnlineRepository".
Update with example
Here is how I did this in a asp.Net Mvc 5 app.
A Model class that holds a single user like:
public class SingleConnection
{
public SingleConnection()
{
ConnectionId = new List();
}
public string Id { get; set; }
public List ConnectionId { get; set; }
}
A connection mapping class that helps in adding/removeing and getting a user from list
public class ConnectionMapping
{
private readonly List _connections = new List();
public int Count
{
get
{
return _connections.Count;
}
}
public void Add(string key, string connectionId)
{
lock (_connections)
{
var sn = _connections.Where(x => x.Id == key).FirstOrDefault();
if (sn != null) // there is a connection with this key
{
_connections.Find(x => x.Id == key).ConnectionId.Add(connectionId);
}
else
{
_connections.Add(new SingleConnection { Id = key, ConnectionId = new List { connectionId } });
}
}
}
public List GetConnections(string id)
{
var con = _connections.Find(x => x.Id == id);
return con != null ? con.ConnectionId : new List();
}
public List AllConnectionIds()
{
List results = new List();
var allItems = _connections.Where(x => x.ConnectionId.Count > 0).ToList();
foreach (var item in allItems)
{
results.AddRange(item.ConnectionId);
}
return results;
}
public List AllKeys()
{
return _connections.Select(x => x.Id).ToList();
}
public void Remove(string key, string connectionId)
{
lock (_connections)
{
var item = _connections.Find(x => x.Id == key);
if (_connections.Find(x => x.Id == key) != null)
{
_connections.Find(x => x.Id == key).ConnectionId.Remove(connectionId);
if (_connections.Find(x => x.Id == key).ConnectionId.Count == 0)
{
_connections.Remove(item);
}
}
}
}
}
In my Hub Class
private void IsActive(string connection, bool connected)
{
Clients.All.clientconnected(connection, connected);
}
public override Task OnConnected()
{
string name = Context.User.Identity.Name;
_connections.Add(name, Context.ConnectionId);
IsActive(name, true);
return base.OnConnected();
}
public override Task OnDisconnected(bool stopCalled)
{
string name = Context.User.Identity.Name;
_connections.Remove(name, Context.ConnectionId);
IsActive(name, false);
return base.OnDisconnected(stopCalled);
}
public override Task OnReconnected()
{
string name = Context.User.Identity.Name;
if (!_connections.GetConnections(name).Contains(Context.ConnectionId))
{
_connections.Add(name, Context.ConnectionId);
}
IsActive(name, false);
return base.OnReconnected();
}
In _Layout.cshtml
// reference scripts
// add a callback or the OnConnected() Will not fire
chat.client.clientconnected = function (id,active){
/*
this will be called everytime a user connect or disconnect to the hub
*/
}
$.connection.hub.start();
Now with this I get in realtime all users that are online.
Note: This is an InMemory solution. Other solutions are here
Hope this helps...
I would create my own system to define what are your "active" users:
You can keep the track of your users with a dictionary stored in the System.Web.Caching.Cache class.
In your base controller (because it would be instantiate for any
client request) insert the current user to your cached dictionary
by calling the KeepTrackActiveUsers method.
Add the SetInactiveUser method to your logout method.
{
private Dictionary<int,DateTime> ActiveUsers
{
get
{
if(Cache["ActiveUsers"] == null)
Cache["ActiveUsers"] = new Dictionary<int,DateTime>();
return Cache["ActiveUsers"];
}
set { Cache["ActiveUsers"] = value; }
}
private void KeepTrackActiveUsers()
{
ActiveUsers[CurrentUserId] = DateTime.Now;
}
private const int expirationTime = 600;
private IEnumerable<int> GetActiveUsers()
{
DateTime now = DateTime.Now;
ActiveUsers = ActiveUsers
.Where(x => now.Subtract(x.Value).TotalSeconds < expirationTime)
.ToDictionary(x => x.Key, x => x.Value);
return ActiveUsers.Keys;
}
private void SetInactiveUser()
{
ActiveUsers.Remove(CurrentUserId);
}
//to be defined
private int CurrentUserId
{
get { return default(int); }
}
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 stored some values into a model class using session variables and want to access them after the form submits. The values are stored in the ReportChooser Model and I would like to access the values in the View.
Report Controller
List<ReportEntryInfo> reiList = new List<ReportEntryInfo>();
foreach (string s in Request["ReportPeriodEntries"].ToString().Split(','))
{
string[] reportPeriodEntries = s.ToString().Split('_');
string reportPeriodID = reportPeriodEntries[0];
string entryID = reportPeriodEntries[1];
ReportEntryInfo rei = new ReportEntryInfo();
rei.EntryID = Convert.ToInt16(entryID);
rei.ReportPeriodID = Convert.ToInt16(reportPeriodID);
rei.ReportPeriodName = (from rp in db.ReportPeriods where rp.ReportPeriodID == rei.ReportPeriodID select rp.ReportPeriodName).FirstOrDefault();
reiList.Add(rei);
}
rc.ReportPeriodEntries = reiList;
List<ReportSchoolInfo> rsiList = new List<ReportSchoolInfo>();
foreach (string s in Request["Schools"].ToString().Split(','))
{
ReportSchoolInfo rsi = new ReportSchoolInfo();
rsi.SchoolID = Convert.ToInt16(s);
List<School> sList = db.Schools.Where(sc => sc.SchoolID == rsi.SchoolID && sc.IsActive == true).ToList();
foreach (School sl in sList)
{
rsi.SchoolName = sl.SchoolName;
rsi.SchoolLevelID = sl.SchoolLevelID;
rsi.DistID = sl.DistID;
rsi.DistName = sl.District.DistName;
}
rsiList.Add(rsi);
}
rc.Schools = rsiList;
rc.IndicatorID = indicatorID;
if (form["ComparisonSideBySide"] == "School")
rc.ComparisonSideBySide = ComparisonSideBySideValue.School;
else
rc.ComparisonSideBySide = ComparisonSideBySideValue.Entry;
rc.IncludeNarrative = Convert.ToBoolean(form["IncludeNarrative"]);
if (ModelState.IsValid)
{
if (indicatorID == 1)
{
if (rc.ComparisonSideBySide == ComparisonSideBySideValue.School)
return RedirectToAction("Leadership_sch");
else
return RedirectToAction("Leadership_entry");
}
else
{
ViewBag.ReportChooser = rc;
return View();
}
}
else
{
ViewBag.ReportChooser = rc;
return View();
}
View
#model IEnumerable<ImpactIndicator.Models.ReportDataModel>
#{
ViewBag.Title = "Report";
ImpactIndicator.Models.ReportChooser reportChooser = ViewBag.ReportChooser;
}
<hgroup class="title">
<h2>Report: Leadership</h2>
</hgroup>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
}
ReportChooser Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
namespace ImpactIndicator.Models
{
public enum ComparisonSideBySideValue { School, Entry };
public class ReportChooser
{
public int IndicatorID
{
get
{
if (HttpContext.Current.Session["ReportChooser_IndicatorID"] != null)
return Convert.ToInt16(HttpContext.Current.Session["ReportChoose_IndicatorID"]);
else
return 0;
}
set
{
HttpContext.Current.Session["ReportChooser_IndicatorID"] = value;
}
}
public List<ReportSchoolInfo> Schools
{
get
{
if (HttpContext.Current.Session["ReportChooser_SchoolInfo"] != null)
{
List<ReportSchoolInfo> schools=(List<ReportSchoolInfo>)HttpContext.Current.Session["ReportChooser_SchoolInfo"];
schools.OrderBy(t=>t.DistName).ThenBy(t=>t.SchoolName);
return schools;
}
else
return null;
}
set
{
HttpContext.Current.Session["ReportChooser_SchoolInfo"] = value;
}
}
public int SchoolLevelID
{
get
{
if (HttpContext.Current.Session["ReportChooser_SchoolLevelID"] != null)
return Convert.ToInt16(HttpContext.Current.Session["ReportChoose_SchoolLevelID"]);
else
return 0;
}
set
{
HttpContext.Current.Session["ReportChooser_SchoolLevelID"] = value;
}
}
public List<ReportEntryInfo> ReportPeriodEntries
{
get
{
if (HttpContext.Current.Session["ReportChooser_ReportPeriodEntries"] != null)
return (List<ReportEntryInfo>)HttpContext.Current.Session["ReportChooser_ReportPeriodEntries"];
else
return null;
}
set
{
HttpContext.Current.Session["ReportChooser_ReportPeriodEntries"] = value;
}
}
public bool IncludeNarrative
{
get
{
if (HttpContext.Current.Session["ReportChooser_IncludeNarrative"] != null)
return Convert.ToBoolean(HttpContext.Current.Session["ReportChooser_IncludeNarrative"]);
else
return false;
}
set
{
HttpContext.Current.Session["ReportChooser_IncludeNarrative"] = value;
}
}
public ComparisonSideBySideValue ComparisonSideBySide
{
get
{
if (HttpContext.Current.Session["ReportChooser_ComparisonSideBySide"] != null)
return (ComparisonSideBySideValue)HttpContext.Current.Session["ReportChooser_ComparisonSideBySide"];
else
return ComparisonSideBySideValue.Entry;
}
set
{
HttpContext.Current.Session["ReportChooser_ComparisonSideBySide"] = value;
}
}
public ReportChooser()
{
}
}
}
ReportDataModel Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ImpactIndicator.Models
{
public class ReportDataModel
{
public int IndicatorID { get; set; }
public int ReportPeriodID { get; set; }
public int EntryID { get; set; }
public int SchoolID {get; set;}
public bool IsSchoolRequiredToReport { get; set; }
public int? SchoolEntryID { get; set; }
public int? IndDomainID {get; set;}
public int? IndLevelID {get; set;}
public int? IndQuestionID {get; set;}
public string Response { get; set; }
public ReportDataModel()
{
}
}
}
You can access to variables stored in session using this
var variable = (Cast the type of variable)HttpContext.Current.Session["the key"];