Casting Error: Inserting data into Custom MembershipUser - c#

I'm attempting to fill in data to my NCCMembershipUser with the following code:
string name = User.Identity.Name;
NCCMembershipUser currentUser = (NCCMembershipUser)NCCMembershipProvider.GetUser(name, true);
currentUser.Salutation = GenderSelect.SelectedValue;
currentUser.FirstName = TextBoxFirstName.Text;
currentUser.LastName = TextBoxLastName.Text;
currentUser.Position = TextBoxPosition.Text;
...
try
{
NCCMembershipProvider u = (NCCMembershipProvider)Membership.Provider;
u.UpdateUser(currentUser);
}
I am getting an error "An object reference is required for the non-static field, method, or property 'System.Web.Security.MembershipProvider.GetUser(string, bool)'"
If I instead use Membership.GetUser() (without the name string) to access the current user, it gives me a casting error, and GetUser() appears it cannot be overridden.
Edit:
The casting error I get is "[A]NCC.App_Code.NCCMembershipProvider cannot be cast to [B]NCC.App_Code.NCCMembershipProvider."

The error tells you that the GetUser method isn't static, so it cannot be invoked without an instance of the NCCMembershipProvider class.
You have to grab your provider earlier in your method:
string name = User.Identity.Name;
NCCMembershipProvider u = (NCCMembershipProvider)Membership.Provider;
NCCMembershipUser currentUser = (NCCMembershipUser)u.GetUser(name, true);
currentUser.Salutation = GenderSelect.SelectedValue;
currentUser.FirstName = TextBoxFirstName.Text;
currentUser.LastName = TextBoxLastName.Text;
currentUser.Position = TextBoxPosition.Text;
// ...
try
{
u.UpdateUser(currentUser);
}

The casting error I get is "[A]NCC.App_Code.NCCMembershipProvider
cannot be cast to [B]NCC.App_Code.NCCMembershipProvider."
For this error, verify that you don't have that class in your App_Code folder, if so, move it to another place like a new folder called Membership
That will take care of the casting issue as the app is compiling 2 different DLLs into 2 different places in the temporary asp.net folders.

Related

CS1061 'IEnumerable<<anonymous type: x>>' does not contain a definition for dump

I just want to get the password out of my software KeePass.
After using the code from an old question here Link to the question, im getting this error message:
S1061 'IEnumerable<<anonymous type: string Group, string Title, string Username, string Password>>' does not contain a definition for 'Dump' and no accessible extension method 'Dump' accepting a first argument of type 'IEnumerable<<anonymous type: string Group, string Title, string Username, string Password>>' could be found (are you missing a using directive or an assembly reference?) KeePasso C:\Users\prusinma\source\repos\KeePasso\KeePasso\Program.cs 36 Active
This is the code im using:
using System.Linq;
using KeePassLib;
using KeePassLib.Keys;
using KeePassLib.Serialization;
namespace KeePasso
{
class Program
{
static void Main()
{
var dbpath = #"\\xxx\Home_VIE\xxx\Desktop\KeePassDatabase\Database.kdbx";
var keypath = #"\\xxx\Home_VIE\xxx\Desktop\KeePassDatabase\Database.key";
var masterpw = "1234abcd";
var ioConnInfo = new IOConnectionInfo { Path = dbpath };
var compKey = new CompositeKey();
compKey.AddUserKey(new KcpPassword(masterpw));
compKey.AddUserKey(new KcpKeyFile(IOConnectionInfo.FromPath(keypath))); // Keyfile
var db = new PwDatabase();
db.Open(ioConnInfo, compKey, null);
var kpdata = from entry in db.RootGroup.GetEntries(true)
select new
{
Group = entry.ParentGroup.Name,
Title = entry.Strings.ReadSafe("Title"),
Username = entry.Strings.ReadSafe("UserName"),
Password = entry.Strings.ReadSafe("Password"),
};
kpdata.Dump(); // this is how Linqpad outputs stuff
db.Close();
}
}
}
In the last rows in the code, there is a red underline at Dump. Which displays the same error message i shared above.
I was already trying to find similiar questions and in most of them they were related to the type. But as i can see, all the datas/entries in Title, Username and Password are strings.
Would appreciate if someone could help me here out. Id also be open for a other solution how to read out the password from the database.
Thanks!
Since kpdata is collection of anonimous types, which has overriden ToString (and if entry.Strings.ReadSafe returns string or some type with "correctly" overriden ToString method) you can just use Console.WriteLine on it:
Console.WriteLine(string.Join(Environment.NewLine, kpdata));; // instead of kpdata.Dump();
Otherwise you will need to find a way to import LINQPad's Dump method into your project or just use some json serialization library to convert object to string.
Cast it to object!
//But This works!
((object)d).Dump();
// as does this)
(d as Object).Dump()

The settings key with code name 'XX' already exists

