ASP.net Entity Framework Check if exists in database - sql

I have VS2015, entity framework 6. I have a database with one table (Logins)
FirstName, lastName, Birthdate, email, password
I also have a textbox(s), button
tbEmail tbpass and btnLogin
How do I check if the users email in the textbox matches one in the database?
So far I have:
protected void btnLogin_Click(object sender, EventArgs e)
{
Logins Log = new Logins();
using (LoginDataEntities lg = new LoginDataEntities())
{
string #email = tbUsernameL.Text;
string #password = tbPassL.Text;
var logged = from L in lg.Logins
where L.Username == #email
&& L.Pass == #password
select L.Username;
if (logged != null)
{
lblSuccess.Visible = true;
}
else
{
lblFail.Visible = true;
}
}
}
However, its not working and always enables the success label. How do I fix this?

Try it once with the following snippet:
using (LoginDataEntities lg = new LoginDataEntities())
{
string #email = tbUsernameL.Text;
string #password = tbPassL.Text;
var logged = lg.Logins
.SingleOrDefault(l=> l.Username == #email && l.Pass == #password);
if (logged != null) // update
{
lblSuccess.Visible = true;
}
else
{
lblFail.Visible = true;
}
}
Alternatively, can you also look at the following example again:
http://www.c-sharpcorner.com/uploadfile/b19d5a/custom-user-login-and-registration-page-in-Asp-Net-mvc3-with-razor-and-entity-framework/
Or you refactorisiers the VS template with Individual User Accounts

Related

Best practice to check duplicate string data before insert data using Entity Framework Core in C#

I need an advice for my code. What I want to do is insert a row into a table using Entity Framework Core in ASP.NET Core.
Before inserting new data, I want to check if email and phone number is already used or not.
I want to return specifically, example if return = x, email used. If return = y, phone used.
Here's my code
public int Insert(Employee employee)
{
var checkEmail = context.Employees.Single(e => e.Email == employee.Email);
if (checkEmail != null)
{
var checkPhone = context.Employees.Single(e => e.Phone == employee.Phone);
if (checkPhone != null)
{
context.Employees.Add(employee);
context.SaveChanges();
return 1;
}
return 2;
}
return 3;
}
I'm not sure with my code, is there any advice for the best practice in my case?
I just don't like these "magic numbers" that indicate the result of your checks.... how are you or how is anyone else going to know what 1 or 2 means, 6 months down the road from now??
I would suggest to either at least create a constants class that make it's more obvious what these numbers mean:
public class CheckConstants
{
public const int Successful = 1;
public const int PhoneExists = 2;
public const int EmailExists = 3;
}
and then use these constants in your code:
public int Insert(Employee employee)
{
var checkEmail = context.Employees.Single(e => e.Email == employee.Email);
if (checkEmail != null)
{
var checkPhone = context.Employees.Single(e => e.Phone == employee.Phone);
if (checkPhone != null)
{
context.Employees.Add(employee);
context.SaveChanges();
return CheckConstants.Successful;
}
return CheckConstants.PhoneExists;
}
return CheckConstants.EmailExists;
}
and also in any code that calls this method and need to know about the return status code.
Alternatively, you could also change this to an enum (instead of an int):
public enum CheckConstants
{
Successful, PhoneExists, EmailExists
}
and then just return this enum - instead of an int - from your method:
public CheckConstants Insert(Employee employee)
{
var checkEmail = context.Employees.Single(e => e.Email == employee.Email);
if (checkEmail != null)
{
var checkPhone = context.Employees.Single(e => e.Phone == employee.Phone);
if (checkPhone != null)
{
context.Employees.Add(employee);
context.SaveChanges();
return CheckConstants.Successful;
}
return CheckConstants.PhoneExists;
}
return CheckConstants.EmailExists;
}
merge two database check to one Query
use SingleOrDefault instance of Single
public int Insert(Employee employee)
{
var checkEmail = context.Employees.Select (e=>new {e.Email , e.Phone }).SingleOrDefault(e => e.Email == employee.Email || e.Phone == employee.Phone);
if (checkEmail == null)
{
context.Employees.Add(employee);
context.SaveChanges();
return 1;
}
else if (checkEmail.Email == employee.Email)
return 3;
else
return 2;
}

How to create a apex test class for my apex class

It is my first apex class and i don't really know how to implement a proper test class.
My goal is to achieve test coverage of 75%.
I updated based on the comments but i managed to achieve only 70 %. I don't have other idea how to improve this more.
Here is what i did :
Apex class:
public with sharing class AccountController {
#AuraEnabled
public static List<Account> findAll() {
User userDetails =[SELECT Id, Name, Email, Profile.Name, UserRole.Name FROM User
where Id=:userinfo.getUserId() ];
// Theme4t is theme that is used by mobille app for android or iphone
if(((userDetails.UserRole.Name).equals('yon')|| (userDetails.UserRole.Name).equals('bon')|| (userDetails.UserRole.Name).contains('non')
|| (userDetails.UserRole.Name).contains('go')) && UserInfo.getUiTheme() != 'Theme4t'){
return [SELECT id, name, AccountStatus__c, ShippingLatitude, ShippingLongitude, ShippingCity
FROM Account
WHERE ShippingLatitude != NULL AND ShippingLongitude != NULL
LIMIT:22000];
}else {
return [SELECT id, name, AccountStatus__c, ShippingLatitude, ShippingLongitude, ShippingCity
FROM Account
WHERE OwnerId =: UserInfo.getUserId() AND ShippingLatitude != NULL AND ShippingLongitude != NULL
LIMIT:5000];
}
}
Apex test class:
#isTest
public class AccountControllerTest
{
static testMethod void testMethod1()
{
Account acc = new Account();
acc.Name='Test';
insert acc;
User userDetails =[SELECT Id, Name, Email, Profile.Name, UserRole.Name FROM User
where Id=:userinfo.getUserId() ];
List<Account> lstAcc = AccountController.findAll();
UserRole ur =new UserRole();
userDetails.UserRoleId=[select Id from UserRole where Name='yon'].Id;
System.runAs(userDetails){
List<Account> lstAcc1 = AccountController.findAll();
}
userDetails.UserRoleId=[select Id from UserRole where Name='bon'].Id;
System.runAs(userDetails){
List<Account> lstAcc2 = AccountController.findAll();
}
userDetails.UserRoleId=[select Id from UserRole where Name='non'].Id;
System.runAs(userDetails){
List<Account> lstAcc3 = AccountController.findAll();
}
userDetails.UserRoleId=[select Id from UserRole where Name='go'].Id;
System.runAs(userDetails){
List<Account> lstAcc4 = AccountController.findAll();
}
}
Please complete the below trailhead to learn the unit test in Salesforce.
https://trailhead.salesforce.com/en/content/learn/modules/apex_testing/apex_testing_intro
And also as you are trying to create a user after account insertion it will throw Mixed DML error. you need to use system.runAs() method. follow the below URL for using the method.
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_testing_tools_runas.htm
Let me know if still, you need any help on this.
Here is the code for your class and test class. Please follow the best practices from http://blog.shivanathd.com/2013/11/Best-Practices-Test-Class-in-Salesforce.html
This time I am providing the code to you to understand how to create a test class, but next time onwards please follow the steps and documents I have shared.
public with sharing class AccountController {
//using a test visible variable for setting the ui theme check.
#TestVisible static Boolean isTheme4t = UserInfo.getUiThemeDisplayed() == 'Theme4t';
#AuraEnabled
public static List<Account> findAll() {
User userDetails =[SELECT Id, Name, Email, Profile.Name, UserRole.Name FROM User where Id=:userinfo.getUserId()];
// Theme4t is theme that is used by mobille app for android or iphone
if(((userDetails.UserRole.Name).equals('yon')|| (userDetails.UserRole.Name).equals('bon')|| (userDetails.UserRole.Name).contains('non') || (userDetails.UserRole.Name).contains('go')) && !isTheme4t){
return [SELECT id, name, AccountStatus__c, ShippingLatitude, ShippingLongitude, ShippingCity FROM Account WHERE ShippingLatitude != NULL AND ShippingLongitude != NULL LIMIT 22000];
}else {
return [SELECT id, name, AccountStatus__c, ShippingLatitude, ShippingLongitude, ShippingCity FROM Account WHERE OwnerId =: UserInfo.getUserId() AND ShippingLatitude != NULL AND ShippingLongitude != NULL LIMIT 5000];
}
}
}
#isTest
public class AccountControllerTest
{
//Use setup data method to create data and query it in testmethod
#testSetup static void setup() {
UserRole r = new UserRole(DeveloperName = 'yon', Name = 'yon');
insert r;
User u = new User(
ProfileId = [SELECT Id FROM Profile WHERE Name = 'System Administrator'].Id,
LastName = 'last',
Email = 'puser000#amamama.com',
Username = 'puser000#amamama.com' + System.currentTimeMillis(),
CompanyName = 'TEST',
Title = 'title',
Alias = 'alias',
TimeZoneSidKey = 'America/Los_Angeles',
EmailEncodingKey = 'UTF-8',
LanguageLocaleKey = 'en_US',
LocaleSidKey = 'en_US',
UserRoleId = r.Id
);
insert u;
System.runAs(u){
Account acc = new Account();
acc.Name = 'Test Account';
acc.ShippingLatitude = 75.46;
acc.ShippingLongitude = 45.46;
acc.AccountStatus__c = 'test';
insert acc;
}
}
static testMethod void testMethod1(){
user u = [select Id from User where email = 'puser000#amamama.com' limit 1];
system.runAs(u){
Test.startTest();
List<Account> acc = [select Id,AccountStatus__c,ShippingLatitude,ShippingLongitude from Account where Name = 'Test Account'];
List<Account> lstAcc4 = AccountController.findAll();
system.assert(lstAcc4.size()>0);
Test.stopTest();
}
}
static testMethod void testMethod2(){
user u = [select Id from User where email = 'puser000#amamama.com' limit 1];
system.runAs(u){
AccountController.isTheme4t = true;
Test.startTest();
List<Account> acc = [select Id,AccountStatus__c,ShippingLatitude,ShippingLongitude from Account where Name = 'Test Account'];
List<Account> lstAcc4 = AccountController.findAll();
system.assert(lstAcc4.size()>0);
Test.stopTest();
}
}
}

Convert EntityFramework to Raw SQL Queries in MVC

I am trying to make a crud calendar in my .net, my question is, How do make the below entity framework codes to SQL queries?
[HttpPost]
public JsonResult SaveEvent(Event e)
{
var status = false;
using (MyDatabaseEntities dc = new MyDatabaseEntities())
{
if (e.EventID > 0)
{
//Update the event
var v = dc.Events.Where(a => a.EventID == e.EventID).FirstOrDefault();
if (v != null)
{
v.Subject = e.Subject;
v.Start = e.Start;
v.End = e.End;
v.Description = e.Description;
v.IsFullDay = e.IsFullDay;
v.ThemeColor = e.ThemeColor;
}
}
else
{
dc.Events.Add(e);
}
dc.SaveChanges();
status = true;
}
return new JsonResult { Data = new { status = status } };
}
http://www.dotnetawesome.com/2017/07/curd-operation-on-fullcalendar-in-aspnet-mvc.html
Thanks guys
You can run raw query in entity framework with dc.Database.ExecuteSqlCommand() command like below:
var status = false;
using (MyDatabaseEntities dc = new MyDatabaseEntities())
{
if (e.EventID > 0)
{
dc.Database.ExecuteSqlCommand(&#"
UPDATE Events
SET Subject = {e.Subject},
Start = {e.Start},
End = {End},
Description = {Description},
IsFullDay = {IsFullDay},
ThemeColor = {ThemeColor},
WHERE EventID = {e.EventID}
IF ##ROWCOUNT = 0
INSERT INTO Events (EventID, Subject, Start, End, Description, IsFullDay, ThemeColor)
VALUES ({e.EventID}, {e.Subject}, ...)
");
status = true;
}
return new JsonResult { Data = new { status = status }
};

ASP.net MVC 4 site gets slow on first request to database

I have an ASP.net MVC 4 site and it gets slow on the first request. I tried breakpoint while running the application. During the login process it almost stays for a minute at my first database query:
var InstnCode = form["code"].ToString();
var ComAccount = Context.Companies.Where(x => x.CompanyCode == InstnCode);
After that everything runs smoothly.
Why is it so how can I rectify this process. Due to this problem sometimes I get a Server Timeout error.
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(UserProfile model, string returnUrl, FormCollection form)
{
var InstnCode = form["code"].ToString();
var ComAccount = Context.Companies.Where(x => x.CompanyCode == InstnCode);
if (ComAccount.Any())
{
var modelvalue =
(from d in Context.UserProfiles
where d.UserName == model.UserName && d.Password == model.Password && d.Company.CompanyCode == InstnCode
select d).FirstOrDefault();
if (modelvalue != null)
{
string code = null;
Session["UName"] = modelvalue.UserName;
Session["Theme"] = modelvalue.Theme;
Session["InstnName"] = modelvalue.Company.CompanyName;
Session["Role"] = modelvalue.Role.RoleName;
Session["StartUp"] = modelvalue.StartUp;
var permission =
Context.AccountPermissions.Where(x => x.RoleId == modelvalue.RoleId)
.AsQueryable()
.FirstOrDefault();
if (permission != null)
{
SetSessions(permission, "yes");
}
else
{
SetSessions(permission, "no");
}
if (modelvalue.CompanyId != 0 && modelvalue.StaffId == null && modelvalue.StudentProfileId == null)
{
Session["ComID"] = modelvalue.CompanyId;
code = modelvalue.Company.CompanyCode;
}
else if (modelvalue.CompanyId != 0 && modelvalue.StudentProfileId != null)
{
var student =
(from d in Context.StudentProfiles
where d.StudentProfileId == modelvalue.StudentProfileId
select d).FirstOrDefault();
code = student.Company.CompanyCode;
Session["ComID"] = student.CompanyId;
}
else if (modelvalue.CompanyId != 0 && modelvalue.StaffId != null)
{
var staff =
(from d in Context.Staff where d.StaffId == modelvalue.StaffId select d).FirstOrDefault();
code = staff.Company.CompanyCode;
Session["ComID"] = staff.CompanyId;
Session["StaffID"] = staff.StaffId;
}
return RedirectToLocal(returnUrl);
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect");
return View(model);
}
}
ModelState.AddModelError("", "The institution code provided is incorrect");
return View(model);
}
This is my login function. I'm using
#using (Html.BeginForm("Login", "Account", FormMethod.Post, new { enctype = "multipart/form-data" })) for my login form.
Any help will be greatly appreciated.
Thanks in advance

the process cannot access the file 'xxx.xml' because it is being used by another process

I googled a lot, but i dint get any solution for problem.
Iam trying to add a node in to a xxx.xml file, but its throwing an error
"the process cannot access the file 'xxx.xml' because it is being used by another process", below is my class
public class Registration
{
List Users;
List NewUsers;
string Userpath = string.Empty;
string NewUserpath = string.Empty;
string strUsername = string.Empty;
public bool FINDUSERNAME(string firstname, string lastname, string emailaddress, string country, string purchasedate, string username, string password)
{
//Put code to get the offers from database to Offers variable
if (ReadXML(firstname, lastname, emailaddress, country, purchasedate, username, password))
return true;
else
return false;
}
//bool ReadXML(XmlDocument xmlfile2)
bool ReadXML(string firstname, string lastname, string emailaddress, string country, string purchasedate, string username, string password)
{
try
{
XmlDocument receivedxml = new XmlDocument();
Userpath = HttpContext.Current.Server.MapPath("/SampleData/Registration.xml");
NewUserpath = HttpContext.Current.Server.MapPath("/SampleData/NewRegistration.xml");
XmlReaderSettings xrs = new XmlReaderSettings();
xrs.DtdProcessing = DtdProcessing.Ignore;
XmlReader xr = XmlReader.Create(Userpath, xrs);
if (xr != null)
{
//Setting the Root element
XmlRootAttribute xRoot = new XmlRootAttribute();
xRoot.ElementName = "Registration";
xRoot.IsNullable = true;
XmlSerializer deserializer = new XmlSerializer(typeof(Registration), xRoot);
Registration UserDetails = (Registration)deserializer.Deserialize(xr);
Users = UserDetails.Users;
foreach (var varuser in Users)
{
if (username == varuser.Username)
{
strUsername = varuser.Username;
return true;
}
}
if (strUsername == "")
{
//here iam trying to add a node to the xml
using (StreamWriter sw = new StreamWriter(File.Create(Userpath)))
{
sw.Write("<User><Firstname>"
+ firstname + "</Firstname><Lastname>"
+ lastname + "</Lastname><Country>"
+ country + "</Country><Purchasedate>"
+ purchasedate + "</Purchasedate><Emailaddress>"
+ emailaddress + "</Emailaddress><Username>"
+ username + "</Username><Password>"
+ password + "</Password></User>");
}
return false;
}
}
return false;
}
catch (Exception)
{
return false;
}
}
}
Thanks in Advance...
It looks like you are never closing your reader, you need to call xr.Close() at some point. Or as Johan suggested, wrap it in a using statement:
using (XmlReader xr = XmlReader.Create(Userpath, xrs))
{
//Setting the Root element
XmlRootAttribute xRoot = new XmlRootAttribute();
xRoot.ElementName = "Registration";
xRoot.IsNullable = true;
XmlSerializer deserializer = new XmlSerializer(typeof(Registration), xRoot);
Registration UserDetails = (Registration)deserializer.Deserialize(xr);
Users = UserDetails.Users;
foreach (var varuser in Users)
{
if (username == varuser.Username)
{
strUsername = varuser.Username;
return true;
}
}
if (strUsername == "")
{
//here iam trying to add a node to the xml
using (StreamWriter sw = new StreamWriter(File.Create(Userpath)))
{
sw.Write("<User><Firstname>"
+ firstname + "</Firstname><Lastname>"
+ lastname + "</Lastname><Country>"
+ country + "</Country><Purchasedate>"
+ purchasedate + "</Purchasedate><Emailaddress>"
+ emailaddress + "</Emailaddress><Username>"
+ username + "</Username><Password>"
+ password + "</Password></User>");
}
return false;
}
}
Also another note: I notice your method is named ReadXML, yet you are also writing XML in this method. This can be confusing, are you reading or writing? Part of your issue may also be that you are opening the file for reading, and then creating the file for writing?? I have not dealt with the C# Xml libs before but something doesn't seem right here. You might consider breaking this down more.