Insert into bridge table entity framework - asp.net

Hi guys,
I'm learning to climb with EF ,I do have basic understanding of CRUD with EF ,but now I have a table which have a navigation property (Which I suspect is the bridge table) ,so I need to add value into the bridge table ,I think I can do it with navigational property.
Problem Explained:
Original partial DB Diagram
Partial EF Model Diagram
Code I Wrote:
protected void BtnAddUser_Click(object sender, EventArgs e)
{
DBEntities entities = new DBEntities();
var usr = new User();
//I thought I would add an Roles object into usr.UserRoles.Add(usrRoles);
//but UserRoles have only two fields ,RoleTypeId and UserId
//var usrRoles = new Roles()
//{Id=0,RoleDescription="dfdfdf",RoleType="WebSite Admin"};
usr.UserName = TxtbxUserName.Text;
usr.Password = TxtBxPassword.Text;
usr.Email = TxtbxEmail.Text;
usr.CreateDate = DateTime.Now;
usr.LastActivityDate = DateTime.Now;
usr.IsEnabled = true;
//What to Add in the .Add method
usr.UserRoles.Add(
entities.User.AddObject(usr);
int result = entities.SaveChanges();
LblMsg.Text = result == 1 ? "User created successfully." : "An error occured ,please try later.";
entities.Dispose();
}
Update (What I have tried so far):
I fetch "Website Admin" role from roles table and put it into ObjectContext.UserRoles.Add(UserRoleWebsiteAdmin);
So that what I did in the code,
//Fetch WebsiteAdmin from Roles
var userRole = from usrRole in entities.Roles
where usrRole.Id == 1
select usrRole;
usr.UserName = TxtbxUserName.Text;
//same old code of usr.Property = someTextBox
//I have tried to type cast it LinqtoEntities result into Roles
usr.UserRoles.Add((Roles)userRole);
Exception generated
P.S: Let me know if you need more clarification.

Maybe you can use using http://msdn.microsoft.com/en-us/library/yh598w02.aspx and object initializer http://msdn.microsoft.com/en-us/library/bb384062.aspx for better readability so:
using(DBEntities entities = new DBEntities())
{
//Make user object
var user = new User{
UserName = TxtbxUserName.Text,
Password = TxtBxPassword.Text,
Email = TxtbxEmail.Text,
CreateDate = DateTime.Now,
LastActivityDate = DateTime.Now,
IsEnabled = true
};
//Fetch type of Role from Roles table
var userRole = entities.Roles.Where(x=>x.usrRole.Id ==1).Single();
user.UserRoles.Add(userRole);
entities.User.AddObject(user);
int result = entities.SaveChanges();
LblMsg.Text = result == 2 ? "User created succesfully." : "An error occured ,please try later.";
}
Regards

Well thanks guys...
Here what I have done and it works,
DBEntities entities = new DBEntities();
//Make user object
var usr = new User();
//Fetch type of Role from Roles table
var userRole = (from usrRole in entities.Roles
where usrRole.Id == 1
select usrRole).Single();
//copy user related info from textboxes
usr.UserName = TxtbxUserName.Text;
usr.Password = TxtBxPassword.Text;
usr.Email = TxtbxEmail.Text;
usr.CreateDate = DateTime.Now;
usr.LastActivityDate = DateTime.Now;
usr.IsEnabled = true;
usr.UserRoles.Add(userRole as Roles);
entities.User.AddObject(usr);
int result = entities.SaveChanges();
LblMsg.Text = result == 2 ? "User created succesfully." : "An error occured ,please try later.";
entities.Dispose();

Related

use isolation level snapshot entity framework 4

I'm try to using a TransactionScope with isolation level snapshot on Entity framework 4 in asp.net web proyect and sql server 2012 standard edition. I'm getting this error Transactions with IsolationLevel Snapshot cannot be promoted.
using (var scope = new TransactionScope(TransactionScopeOption.RequiresNew,
new TransactionOptions { IsolationLevel = IsolationLevel.Snapshot })) {
using (var db = new Datos.TestDBDataContext(System.Configuration
.ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString))
{
Datos.Contacto newUser = new Datos.Contacto
{
name = user.name,
lastName = user.lastName,
type = user.type,
userId = user.userId,
email = user.Email,
password = Password(),
jobCode = user.JobCode,
DateCreated = user.DateCreated,
cityCode = user.cityCode,
numberPass = user.numberPass,
place = user.place,
estate = false
};
db.Contacts.InsertOnSubmit(newUser);
db.SubmitChanges();
}
scope.Complete();
}
What I'm doing wrong ?
Please try as shown below.Set the IsolationLevel.Serializable.
Serializable : Volatile data can be read but not modified, and no new
data can be added during the transaction.
IsolationLevel Enumeration
var scope = new TransactionScope(TransactionScopeOption.RequiresNew,
new TransactionOptions {
IsolationLevel = IsolationLevel.Snapshot,
IsolationLevel = IsolationLevel.Serializable,
})

Failed to change password with UserManager.RemovePassword() and UserManager.AddPassword() in Asp.Net Identity

I use the following code to change a user's password:
UserManager<ApplicationUser> userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
var user = userManager.FindByName(currentUser.LoginName); // currentUser is the currently logged in user
IdentityResult result1 = userManager.RemovePassword(user.Id);
IdentityResult result2 = userManager.AddPassword(user.Id, txtPassword1.Text);
It works last year. But this year when I run it, it doesn't work (exactly the same code). When it runs to this statement:
IdentityResult result1 = userManager.RemovePassword(user.Id);
it gives the following exception:
{"Cannot insert the value NULL into column 'PasswordHash', table 'xxx.dbo.AspNetUsers'; column does not allow nulls. UPDATE fails.The statement has been terminated."}
I debugged into into, right before that statement,
user.PasswordHash = 'AAdcuoWRRXqfkB+vWpemPCkFNgWRGGe2tXyeJHy21S8qYYfAo9wJbfqtkog+lk2dZg=='
but after this statement, user.PasswordHash becomes null
I am really confused. What's the problem here?
If you want change user password use this code instead:
var validPass= await userManager.PasswordValidator.ValidateAsync(txtPassword1.Text);
if(validPass.Succeeded)
{
var user = userManager.FindByName(currentUser.LoginName);
user.PasswordHash = userManager.PasswordHasher.HashPassword(txtPassword1.Text);
var res= userManager.Update(user);
if(res.Succeeded)
{
// change password has been succeeded
}
}
If you want to change your user's password you can try two kinds of approach.
One approach can be using "RemovePassword" and "AddPassword" as below:
string pwd = txtpwd.Text.Trim();
var userStore = new UserStore<IdentityUser>();
var userManager = new UserManager<IdentityUser>(userStore);
string userName = UserName.Text;
var user = userManager.FindByName(userName);
if (user.PasswordHash != null)
{
userManager.RemovePassword(user.Id);
}
userManager.AddPassword(user.Id, pwd);
Another approach is using "ChangePassword" as below:
var userStore = new UserStore<IdentityUser>();
var userManager = new UserManager<IdentityUser>(userStore);
// var user = new IdentityUser() { UserName = UserName.Text };
if (UserName.Text != null && txtcurpwd != null && txtNewpwd != null)
{
string username = UserName.Text;
var user = userManager.FindByName(username);
IdentityResult result = userManager.ChangePassword(user.Id, txtcurpwd.Text, txtNewpwd.Text);
if (result.Succeeded)
lblErrorMsg.Text = "password changed successfully for the user : " + username;
else
lblErrorMsg.Text = result.Errors.FirstOrDefault();
}
else
lblErrorMsg.Text = "Details missing ";
}

