I am using ASP.NET MVC 4 (.NET framework 4.5) with LINQ-to-SQL and SQL Server 2008 R2
This function returns always true if I run it through debug mode, but when I run it without debug, it returns false. I once got this error: http://i.imgur.com/HydhT.png
I tried googling this, some similiar problems came up but I checked them all:
UserProfiles table has a primary key
The datacontext is in sync with the database
I've tried putting ConflictMode.ContinueOnConflict as an argument in SubmitChanges()
I've tried to put above the facebookID in LINQ designer: UpdateCheck=UpdateCheck.Never
Nothing works. I have never experienced anything like this before. Does anyone have any idea?
Code:
facebookID field in SQL Server is varchar(50) NULL with default value NULL
public static bool changeFacebookIDByEmail(string email, string facebookID)
{
UserProfile profile = (from s in _dc.Users
join u in _dc.Memberships on s.UserId equals u.UserId
join i in _dc.UserProfiles on u.UserId equals i.userID
where u.Email == email
select i).SingleOrDefault();
profile.facebookID = facebookID;
ChangeSet cs = _dc.GetChangeSet();
_dc.SubmitChanges();
if (cs.Updates.Count <= 0)
return false;
else
return true;
}
It seems like you are executing a manual SQL statement:
UPDATE UserProfiles SET facebookID = NULL WHERE userID = '85A6D951-15C8-4892-B17D-BD93F3D0ACBB'
This will set the facebookID to null. Entity framework does not know this, though. It cannot interpret raw SQL. So it still thinks the facebookID is set to some value. When you later set it to that value in changeFacebookIDByEmail EF thinks nothing changed.
Sou you probably should not execute raw SQL strings. Use EF to change the value to null.
Change .singleordefault to .single I think your problem will be revealed pretty soon after that.
Basically anything found by your query with be in the datacontext. Anything new eg default will not.
You need to rewrite your routine to insert the new user in the case where it's not found.
EDIT
This is some code from a project I have been working on. I've cut out a bunch of stuff to demonstrate how it should work.
// add the identity as necessary
var found = dB.Identities.SingleOrDefault(q => q.UserName == userName);
if (found == null)
{
found = new Identity
{
Domain = domain,
Password = User.Identity.AuthenticationType,
Salt = "",
UserName = userName,
LastUpdatedDateTime = DateTime.Now
};
dB.Identities.InsertOnSubmit(found);
}
dB.SubmitChanges(null);
Related
I have an Oracle DB set up, and the Database has a bunch of Views.
The view GFL_BUYERS_ID_V has 2 columns of EMPLOYEE_ID and FULL_NAME. The database is already filled before I created the mvc project.
I Add the database successfully and added the a schema modelBuilder.HasDefaultSchema("examplename."); to my context because when I use SQL to retrieve data, I need to do:
SELECT * FROM "examplename".GFL_BUYERS_ID_V
for it to work, I assume that is what it's for. Apologies in advance I am new to .net, mvc and connecting databases.
The following crashes at the .Select and tells me that value cannot be null (I have no clue what is returning a null value, if I inspect values in context->GFL_BUYERS_ID_V when it breaks, in Local there are 0 values, and in Result View it contains all the appropriate one's, I assume this is relevant info but I don't know how to use it):
var model = new EmployeeModel();
using (var context = new OracleContext())
{
model.Buyers = context.GFL_BUYERS_ID_V.Select(s => new EmployeeModel.Buyer
{
BuyerId = s.EMPLOYEE_ID,
FullName = s.FULL_NAME
}).ToList();
}
return View(model);
this is my object:
public class EmployeeModel
{
public int EmployeeModelId { get; set; }
public List<Buyer> Buyers { get; set; }
public class Buyer
{
public int BuyerId { get; set; }
public string FullName { get; set; }
}
}
I know there is a connection to the database and I can query it via VB. I have fiddled enough with the connection string to know it is correct.
Edit: Scratch that I have no clue if my program is able to connect to the Database or not.
Screen shot of the error
If you would like me to provide more information, I will be happy to, really want to make this one work.
Edit 2: This seems like some sick joke clearly it shows a count: how
Is there an inner exception which is causing the ArgumentNullException?
You are definitely thinking along the right path, so I would break it down into manageable pieces:
1) confirm DB connectivity
2) confirm context is valid, which would most likely only be invalid if no DB connectivity
3) confirm GFL_BUYERS_ID_V is showing data
4) then do the projection to a different model
So the problem was in the Database server not the code. For some reason it used an old default schema variable that wasn't used for a long time.
This has been asked before, but none of the available answers seem to fit to my case.
In order to perform some validation, I have to reload from DB the same entity, which already bound to the model. The following causes the error. I'm almost losing my mind.
[HttpPost]
public ActionResult Edit(Tekes tekes, FormCollection fc)
{
...
Tekes myTekes = db.Tkasim.Find(tekes.TeksID);
<some validation here>
if (ModelState.IsValid)
{
db.Entry(tekes).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Details", new { id = tekes.TekesID });
}
}
Not sure why you have to grab the same entity from the data base. Anyway, the problem is that the Find statement adds the Tekes object to the context, subsequently the statement db.Entry(tekes).State = EntityState.Modified tries to do the same. It's not clear what the validation is all about, but I think you can solve this by replacing the Find by
var myTekes = db.Tkasim.AsNoTracking().Single(x => x.TeksId == tekes.TeksID);
AsNoTracking tells EF to fetch entities without adding them to the cache and the state manager.
Trying to use the WebSecurity and if my user loses, needs to resend, or otherwise changes their email, their does not seem to be any way to reset your confirmation token via the WebSecurity classes.
How do I reset the confirmation token for WebSecurity in Asp.NET MVC?
There doesn't seem to be support for this in the WebSecurity type. I was forced to query the database directly. Since I was using EF my code looked like the following:
public string GetConfirmationToken(string email)
{
using (var db = new DbContext())
{
var tsqlQuery = string.Format("SELECT [ConfirmationToken] FROM [webpages_Membership] WHERE [UserId] IN (SELECT [UserId] FROM [UserProfile] WHERE [Email] LIKE '{0}')", email);
return db.Database.SqlQuery<string>(tsqlQuery).First();
}
}
I am working on an application which has a registration form and I have to display to the user whether the username exists or not.
I am using asp.net mvc3 and planned to use AJAX to achieve this.
I have a form
<tr>
<td>User Name*</td>
<td><input id="UserName" name="UserName" type="text" onblur="check(this.value);"/></td>
<td id= "UName"></td>
</tr>
which calls a .js file that has the folling contents
function check(User) {
...
var url = "/UserNameCheck/Index";
url += "?User=" + User;
xmlHttp.onreadystatechange = state_Change;
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
}
function state_Change() {
if (xmlhttp.readyState == 4) {// 4 = "Response loaded"
if (xmlhttp.status == 200) {// 200 = Response Error Free
document.getElementById("UName").innerHTML = xmlHttp.responseText
}
else {
alert("Problem retrieving XML data");
}
}
}
I alerted the username and I am getting the correct value that i had entered. Now, the URL is /UserNameCheck/Index where UserNameCheck is a controller and Index is a method in that.
The controller has this code.
public ActionResult Index(string User)
{
string UserName;
try
{
Response.Cache.SetCacheability(HttpCacheability.NoCache);
UserName = Request.QueryString["User"];
ConnectionPackage.ConnectionClass cc = new ConnectionPackage.ConnectionClass();
conn = cc.con;
string sql = "Select UserName FROM UserDetails where UserName = '" + UserName + "'";
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.CommandType = CommandType.Text;
object p = cmd.ExecuteScalar();
cmd.ExecuteNonQuery();
string u = (string)p;
if (u.Length==0 || u.Equals("NULL") || u.Equals("null")||u.Equals("Null"))
{
return View();
}
return null;
}
catch (Exception ex){
}
and the view has
String buffer = " <table><tr><td id = 'UName' >" This user name already exists. Please select some other unser name.
buffer = buffer + "</td></tr></table>";
response.getWriter().println(buffer);
I also tried writing
Response.Clear();
Response.Write("UserName already exists. Please select another UserName");
Response.End();
instead of returning View.
But in both the cases, I didn't get any message that the username exists even though I typed a user name that was already present in the database.
The connection string work for inserting into the database, so I dont think there is a problem with that. Is there a problem with the URL that I have mentioned in the js file? Or is my entire approach wrong?
I am basically from java background so dont know much about asp.net. Please do help.
Thank you very much in advance.
I followed what was given in MSDN article How to: Implement Remote Validation in ASP.NET MVC
jQuery in Action is the most popular jQuery book
You're doing alright but you could make this a whole lot easier on yourself. If you are usinng MVC3 with Razor, your app already has jQuery installed.
Use the $.ajax() method to perform the calls to your controller action that checks names...
Bind the $.ajax() call "unobtrusively" which means instead of on your HTML control, bind the event to your control from the jquery/javascript.
Second, if you want a little fancy performance, you can bind it via the live() jquery function or keyup event, so that as you are typing the ajax call is made and you find out realtime.
Ultimately you will end up with a lot less javascript, and your JS stuff will be cleanly separated from your markup.
As far as your controller action is going, it looks fine for playing around and learning, but you'd want to think about either (a) putting your SQL statement as a stored procedure on the db server and calling that, or (b) writing a repository pattern class and then using LINQ to do your query work after the DB fetch.
Another possibility would be to use Entity Framework 4.1 via NuGet to eliminate both needs. It can have a bit of a learning curve, but there's lots of good stuff out there and your example would be fairly simple to get started with.
Let me know if you have any specific concerns with your code and I can provide a more detailed answer.
I'm new to MVC and its going well but struggling a bit with the back to front SQL etc
select * from aspnet_Users
where Active = 1 and UserId in (select UserId from aspnet_UsersInRoles,aspnet_Roles where aspnet_Roles.RoleId = aspnet_UsersInRoles.RoleId and aspnet_Roles.RoleName = 'Auth Level 1')
Tables and fields are:
aspnet_Users (UserId int, Active bit, eMail varchar)
aspnet_UsersInRoles (UserId, RoleId)
aspnet_Roles (RoleId int, RoleName varchar)
My attempt - but incomplete looks like this so far:
LmsDataContext db = new LmsDataContext();
var AuthUsers = from aspnet_User in db.aspnet_Users
join userinroles in db.aspnet_UsersInRoles on aspnet_User.UserId equals userinroles.UserId
where aspnet_User.Active
select aspnet_User;
Many thanks in advance
Assuming that you have the associations defined in the database (or the designer), you should be able to access via properties the related entities without resorting to explicit joins. The following example is untested, but should put you on the right track. The basic idea is to find if there are any associations where the associated role has the correct name and choose the user if any are found.
var users = db.aspnet_Users
.Where( u => u.Active )
.Any( u => u.aspnet_UsersInRoles
.Any( r => r.aspnet_Roles.RoleName == "Auth Level 1" ) );
Thanks tvanfossen for the prompt reply, I tried to implement your way but could not get it right. I think your approach is neater bu tI got the following to work :
// Loop through all the Users on the System who are in Auth Level 1 Role and Email them
LmsDataContext db = new LmsDataContext();
var AuthUsers = from aspnet_User in db.aspnet_Users
join userinroles in db.aspnet_UsersInRoles on aspnet_User.UserId equals userinroles.UserId
where aspnet_User.Active
&& userinroles.aspnet_Role.RoleName == "Auth Level 1"
select aspnet_User;
Cheers
J