public bool SetupEmpty(UserViewModel model, SimsContext db)
{
if (model != null && db != null)
{
// Setup the User
model.User = new T2.Models.User();
model.User.Roles = "";
model.User.ActiveUser = true;
}
return false;
}
Checking that both model and db have been set before starting to use them. Otherwise, if one of them is not set the program could crash.
Related
I have very weird problem
My code it works fine if I login and use then it save the preferences etc.
But problem starts when I login, do some selections, and logout and login as another user, then upon saving it also remembers the seelctions I had done wfor the other user, the last one and save that also.
How to prevent this?
private ApplicationDbContext db = new ApplicationDbContext();
...
public IHttpActionResult Add(UserPreferencesDto model)
{
model.UserId = User.Identity.GetUserId();
var userPreferences = db.UserPreferences.Where(u =>
u.UserId == model.UserId &&
u.Key == model.Key.Trim())
.FirstOrDefault();
List<int> StatesCollection = new List<int>();
var param = model.Value.Trim();
string[] paramSplitted = param.Split(',');
if (userPreferences != null)
{
if (string.IsNullOrEmpty(userPreferences.Value) == false)
{
var trimmedPreferenceValue = userPreferences.Value.Trim('[', ']');
if (string.IsNullOrEmpty(trimmedPreferenceValue) == false)
{
StatesCollection = trimmedPreferenceValue.Split(',')
.Select(s => Convert.ToInt32(s)).ToList<int>();
}
if (model.IsStateSelected == false && paramSplitted.Count() == 1
&& StatesCollection.Contains(int.Parse(param.Trim())))
{
StatesCollection = StatesCollection.Where(sa => sa != int.Parse(param)).ToList<int>();
userPreferences.Value = StatesCollection.Count > 0 ? JsonConvert.SerializeObject(StatesCollection) : "";
}
else if (model.IsStateSelected && paramSplitted.Count() == 1
&& !StatesCollection.Contains(int.Parse(param)))
{
StatesCollection.Add(int.Parse(param));
userPreferences.Value = JsonConvert.SerializeObject(StatesCollection);
}
}
else
{
StatesCollection.Add(int.Parse(param));
userPreferences.Value = JsonConvert.SerializeObject(StatesCollection);
}
}
else
{
if (model.IsStateSelected == true)
{
//string[] splittedStates = model.Value.Split(',');
int[] secRolesIds = Array.ConvertAll(paramSplitted, int.Parse);
model.Value = JsonConvert.SerializeObject(secRolesIds);
db.UserPreferences.Add(Mapper.Map<UserPreferences>(model));
}
}
db.SaveChanges();
return Ok();
}
Even if the preferences exist it goes to the last else.
SaveChanges() in entity framework saves ALL tracked changes.
You would have to explicitly discard changes or use untracked entities, only adding them when you wish to save.
https://learn.microsoft.com/en-us/ef/core/querying/tracking
I think you should make the userPreferences variable null before giving a value to it, this way you could prevent it to have a value from the last execution because you would ensure it became null because you forced it to be. By doing so if there is no result in the database when you try to assign a value to it it will remain null for sure and so it will enter to the if with the if (userPreferences != null) and don't go to the else.
I am basically trying to handle unique constraint validation in my .Net API. I have two unique key cosntraints on two fields in my table.
If you see my code below , I am trying to check if the record exists. I am looking at returning a boolean value if the record exist. is that possible. For the time being, I am returning null.
Is this the best way to do it.
[HttpPost]
[SkipTokenAuthorization]
[Route("api/classificationoverrides/create")]
public IHttpActionResult Create(ClassificationItemViewModelCreate model)
{
var mgrClassificationService = GetService<MGR_STRT_CLASSIFICATION>();
var isExists = mgrClassificationService.Where(x =>
x.MANAGERSTRATEGYID == model.ManagerStrategyId && x.PRODUCT_ID == model.ProductId).FirstOrDefault();
if (isExists == null)
{
var mgrClassficationOverride = new MGR_STRT_CLASSIFICATION();
if (model != null)
{
mgrClassficationOverride.PRODUCT_ID = model.ProductId;
mgrClassficationOverride.LEGACY_STRATEGY_ID = model.LegacyStrategyId;
mgrClassficationOverride.STRATEGY_ID = model.StrategyId;
mgrClassficationOverride.MANAGERSTRATEGY_TYPE_ID = model.ManagerStrategyTypeId;
mgrClassficationOverride.MANAGERSTRATEGYID = model.ManagerStrategyId;
mgrClassficationOverride = mgrClassificationService.Create(mgrClassficationOverride);
}
return Ok(mgrClassficationOverride);
}
else
{
return null;
}
}
What is the Query results window's global service (interface)? Code below:
var dteService = Package.GetGlobalService(typeof(EnvDTE.DTE)) as EnvDTE.DTE;
if (dteService == null)
{
Debug.WriteLine("");
return;
}
var something=Package.GetGlobalService(typeof(???)) as ???;
EDIT: The goal is, when I press the context menu button, I want the function callback to be able to access the service where the work item is selected (or the results list
Please check this case in MSDN forum for the details how to get it work: https://social.msdn.microsoft.com/Forums/vstudio/en-US/2d158b9c-dec1-4c59-82aa-f1f2312d770b/sdk-packageget-selected-item-from-query-results-list
The following code is quoted from above link for your quick reference:
Document activeDocument = _applicationObject.ActiveDocument;
if (activeDocument != null)
{
DocumentService globalService = (DocumentService)Package.GetGlobalService(typeof(DocumentService));
if (globalService != null)
{
string fullName = activeDocument.FullName;
IWorkItemTrackingDocument document2 = globalService.FindDocument(fullName, null);
if ((document2 != null) && (document2 is IResultsDocument))
{
int[] selectedItemIds = ((IResultsDocument)document2).SelectedItemIds;
}
}
}
var dteService = Package.GetGlobalService(typeof(EnvDTE.DTE)) as EnvDTE.DTE;
if (dteService == null)
{
Debug.WriteLine("");
return;
}
DocumentService documentService = Package.GetGlobalService(typeof(DocumentService)) as DocumentService;
if (documentService == null)
return;
string fullName = dteService.ActiveDocument.FullName;
IWorkItemTrackingDocument activeDocument = documentService.FindDocument(fullName, null);
if (activeDocument == null || !(activeDocument is IResultsDocument))
return;
private PMS_USERS currUser;
private bool validateUserName()
{
dbContext = new PmsEntities();
var validateUser = dbContext.PMS_USERS.Where(p=> p.LOGICALREF != currUser.LOGICALREF).Where(p=> p.USERNAME == currUser.USERNAME);
return !validateUser.Any();
}
Hello,
I got an error while validating on my new user register form.
My PMS_USERS table has no record(null). I also tried checking for null control(s) for currUser.
What am I missing?
Error is :
Non static method requires a target
You should first test if currUser is null or not and your dbContext too.
if (currUser == null) return false;
if (dbContext == null) throw new Exception ("The dbContext has not been set");
Secondly, you can simplify your query like yhat :
var validateUser = dbContext.PMS_USERS.Where(p=> p.LOGICALREF != currUser.LOGICALREF && p.USERNAME == currUser.USERNAME);
And then change the return statement to :
return (validateUser.FirstOrDefault() != null);
You can alternativelly use SingleOrDefault statement insead of FirstOrDefault, if you want to be sure there is only one user corresponding to your criteria.
"Non static method requires a target" means that some object inside the scope is null.
Try checking the context and the var result values:
dbContext = new PmsEntities();
if (dbContext != null && currUser != null)
{
var validateUser = dbContext.PMS_USERS.Where(p=> p.LOGICALREF != currUser.LOGICALREF && p.USERNAME == currUser.USERNAME);
if (validateUser !=null)
{
return !validateUser.Any();
}
else
return null;
}
Check it and tell us if you have the same exception.
Use
private PMS_USERS currUser;
private bool validateUserName()
{
dbContext = new PmsEntities();
return PMS_USERS != null
? var validateUser = dbContext.PMS_USERS.Where(p=> p.LOGICALREF != currUser.LOGICALREF).Where(p=> p.USERNAME == currUser.USERNAME).Any()
: false;
}
I am working on a website. I have to find the value of user can't change password property of a user. I get this link
http://msdn.microsoft.com/en-us/library/aa746448(v=vs.85).aspx[^]
according to which I have to find "ntSecurityDescriptor" value of that user. They are using DirectoryEntry class to find that but in my case I am using LdapConnection class.
If I use entry class I was not able to make connectivity with server So that I change it to LdapConnection class. Now I don't know how to find value.
I find my solution.
SearchResponse response = (SearchResponse)connection.SendRequest(request);
DirectoryAttribute attribute = response.Entries[0].Attributes["ntSecurityDescriptor"];
if (attribute != null)
{
const string PASSWORD_GUID = "{ab721a53-1e2f-11d0-9819-00aa0040529b}";
const int ADS_ACETYPE_ACCESS_DENIED_OBJECT = 6;
bool fEveryone = false;
bool fSelf = false;
ActiveDs.ADsSecurityUtility secUtility = new ActiveDs.ADsSecurityUtility();
ActiveDs.IADsSecurityDescriptor sd = (IADsSecurityDescriptor)secUtility.ConvertSecurityDescriptor((byte[])attribute[0], (int)ADS_SD_FORMAT_ENUM.ADS_SD_FORMAT_RAW, (int)ADS_SD_FORMAT_ENUM.ADS_SD_FORMAT_IID);
ActiveDs.IADsAccessControlList acl = (ActiveDs.IADsAccessControlList)sd.DiscretionaryAcl;
foreach (ActiveDs.IADsAccessControlEntry ace in acl)
{
if ((ace.ObjectType != null) && (ace.ObjectType.ToUpper() == PASSWORD_GUID.ToUpper()))
{
if ((ace.Trustee == "Everyone") && (ace.AceType == ADS_ACETYPE_ACCESS_DENIED_OBJECT))
{
fEveryone = true;
}
if ((ace.Trustee == #"NT AUTHORITY\SELF") && (ace.AceType == ADS_ACETYPE_ACCESS_DENIED_OBJECT))
{
fSelf = true;
}
break;
}
}
if (fEveryone || fSelf)
{
return Global.RequestContants.CANT_CHANGE_PASSWORD;
}
else
{
return string.Empty;
}
}