Session object is working on localhost but fails on server - c#

I have created a SessionManager class in my MVC 5 Web application to maintain session for the application. This class works fine on localhost but failes on server. Here is my SessionManager class code:
public class SessionManager : BaseController
{
private HttpContext _context;
public SessionManager()
{
//TODO:
}
public SessionManager(HttpContext context)
{
_context = context;
}
private RAWOnlineDBEntities db = new RAWOnlineDBEntities();
private string _FromMailID = string.Empty;
private string _FromPassword = string.Empty;
private string _CompanyName = string.Empty;
private string _AdminEmailID = string.Empty;
public string FromMailID
{
get
{
if (_context != null && _context.Session != null)
{
if (_context.Session["FromMailID"] == null)
{
_context.Session["FromMailID"] = db.Users.Where(u => u.CompanyID == CompanyID && u.UserID == UserID && u.IsActive == true).Select(table => table.InternalMailID).FirstOrDefault();
}
}
//return _FromMailID = _context.Session["FromMailID"].ToString(); // localhost
// Server
return _FromMailID = db.Users.Where(u => u.CompanyID == CompanyID && u.UserID == UserID && u.IsActive == true).Select(table => table.InternalMailID).FirstOrDefault();
}
}
public string FromPassword
{
get
{
try
{
if (_context != null && _context.Session != null)
{
if (_context.Session["FromPassword"] == null)
{
_context.Session["FromPassword"] = db.Users.Where(u => u.CompanyID == CompanyID && u.UserID == UserID && u.IsActive == true).Select(table => table.InternalMailIDPassword).FirstOrDefault();
}
}
_FromPassword = _context.Session["FromPassword"].ToString();
}
catch (Exception ex)
{
//ErrorSignal.FromCurrentContext().Raise(ex); //ELMAH Signaling
IsSuccess = false;
ViewBag.ErrorMessage = "Transaction failed. Please try again. If problem persists, contact system administrator.";
ViewBag.InfoMessage = "";
// Handle exception here and Log Error to text file...
string sLogFilePath = Server.MapPath(#"~/ApplicationFiles/ErrorLog/ErrorLogFile.txt");
GeneralRepository.LogErrorToFile(ex, sLogFilePath, "FromPassword from session manager");
}
return _FromPassword;
}
}
public string CompanyName
{
get
{
if (_context != null && _context.Session != null)
{
if (_context.Session["CompanyName"] == null)
{
_context.Session["CompanyName"] = db.CompanyMasters.Where(u => u.CompanyID == CompanyID && u.IsActive == true).Select(table => table.CompanyName).FirstOrDefault();
}
}
return _CompanyName = _context.Session["CompanyName"].ToString();
}
}
public string AdminEmailID
{
get
{
if (_context != null && _context.Session != null)
{
if (_context.Session["AdminEmailID"] == null)
{
_context.Session["AdminEmailID"] = (from table in db.Users
where table.RoleID == ADMIN_ROLE
&& table.IsActive == true
&& table.UserName.ToUpper() == "ADMIN"
select table.EmailID).FirstOrDefault();
}
}
return _AdminEmailID = _context.Session["AdminEmailID"].ToString();
}
}
}
And I am calling this class like this in my controller action method...
System.Web.HttpContext currentContext = System.Web.HttpContext.Current;
SessionManager objSessionManager = new SessionManager(currentContext);
StringBuilder MsgBody = MakeMailBodyForReportCreated(objReportTransactionData);
EmailRepository.SendEmail(objSessionManager.FromMailID, objSessionManager.FromPassword, ToMailAddress, CCMailAddress, MsgSubject, MsgBody.ToString());
and here is my web.config file
<sessionState mode="InProc" timeout="20"></sessionState>
<pages validateRequest="false" enableSessionState="true" />
<modules>
<remove name="Session" />
<add name="Session" type="System.Web.SessionState.SessionStateModule" />
</modules>
Please help...

Related

EF cannot update column when success savechanges

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;
}
}
}
}

