Convert var type to GUID type - asp.net

I have a var and want to change it to System.GUID .What should I do?
var requstid = Session ["y"];
want to convert type var to GUID.

If Session contains Guid, then just cast to it:
var requstid = Session ["y"] != null ? (Guid)Session ["y"] : default(Guid);

var requestId = Guid.Parse(Session["y"]);
or
var requestId = new Guid(Session["y"]);

Related

Can this query be changed to add an or?

I'm not sure how to change this query in google app maker language
var query = app.models.folders.newQuery();
query.filters.requestId._equals = request;
query.filters.filecount._equals = null;
var total = 0;
var recx = query.run();
So right now it is the equivalent of
select * from folders
where requestID = request
and filecount = null
But I would like to know if there is a way to change it to the equivalent of
select * from folders
where requestID = request
and (filecount = null or filecount < 0)
Maybe by using query.where?
You could try by just adding another filter to your query:
var query = app.models.folders.newQuery();
query.filters.requestId._equals = request;
query.filters.filecount._equals = null;
query.filters.filecount._lessThan = 0;
var total = 0;
var recx = query.run();

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

LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression

LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression.
public ActionResult PopulateFromDB(string sidx, string sord, int page, int rows)
{
var context = new NerdDinnerEntities();
var jsonData = new
{
total = 1,
page = page,
sord =sord,
records = context.Authors.Count(),
rows = (from n in context.Authors
select new
{ AuthorId = n.AuthorId ,
cell = new string[] { n.AuthorId.ToString(), n.Name.ToString(), n.Location.ToString() }
}).ToList()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
I am writting ToList or Toarray is it not working the error comes :
public ActionResult PopulateFromDB(string sidx, string sord, int page, int rows)
{
var context = new NerdDinnerEntities();
var jsonData = new
{
total = 1,
page = page,
sord =sord,
records = context.Authors.Count(),
rows = (from n in context.Authors
select new
{ AuthorId = n.AuthorId ,
cell = new string[] { n.AuthorId.ToString(), n.Name.ToString(), n.Location.ToString() }
}).ToList()
};
return Json(jsonData,JsonRequestBehavior.AllowGet);
}
From your code I assume your adding a custom property cell for display/storage purposes on the client-side. I would avoid this as your essentially coupling your API call to one particular client. I would suggest you simply return the data required & deal with it at the client-side specifically e.g.
Server
...
select new
{
Id = n.AuthorId,
Name = n.Name,
Location = n.Location
}).ToList();
...
Client
var response = ...
foreach (var author in response)
{
var cell = new string[] { author.Id.ToString(), author.Name, author.Location };
// do something with cell
}
You should try SqlFunctions.StringConvert to convert this, There is no overload for int so you should cast your number to a double or a decimal.
public ActionResult PopulateFromDB(string sidx, string sord, int page, int rows)
{
var context = new NerdDinnerEntities();
var jsonData = new
{
total = 1,
page = page,
sord =sord,
records = context.Authors.Count(),
rows = (from n in context.Authors
select new
{ AuthorId = n.AuthorId ,
cell = new string[] { SqlFunctions.StringConvert((double)n.AuthorId), n.Name, n.Location }
}).ToList()
};
return Json(jsonData,JsonRequestBehavior.AllowGet);
}
You are not using LinqToSql Classes, if you were using that your code should work, but as you mention that you are using LinqToEntity then You should use SqlFunctions.StringConvert to convert to string.

Insert into bridge table entity framework

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();

problem in getting value of the object attribute in flex

i have an xml which contains 'interface' sub tag, iam converting xml to object using SampleXmlDecoder. compiler did not allow me to access the value of the 'inteface' attrible of the resultobject.
var xml:XML = event.result as XML;
var xmlDoc : XMLDocument = new XMLDocument(xml.toString());
var decoder : SimpleXMLDecoder = new SimpleXMLDecoder(true)
var resultObj : Object = decoder.decodeXML(xmlDoc);
var o:Object = new Object();
o.someprop = resultObj.maintag.item.interface;
its treating interface as keyword.
can anyone tell me the solution for this. Thanks in advance
o.someprop = resultObj.maintag.item["interface"];

Resources