I am trying to save a setting in Kentico and I get this error:
The settings key with code name 'AvalaraOrderStatus' already exists.
I already created the setting and I have saved a value to it. The code worked fine in Kentico 8, but I was asked for no SiteInfiIdentifer.
Here is the code I created to make the setting:
//if the setting does not exist, then create it
if (SettingsKeyInfoProvider.GetSettingsKeyInfo(siteName + ".AvalaraOrderStatus", siteID) == null)
{
// Create and set up new SettingsKey
SettingsKeyInfo si = new SettingsKeyInfo();
si.KeyName = "AvalaraOrderStatus";
si.KeyDisplayName = "Avalara Order Status";
si.KeyDescription = "Avalara order status for this site";
si.KeyType = "string";
si.KeyValue = string.Empty;
si.KeyCategoryID = category.CategoryID;
SettingsKeyInfoProvider.SetSettingsKeyInfo(si);
}
The code throws the error on the last line. Here is my code:
int currentSiteID = CMS.SiteProvider.SiteContext.CurrentSiteID;
SiteInfoIdentifier siteId = new SiteInfoIdentifier(currentSiteID);
//update settings in system
SettingsKeyInfoProvider.SetValue(siteName + ".AvalaraOrderStatus", siteId, orderStatus.Trim());
A few things to note:
The first parameter of the SettingsKeyInfoProvider.GetSettingsKeyInfo method does not need to be prefixed with the site name. This is why a site identifier is provided (in your case, the SiteID). Otherwise, you might be getting a null value every time the if statement evaluates, which is why the setting key is being recreated even if it exists. So that should be:
SettingsKeyInfoProvider.GetSettingsKeyInfo("AvalaraOrderStatus", siteID)
The same applies for the SettingsKeyInfoProvider.SetValue method - no need to prefix the site name:
SettingsKeyInfoProvider.SetValue("AvalaraOrderStatus", siteId, orderStatus.Trim())
The CurrentSiteID integer is a valid SiteIdentifier, so there is no need to explicitly instantiate a SiteInfoIdentifier object:
SettingsKeyInfoProvider.SetValue("AlavaraOrderStatus", CMS.SiteProvider.SiteContext.CurrentSiteID, orderStatus.Trim())

How to check if an azure active directory user is already in an approle

I've created an Azure active directory user and added the user to app roles.
Now i am retrieving this user and attempting to add it to more app roles.
var activeDirectoryUser = client.Users.Where(u => u.UserPrincipalName == user.UserName).ExecuteSingleAsync().Result as User;
As a precaution i want to first check if the user is already in an app role before adding however the problem is that the ApproleAssignments field on the User object is always empty. Even thou the user has app role assignments and i get an error if i try and add the user to the same app role.
Creating new app role assignment.
var appRoleAssignment = new AppRoleAssignment
{
Id = appRole.Id,
ResourceId = Guid.Parse(servicePrincpal.ObjectId),
PrincipalType = "User",
PrincipalId = Guid.Parse(user.ObjectId)
};
if(IsUserInAppRole(user,appRoleAssignment))return;
user.AppRoleAssignments.Add(appRoleAssignment);
user.UpdateAsync().Wait();
Checking if user is in app role.
private bool IsUserInAppRole(User user, AppRoleAssignment appRoleAssignment)
{
var userInApprole = user.AppRoleAssignments.Where(ara => ara.ObjectId == appRoleAssignment.Id.ToString());
return userInApprole.Any();
}
I'm using the latest version of Microsoft.Azure.ActiveDirectory.GraphClient library
Sorry for the late response. The following code worked for me. Not sure if you need to use the IUserFetcher interface, but your LINQ query fails because you are comparing the objectID of the assignment, with the appRole Id. What you need to compare is the ID of the assignment.
var userFetcher = user as IUserFetcher;
IPagedCollection<IAppRoleAssignment> rawObjects = userFetcher.AppRoleAssignments.ExecuteAsync().Result;
IList<IAppRoleAssignment> assignments = rawObjects.CurrentPage.ToList();
IAppRoleAssignment a = null;
a = assignments.Where(ara => ara.Id.Equals(appRole.Id)).First();
if (a != null) {
Console.WriteLine("Found assignment {0} for user {1}", appRole.Id, user.DisplayName);
}
Hope this helps...
var userFetcher = user as IUserFetcher;
IPagedCollection rawObjects = userFetcher.AppRoleAssignments.ExecuteAsync().Result;
IList<IAppRoleAssignment> assignments = rawObjects.CurrentPage.ToList();
Above lines of code is causing exception due to casting not done, if cast it as:
IPagedCollection rawObjects =
(IPagedCollection)userFetcher.AppRoleAssignments.ExecuteAsync().Result;
IList<IAppRoleAssignment> assignments =
(IList<IAppRoleAssignment>)rawObjects.CurrentPage.ToList();
Code get compiled successfully but gives runtime exception as:
Cannot implicitly convert type 'System.Collections.Generic.List' to 'System.Collections.Generic.IList'. An explicit conversion exists (are you missing a cast?)
Could you please guide how to use those two statements?
Update:
private static bool IsUserInRole(User user, AppRole appRole, bool roleAlreadyAssigned = false)
{
var userFetcher = user as IUserFetcher;
IPagedCollection rawObjects = (IPagedCollection)userFetcher.AppRoleAssignments.ExecuteAsync().Result;
foreach (IAppRoleAssignment item in rawObjects.CurrentPage)
{
if (item.Id == appRole.Id)
{
roleAlreadyAssigned = true; break;
}
}
return roleAlreadyAssigned;
}
The above code worked for me. Try this, hope this will help :)