Error SQL data reader

I created Intranet project which connect with AD to retrieve User's
data as Image , Department . I did my code and it works well but I had
the below error a lot of times .
string User = ConfigurationManager.AppSettings["User"];
string Password = ConfigurationManager.AppSettings["Password"];
var entry = new DirectoryEntry("LDAP://" + "xxxxx", User, Password);
DirectorySearcher searcher = new DirectorySearcher(entry);
searcher.SearchScope = SearchScope.Subtree;
string UserName = Page.User.Identity.Name;
searcher.Filter = string.Format(CultureInfo.InvariantCulture, "(sAMAccountName={0})", UserName.Split('\\')[1]);
SearchResult findUser = searcher.FindOne();
if (findUser != null)
{
DirectoryEntry user = findUser.GetDirectoryEntry();
//string loginuser = user.Properties["UserName"].Value.ToString();
LoggedUser = user.Properties["displayName"].Value.ToString();
Session.Add("LoggedUser", LoggedUser);
LoggedEmail = user.Properties["mail"].Value.ToString();
Session.Add("LoggedEmail", LoggedEmail);
string Mobile = user.Properties["Mobile"] != null && user.Properties["Mobile"].Value != null ? user.Properties["Mobile"].Value.ToString() : null;
string Login = user.Properties["sAMAccountName"].Value.ToString();
if (user.Properties["Department"].Value != null)
LoggedDepartement = user.Properties["Department"].Value.ToString();
_userDept = user.Properties["Department"].Value != null ? user.Properties["Department"].Value.ToString() : "";
ftier.AddLoggedUser(LoggedUser, LoggedDepartement, title, LoggedEmail, data, DateTime.Now, DateTime.Now, " nnnnn", true);
When I've done this in the past one of the problems was unusual characters in the properties of the user object caused this sort of error.
One approach would be to put error checking on each of the variables you're setting so the code can keep working, or export to a text file all the data and go through it using excel and look for unusual or strange control characters.
If the error always occurs at a certain person you could just look at the properties of that user and hope to find the issue that way.
Our issue was the use of Chinese simplified characters in some fields.
Hope this helps you track down your issue.
Dorje

Retrieving CRM 4 entities with custom fields in custom workflow activity C#

I'm trying to retrieve all phone calls related to opportunity, which statecode isn't equal 1. Tried QueryByAttribute, QueryExpression and RetrieveMultipleRequest, but still has no solution.
Here some code i wrote.
IContextService contextService = (IContextService)executionContext.GetService(typeof(IContextService));
IWorkflowContext context = contextService.Context;
ICrmService crmService = context.CreateCrmService(true);
if (crmService != null)
{
QueryByAttribute query = new Microsoft.Crm.Sdk.Query.QueryByAttribute();
query.ColumnSet = new Microsoft.Crm.Sdk.Query.AllColumns();
query.EntityName = EntityName.phonecall.ToString();
query.Attributes = new string[] { "regardingobjectid" };
query.Values = new string[] { context.PrimaryEntityId.ToString() };
RetrieveMultipleRequest retrieve = new RetrieveMultipleRequest();
retrieve.Query = query;
retrieve.ReturnDynamicEntities = true;
RetrieveMultipleResponse retrieved = (RetrieveMultipleResponse)crmService.Execute(retrieve);
}
return ActivityExecutionStatus.Closed;
}
And almost same for QueryExpression
QueryExpression phCallsQuery = new QueryExpression();
ColumnSet cols = new ColumnSet(new string[] { "activityid", "regardingobjectid" });
phCallsQuery.EntityName = EntityName.phonecall.ToString();
phCallsQuery.ColumnSet = cols;
phCallsQuery.Criteria = new FilterExpression();
phCallsQuery.Criteria.FilterOperator = LogicalOperator.And;
phCallsQuery.Criteria.AddCondition("statuscode", ConditionOperator.NotEqual, "1");
phCallsQuery.Criteria.AddCondition("regardingobjectid", ConditionOperator.Equal, context.PrimaryEntityId.ToString();
I always get something like Soap exception or "Server was unable to proceed the request" when debugging.
To get exception details try to use following code:
RetrieveMultipleResponse retrieved = null;
try
{
retrieved = (RetrieveMultipleResponse)crmService.Execute(retrieve);
}
catch(SoapException se)
{
throw new Exception(se.Detail.InnerXml);
}

Remove role and recovery the role in the table

for a mistake. I used a wrong command. I wanted to remove an user' role from the table aspnet_UsersInRoles.
I guess that the command might be
Roles.RemoveUserFromRole(userName, origin_role);
However I used a wrong command mistakenly.
Roles.DeleteRole(origin_role,false);
Originally the table has 4 roles. Now the RoleId in the table only has two,
61572264-4935-461d-9d8c-71f147f28c34
c09f25e6-fd6a-447b-8e0d-eba0cfc94e40
How can I find and recovery them?
Many many thanks.
Hate to say it, but you're hosed. The default ASP.Net providers don't include any sort of auditing or soft-delete. If you have a database backup, you can explore/restore from that.
Below you find the source code for the function you called.
It calls the dbo.aspnet_Roles_DeleteRole stored procedure.
I don't have access to an asp.net membership database at the moment, otherwise I would check for you.
You might want to check what the stored procedure does, but as ssyladin mentioned I doubt you will be able to recover anything (since you sent the throwOnPopulatedRole argument to false).
public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
{
SecUtility.CheckParameter(ref roleName, true, true, true, 256, "roleName");
try {
SqlConnectionHolder holder = null;
try {
holder = SqlConnectionHelper.GetConnection(_sqlConnectionString, true);
CheckSchemaVersion( holder.Connection );
SqlCommand cmd = new SqlCommand("dbo.aspnet_Roles_DeleteRole", holder.Connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandTimeout = CommandTimeout;
SqlParameter p = new SqlParameter("#ReturnValue", SqlDbType.Int);
p.Direction = ParameterDirection.ReturnValue;
cmd.Parameters.Add(p);
cmd.Parameters.Add(CreateInputParam("#ApplicationName", SqlDbType.NVarChar, ApplicationName));
cmd.Parameters.Add(CreateInputParam("#RoleName", SqlDbType.NVarChar, roleName));
cmd.Parameters.Add(CreateInputParam("#DeleteOnlyIfRoleIsEmpty", SqlDbType.Bit, throwOnPopulatedRole ? 1 : 0));
cmd.ExecuteNonQuery();
int returnValue = GetReturnValue(cmd);
if( returnValue == 2 )
{
throw new ProviderException(SR.GetString(SR.Role_is_not_empty));
}
return ( returnValue == 0 );
}
finally
{
if( holder != null )
{
holder.Close();
holder = null;
}
}
}
catch
{
throw;
}
}

Resources