ConcurrentBag FirstOrDefault NullCheck throws

I've got a Problem at my null check .
if (element == null)
throws
Object reference not set to an instance of an object.
Why can a simple null check fail at this Point? When i make a breakpoint at this Position, element has the value "null", but throws the exception anyway.
PS: At this Point, are no additional Threads active.
internal static ConcurrentBag<Node_Library> AddFileDetail(
this ConcurrentBag<Node_Library> list,
FileDetails file , Node<Node_Application> app)
{
var element = list.FirstOrDefault(x => file.Equals(x));
if (element == null)
{
list.Add(new Node_Library(file, app));
}
else
{
if (!element.ApplicationNodes.Contains(app))
{
element.AddNode(app);
}
}
return list;
}
EDIT: file is not null, the list is empty but not null
EDIT2: Operator and FileDetail details
public class FileDetails
{
internal string FileName { get; private set; }
internal string Name { get; private set;}
internal string Endung { get; private set; }
internal string Version { get; private set; }
internal string Produkt { get; private set; }
internal string ProduktVersion { get; private set; }
internal FileTyp Filetyp { get; private set; }
internal string Pfad { get; private set; }
public static bool operator==(FileDetails file1, Node_Library library)
{
return
file1.Version == library.Version &&
file1.Produkt == library.Produkt &&
file1.ProduktVersion == library.ProduktVersion &&
file1.FileName == library.FileName;
}
public static bool operator !=(FileDetails file1, Node_Library library)
{
return
!(file1.Version == library.Version &&
file1.Produkt == library.Produkt &&
file1.ProduktVersion == library.ProduktVersion &&
file1.FileName == library.FileName);
}
public static bool operator ==(FileDetails file1, FileDetails file2)
{
if (
file1.FileName == file2.FileName &&
file1.Produkt == file2.Produkt &&
file1.ProduktVersion == file2.ProduktVersion &&
file1.Version == file2.Version)
return true;
return false;
}
public static bool operator !=(FileDetails file1, FileDetails file2)
{
if (
file1.Name == file2.Name &&
file1.Produkt == file2.Produkt &&
file1.ProduktVersion == file2.ProduktVersion &&
file1.Version == file2.Version)
return false;
return true;
}
internal bool Equals(Node_Library file2)
{
if (file2 == null)
{
return false;
}
return (
Name == file2.Name &&
Produkt == file2.Produkt &&
ProduktVersion == file2.ProduktVersion &&
Version == file2.Version);
}
//More Stuff
}
EDIT3:
I used a breakpoint in my equal overload, but it never triggered... So the problem is maybe the FirstOrDefault?
finally:
Operatoroverload was faulty. Fixed it. Ty a lot.
The problem lies in your operators:
public static bool operator==(FileDetails file1, Node_Library library)
{
return
file1.Version == library.Version &&
file1.Produkt == library.Produkt &&
file1.ProduktVersion == library.ProduktVersion &&
file1.FileName == library.FileName;
}
When you compare an instance to null it's trying to access the properties Version, Produkt, ProduktVersion and FileName from a null instance, hence the NullReferenceException.
So, answering to your initial question "Why can a simple null check fail at this Point?", it's because there's nothing simple about that null check once you override the operators. =D
To solve it, you can add a null check on file2:
public static bool operator ==(FileDetails file1, FileDetails file2)
{
if (file2 != null &&
file1.FileName == file2.FileName &&
file1.Produkt == file2.Produkt &&
file1.ProduktVersion == file2.ProduktVersion &&
file1.Version == file2.Version)
return true;
return false;
}
The problem may be the previous line:
var element = list.FirstOrDefault(x => file.Equals(x));
The file parameter is probably null.
EDIT: If file is not null, then the FileDetails.Equals method can be the culprit.

when session id null redirect to login page by using angularjs or mvc

