Non static method requires a target - c#

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

Related

Why db.savechanges is storing the old records also?

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.

getting error while fetching fields from Dynamics CRM(Online Sales) from different server location

I am trying to fetch all account entity fields from an organization.(https://democrm365.crm4.dynamics.com).
Also, I created some custom fields in account and added into form. After that when I run the following code I am getting all fields related to account.
IOrganizationService service = (IOrganizationService)serviceProxy;
RetrieveEntityRequest request = new RetrieveEntityRequest()
{
EntityFilters = EntityFilters.Attributes,
RetrieveAsIfPublished = false,
LogicalName = "account"
};
RetrieveEntityResponse res = (RetrieveEntityResponse)service.Execute(request);
EntityMetadata currentEntity = res.EntityMetadata;
foreach (AttributeMetadata attribute in currentEntity.Attributes)
{
if (attribute.DisplayName.UserLocalizedLabel != null && attribute.AttributeType != null && attribute.LogicalName != "" && attribute.AttributeType != null && attribute.IsValidForRead.Value == true)
{
if (_allowedFieldTypes.Contains(attribute.AttributeType.ToString().ToLower()))
{
EntityField ef = new EntityField();
ef.AttributeType = attribute.AttributeType.ToString() ?? "";
ef.DisplayName = attribute.DisplayName.UserLocalizedLabel.Label;
ef.IsCustomField = attribute.IsCustomAttribute ?? false;
ef.IsAllowUpdate = attribute.IsValidForUpdate ?? false;
ef.LogicalName = attribute.LogicalName;
if (attribute.AttributeType.ToString().ToLower() == "picklist")
{
PicklistAttributeMetadata pm = (PicklistAttributeMetadata)attribute;
foreach (OptionMetadata x in pm.OptionSet.Options)
{
ef.Items.Add(x.Label.UserLocalizedLabel.Label);
}
}
else if (attribute.AttributeType.ToString().ToLower() == "virtual")
{
if (attribute.AttributeTypeName.Value == "MultiSelectPicklistType")
{
MultiSelectPicklistAttributeMetadata pm = (MultiSelectPicklistAttributeMetadata)attribute;
foreach (OptionMetadata x in pm.OptionSet.Options)
{
ef.Items.Add(x.Label.UserLocalizedLabel.Label);
}
}
}
if (Add)
{
fieldLst.Add(ef);
}
}
}
}
Again, I tested the same code on different organization (https://zoho5.crm.dynamics.com) with all above mentioned steps, then
below code is not working.
if (attribute.DisplayName.UserLocalizedLabel != null && attribute.AttributeType != null && attribute.LogicalName != "" && attribute.AttributeType != null && attribute.IsValidForRead.Value == true)
attribute.DisplayName.UserLocalizedLabel is null for all fields like (Account Name, Account No. Etc)
After some test runs, I removed the custom fields from account form and publish form. Then the above code is working fine.
Try this. You may have to get the label from LocalizedLabels when UserLocalizedLabel is null.
foreach (AttributeMetadata attribute in currentEntity.Attributes)
{
if (attribute.AttributeType != null && attribute.LogicalName != "" && attribute.AttributeType != null && attribute.IsValidForRead.Value == true)
{
string attributeName = attribute.LogicalName;
if (attribute.DisplayName.UserLocalizedLabel != null)
{
attributeName = attribute.DisplayName.UserLocalizedLabel.Label;
}
if (attributeName == attribute.LogicalName && attribute.DisplayName.LocalizedLabels.Count > 0)
{
attributeName = attribute.DisplayName.LocalizedLabels[0].Label;
}
}
}

ActiveDirectory Update a user getting UnauthorizedAccessException

When I attempt to update the Description of a user on the Domain Controller, I get the error UnauthorizedAccessException. I have validated the username and password I am using is in fact able to update the user. I logged in as the services username and password and manually changing the data. Here is my code.
private PrincipalContext pc = new PrincipalContext(ContextType.Domain, Common.DCData.serverName, null, ContextOptions.Negotiate, Common.DCData.userName, Common.DCData.password );
public bool Save(UserData data)
{
try
{
UserPrincipal up = UserPrincipal.FindByIdentity(pc, data.userName);
if ((data.DisplayName != null) && (data.DisplayName != "") && (data.DisplayName != up.DisplayName))
up.DisplayName = data.DisplayName;
if ((data.givenName != null) && (data.givenName != "") && (data.givenName != up.GivenName))
up.GivenName = data.givenName;
if ((data.middleName != null) && (data.middleName != "") && (data.middleName != up.MiddleName))
up.MiddleName = data.middleName;
if ((data.surname != null) && (data.surname != "") && (data.surname != up.Surname))
up.Surname = data.surname;
if ((data.emailAddress != null) && (data.emailAddress != "") && (data.emailAddress != up.EmailAddress))
up.EmailAddress = data.emailAddress;
if ((data.voiceTelephoneNumber != null) && (data.voiceTelephoneNumber != "") && (data.voiceTelephoneNumber != up.VoiceTelephoneNumber))
up.VoiceTelephoneNumber = data.voiceTelephoneNumber;
if ((data.description != null) && (data.description != "") && (data.description != up.Description))
up.Description = data.description;
up.Save(pc);
return true;
}
catch(Exception ex)
{
// Some logging goes here
}
}
The Common.DCData is a simple class that gets data from a database. I have double checked the username and password in the database
The static class I created to pull the data from SQL was not instantiated automatically (as I thought it would be) when referencing the static member. I ended up making the class a non-static class, and instantiating the class manually before using it.

To Check Session is null or not

In the below code I have Session variable in which I want to check whether it is null or not. Please help me to do this.
(SearchDoc) is class.
var SearchDoc = (SearchDoc)Session["Documentname"];
var oDocumentID = SearchDoc.ClientID;
var Documentid = SearchDoc.DocumentID;
if (SearchDoc == null)
{
}
This is the safest approach :
if ((HttpContext.Current.Session !=null && Session["Documentname"] as SearchDoc!= null))
{
//do what you want with
((SearchDoc)Session["Documentname"])
}
2 things to notice :
Yes , sometime the session object is null. ( probably occurs with AShX's without appropriate interface)
use the AS operator. - once it's ok , you can safely cast to SearchDOC
Try this
if(Session["Documentname"] != null)
{
var SearchDoc = (SearchDoc)Session["Documentname"];
var oDocumentID = SearchDoc.ClientID;
var Documentid = SearchDoc.DocumentID;
if (SearchDoc == null)
{
}
}
You can simply try this:
string oDocumentID = string.Empty;
string Documentid = string.Empty;
if(Session["Documentname"] != null){
var SearchDoc = (YourSearchDocType)Session["Documentname"];
oDocumentID = SearchDoc.ClientID;
Documentid = SearchDoc.DocumentID;
// some code
}
dont try to access some property of object which can be null

what is meaning of (model!=null) and (db!=null) in this context

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.

Categories

Resources