Object reference not set to an instance of an object when accessing user profile information

I have created a different identity table MyUserInfo for my user profile where I store additional info such as Name, address etc. The idea is that if the user has not entered his / her data then he will be sent to another page where it can be done. The issue is that when I try to verify if the client has entered his name, address etc... i get an an error and I don't understand why:
Additional information: Object reference not set to an instance of an object.
this happens at the line where I try to check if the value of the User Name is null
if (currentUser.MyUserInfo.FirstName == null)
Here is the code:
string user = System.Web.HttpContext.Current.User.Identity.Name;
var store = new UserStore<ApplicationUser>(new ApplicationDbContext());
store.AutoSaveChanges = false;
var currentUserId = User.Identity.GetUserId();
var manager = new UserManager<ApplicationUser>(store);
var currentUser = manager.FindById(User.Identity.GetUserId());
//check if the user is registered and what his role is
if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated && System.Web.HttpContext.Current.User.IsInRole("Customer"))
{
if (currentUser.MyUserInfo.FirstName == null) //offending line
{
Response.Redirect("EnterUserData.aspx");
}
}
If manager.FindByID() returns null, you will get that exception when you try and reference properties in the currentUser object (which of course would also be null). In addition, currentUser.MyUserInfo could be null, causing the same issue.

Sharepoint Client Object Model setting ModifiedBy field

I am trying to update the "ModifiedBy" field in a Sharepoint discussion board using the Client Object Model. By changing the "Editor" and "Author" fields, I can change the "ModifiedBy" that appears on the list view. However, once you click on a discussion post, the "ModifiedBy" field that appears there (the one with the picture above it) does not reflect the changes. After experimenting, I discovered that the field I need to change to correct this is called "MyEditor". Unfortunately, this field is read-only.
In the code below, I try to change the read-only settings of the field to false. When I look at the MyEditor field in Visual Studio's debugger after the ExecuteQuery() line at the bottom of the first block, it shows that the ReadOnlyField value has in fact been set to false.
sharepointContext.Load(discussionList);
sharepointContext.ExecuteQuery();
var fields = discussionList.Fields;
sharepointContext.Load(fields);
sharepointContext.ExecuteQuery();
var field = fields.GetByInternalNameOrTitle("MyEditor");
field.ReadOnlyField = false;
field.Update();
sharepointContext.Load(field);
sharepointContext.ExecuteQuery();
The code above executes with no problems. The problem comes with this next block:
//...Code to initialize discussionItem...
discussionItem["MyEditor"] = 0;
discussionItem["Editor"] = 0;
discussionItem["Author"] = 0;
discussionItem["Body"] = "Testing";
discussionItem["Title"] = "Hello Worlds";
discussionItem.Update();
sharepointContext.Load(discussionItem);
sharepointContext.ExecuteQuery();
When the code reaches the ExecuteQuery() at the bottom of the second block, it throws a ServerException with the following message:
Invalid data has been used to update the list item.
The field you are trying to update may be read only.
To make sure that the MyEditor field was the one causing the exception to be thrown, I commented out the line where I set it and ran the code again. Everything worked fine. I don't understand what is wrong, can someone help me?
In case someone needs to find the user by name, it goes like this:
private static FieldUserValue GetUser(ClientContext clientContext, string userName)
{
var userValue = new FieldUserValue();
var newUser = clientContext.Web.EnsureUser(userName);
clientContext.Load(newUser);
clientContext.ExecuteQuery();
userValue.LookupId = newUser.Id;
return userValue;
}
The returned value can be set via item["Author"]
ModifiedBy and CreadtedBy calculated automatically from Author and Editor you need to change only Author and Editor fields like this:
using (var clientContext = new ClientContext(#"http://server"))
{
var web = clientContext.Web;
var lst = web.Lists.GetByTitle("Discus");
var item = lst.GetItemById(2);
item["Author"] = 3;
item["Editor"] = 2;
item.Update();
clientContext.ExecuteQuery();
Console.WriteLine("done");
}

Categories