If CurretUserToken is null i am redirecting to LoginPage, but it is redirecting on current layout, i want to render on LoginLayout page
public override void OnAuthorization(AuthorizationContext filterContext)
{
if(filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true)
|| filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AllowAnonymousAttribute), true))
return;
CurrentUserToken = sessionManager.CurrentUserToken;
if (string.IsNullOrEmpty(CurrentUserToken))
HandleUnauthorizedRequest(filterContext);
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { Action = "SignIn", Controller = "Account" }));
}
and this is my controller to which i am redirecting when CurrentUserToken is Null
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> SignIn(LoginModel loginModel, string actionType)
{
if (actionType == "Login")
{
if (loginModel.RememberMe && CheckUserCookie()==null)
{
InsertCookie(loginModel);
}
sessionManager.CurrentUserToken = string.Empty;
loginModel.UserIp = GetClientIPAddress();
resource = "/api/av_sessions/login";
UserModel data = new UserModel();
LoginValidator loginValidator = new LoginValidator();
var validator = loginValidator.Validate(loginModel);
if (validator.Errors.Count() == 0)
{
data = await Post<UserModel>(loginModel);
sessionManager.CurrentUserToken = data.Data.Token;
//sessionManager.LoggedInUserName = loginModel.UserName;
if (data.Errors.Count > 0)
{
sessionManager.CurrentUserToken = string.Empty;
TempData["ErrorMessages"] = string.Join("<br>", data.Errors);
return View("SignIn");
}
else
{
resource = "/api/applications";
var response = await Get<ApplicationListModel>();
this.sessionManager.UserName = loginModel.UserName;
if (!IsValidApps(response))
{
return RedirectToAction("WelCome", "Account");
}
}
}
else
{
var errors = validator.Errors.Select(e => e.ErrorMessage).ToList();
data.Status = Constants.Error;
data.Errors = errors;
sessionManager.CurrentUserToken = string.Empty;
TempData["ErrorMessages"] = string.Join("<br>", data.Errors);
return View("SignIn");
}
}
if (actionType == "Register")
{
return View("Register");
}
return RedirectToAction("DashBoard", "Home");
}
public ActionResult SignOff()
{
//formsAuth.SignOut();
//if (HttpContext.Session != null) HttpContext.Session.RemoveAll();
this.sessionManager.CurrentUserToken = string.Empty;
return RedirectToAction("SignIn", "Account");
}

Multiple User Roles in Authorize

I have a controller which can be accessed by user having admin privileges or nurse. Then on separate action I can do more strict if I want to. Right now what I have is something like this
[AuthorizeUser(UserRole = "Admin", OrganizationType = "Institution")]
It works fine. But I would something like
[AuthorizeUser(UserRole = "Admin,Nurse", OrganizationType = "Institution")]
AuthorizeUser is custom made authorization
public class AuthorizeUser : AuthorizeAttribute
{
public string UserRole { get; set; }
public string OrganizationType { get; set; }
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var isAuthorized = base.AuthorizeCore(httpContext);
if (!isAuthorized)
{
return false;
}
return CheckOrganizationType
.checkRole(this.UserRole, this.OrganizationType, Auth.CurrentUser);
}
}
public static bool checkRole(String role, String organizationType, User user)
{
RolesType rt = null;
OrganizationType ot = null;
foreach (UserRoles ur in user.GetUserRoles())
{
rt = RolesType.Get(ur.organizationTypeId,ur.roleTypeId);
ot = OrganizationType.Get(ur.organizationTypeId, "1");
}
if (rt != null && rt.Name == role && ot != null && ot.Name == organizationType)
{
return true;
}
else
{
return false;
}
}
and then check if the current user has any of the defined roles. How can this be done? Any idea?
You have just to change this statement:
if (rt != null && rt.Name == role && ot != null && ot.Name == organizationType)
with this:
if (rt != null && role.Contains(rt.Name) && ot != null && ot.Name == organizationType)

How I can use profile in web application

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">

Categories

Resources