How to find true value in database? - c#

I want to be able to print a receipt when something is true in the database. For example, clawcutting, it should print the line "Here are your receipt" + claw. But when I have ClawCutting true in the database, it still prints "Error". I do not really understand why it can not find it true in database?
public void DeleteFromService()
{
using (var db = new ApplicationDbContext())
{
double claw = 2.99;
double hair = 3.99;
double washing = 4.99;
Console.WriteLine("Add your booking number on your service");
Services s = new Services();
s.Id = Convert.ToInt32(Console.ReadLine());
if(s.ClawCutting == true)
{
Console.WriteLine("Here are your receipt" + claw);
}
else if(s.HairCut == true)
{
Console.WriteLine("Here are your receipt" + hair);
}
else if (s.Washing == true)
{
Console.WriteLine("Here are your receipt" + washing);
}
else
{
Console.WriteLine("Error");
}
db.Services.Remove(s);
db.SaveChanges();
}
}

Your code never loads anything from the database. Service is a new object and all its properties will have default values. If you want to load a specific item use DbSet.Find where id the primary key value of the item you want to loadeg
var id=Convert.ToInt32(Console.ReadLine());
var s=db.Services.Find(id);
if(s == null)
{
Console.WriteLine($"No service with {id} was found");
return;
}
These two methods will delete the Service from the database, so make sure you use them only if that's what you really want :
db.Services.Remove(s);
db.SaveChanges();

Related

Search data in C# from Database SQL Server

I want to ask you regarding for the searching in C# and why there is a Not Found statement if already found the answer or the data itself.
Here is the code:
Console.WriteLine("Enter Plate Number: ");
string plateNumber1 = Console.ReadLine();
var searchPlateNumberDAL = new ParkingSystemDAL(_iconfiguration);
var listSlotParking = searchPlateNumberDAL.GetList();
listSlotParking.ForEach(item =>
{
bool searchItem = item.plateNumber == plateNumber1;
if (searchItem == true)
{
Console.WriteLine(item.parkingId);
}
else
{
Console.WriteLine("Not Found");
}
});
output
I think there some garbage value is present.
So, code will be
if(item.plateNumber.ToString().Trim().ToUpper() == plateNumber1.ToString().Trim().ToUpper())
{
Console.WriteLine(item.parkingId);
}
you can also use Linq Where expression instead of ForEach
if( listSlotParking.Where(x =>x.planteNumberplateNumber.ToString().Trim().ToUpper() == plateNumber1.ToString().Trim().ToUpper()).ToList().Count()>0)
{
Console.WriteLine(item.parkingId);
}
Try
item.plateNumber.Trim() == plateNumber1.Trim()

Why db.savechanges is storing the old records also?

I have very weird problem
My code it works fine if I login and use then it save the preferences etc.
But problem starts when I login, do some selections, and logout and login as another user, then upon saving it also remembers the seelctions I had done wfor the other user, the last one and save that also.
How to prevent this?
private ApplicationDbContext db = new ApplicationDbContext();
...
public IHttpActionResult Add(UserPreferencesDto model)
{
model.UserId = User.Identity.GetUserId();
var userPreferences = db.UserPreferences.Where(u =>
u.UserId == model.UserId &&
u.Key == model.Key.Trim())
.FirstOrDefault();
List<int> StatesCollection = new List<int>();
var param = model.Value.Trim();
string[] paramSplitted = param.Split(',');
if (userPreferences != null)
{
if (string.IsNullOrEmpty(userPreferences.Value) == false)
{
var trimmedPreferenceValue = userPreferences.Value.Trim('[', ']');
if (string.IsNullOrEmpty(trimmedPreferenceValue) == false)
{
StatesCollection = trimmedPreferenceValue.Split(',')
.Select(s => Convert.ToInt32(s)).ToList<int>();
}
if (model.IsStateSelected == false && paramSplitted.Count() == 1
&& StatesCollection.Contains(int.Parse(param.Trim())))
{
StatesCollection = StatesCollection.Where(sa => sa != int.Parse(param)).ToList<int>();
userPreferences.Value = StatesCollection.Count > 0 ? JsonConvert.SerializeObject(StatesCollection) : "";
}
else if (model.IsStateSelected && paramSplitted.Count() == 1
&& !StatesCollection.Contains(int.Parse(param)))
{
StatesCollection.Add(int.Parse(param));
userPreferences.Value = JsonConvert.SerializeObject(StatesCollection);
}
}
else
{
StatesCollection.Add(int.Parse(param));
userPreferences.Value = JsonConvert.SerializeObject(StatesCollection);
}
}
else
{
if (model.IsStateSelected == true)
{
//string[] splittedStates = model.Value.Split(',');
int[] secRolesIds = Array.ConvertAll(paramSplitted, int.Parse);
model.Value = JsonConvert.SerializeObject(secRolesIds);
db.UserPreferences.Add(Mapper.Map<UserPreferences>(model));
}
}
db.SaveChanges();
return Ok();
}
Even if the preferences exist it goes to the last else.
SaveChanges() in entity framework saves ALL tracked changes.
You would have to explicitly discard changes or use untracked entities, only adding them when you wish to save.
https://learn.microsoft.com/en-us/ef/core/querying/tracking
I think you should make the userPreferences variable null before giving a value to it, this way you could prevent it to have a value from the last execution because you would ensure it became null because you forced it to be. By doing so if there is no result in the database when you try to assign a value to it it will remain null for sure and so it will enter to the if with the if (userPreferences != null) and don't go to the else.

Error 0x87DD0005 when implementing Xbox Live services

I just got done adding Xbox support code to my project, and have run into at least two issues.
The first involves save data sync which is working just fine, however when the game reads the user's login data on Windows it behaves as if login has not been completed - no gamertag is displayed in the corner, and the login provider throws error 0x87DD0005 regardless of the number of retry attempts.
Execution of the code is just fine on Xbox - only Windows seems to be affected by this. I'm also targeting the creator's showcase initially (or at least until I can get to where I'm ready for another run at ID#Xbox) so achievements and the like aren't a concern right now.
The following is the code I'm using (and in no particular order):
public void doStartup()
{
getData(-1);
for (int i = 0; i <= 5; i++)
{
getData(i);
}
ContentViewport.Source = new Uri("ms-appx-web:///logo.html");
}
public async void getData(int savefileId)
{
var users = await Windows.System.User.FindAllAsync();
string c_saveBlobName = "Advent";
//string c_saveContainerDisplayName = "GameSave";
string c_saveContainerName = "file" + savefileId;
if (savefileId == -1) c_saveContainerName = "config";
if (savefileId == 0) c_saveContainerName = "global";
GameSaveProvider gameSaveProvider;
GameSaveProviderGetResult gameSaveTask = await GameSaveProvider.GetForUserAsync(users[0], "00000000-0000-0000-0000-00006d0be05f");
//Parameters
//Windows.System.User user
//string SCID
if (gameSaveTask.Status == GameSaveErrorStatus.Ok)
{
gameSaveProvider = gameSaveTask.Value;
}
else
{
return;
//throw new Exception("Game Save Provider Initialization failed");;
}
//Now you have a GameSaveProvider
//Next you need to call CreateContainer to get a GameSaveContainer
GameSaveContainer gameSaveContainer = gameSaveProvider.CreateContainer(c_saveContainerName);
//Parameter
//string name (name of the GameSaveContainer Created)
//form an array of strings containing the blob names you would like to read.
string[] blobsToRead = new string[] { c_saveBlobName };
// GetAsync allocates a new Dictionary to hold the retrieved data. You can also use ReadAsync
// to provide your own preallocated Dictionary.
GameSaveBlobGetResult result = await gameSaveContainer.GetAsync(blobsToRead);
string loadedData = "";
//Check status to make sure data was read from the container
if (result.Status == GameSaveErrorStatus.Ok)
{
//prepare a buffer to receive blob
IBuffer loadedBuffer;
//retrieve the named blob from the GetAsync result, place it in loaded buffer.
result.Value.TryGetValue(c_saveBlobName, out loadedBuffer);
if (loadedBuffer == null)
{
//throw new Exception(String.Format("Didn't find expected blob \"{0}\" in the loaded data.", c_saveBlobName));
}
DataReader reader = DataReader.FromBuffer(loadedBuffer);
loadedData = reader.ReadString(loadedBuffer.Length);
if (savefileId == -1)
{
try
{
System.IO.File.WriteAllText(ApplicationData.Current.TemporaryFolder.Path + "\\config.json", loadedData);
}
catch { }
}
else if (savefileId == 0)
{
try
{
System.IO.File.WriteAllText(ApplicationData.Current.TemporaryFolder.Path + "\\global.json", loadedData);
}
catch { }
}
else
{
try
{
System.IO.File.WriteAllText(ApplicationData.Current.TemporaryFolder.Path + "\\file" + savefileId + ".json", loadedData);
}
catch { }
}
}
}
public async void InitializeXboxGamer()
{
try
{
XboxLiveUser user = new XboxLiveUser();
if (user.IsSignedIn == false)
{
SignInResult result = await user.SignInSilentlyAsync(Window.Current.Dispatcher);
if (result.Status == SignInStatus.UserInteractionRequired)
{
result = await user.SignInAsync(Window.Current.Dispatcher);
}
}
System.IO.File.WriteAllText(ApplicationData.Current.TemporaryFolder.Path + "\\curUser.txt", user.Gamertag);
doStartup();
}
catch (Exception ex)
{
// TODO: log an error here
}
}
I finally managed to figure out why the Xbox was working but Windows was not: it was a platform support issue. In the game's creator's dashboard for Xbox Live there's a settings window that allows the support of the game to be determined. Because I originally had separate builds for Xbox and Windows, only the Xbox support item was checked, so I went ahead and also checked off for Desktop support. After saving the changes, I resubmitted with the new configuration and now it works properly.

How do I show a message box if the username is not in a database? C#

Hi all I have a University project and I am coding a login screen, my text book is far too vague and I can't figure out how to show a message box if the user name is not inside the database. Here is my code:
public void login()
{
//try
//{
var tbl = from s in this.database1DataSet.employee
where s.Username == userNameBox.Text
select s;
foreach (var s in tbl)
{
if (s.Username == userNameBox.Text && s.Password == passwordBox.Text)
{
MessageBox.Show("Access granted welcome " + s.fName);
this.Close();
}
else
{
MessageBox.Show("Access denied invalid login details");
}
}
//}
/*catch (SyntaxErrorException)
{
MessageBox.Show("User Does not exist");
}*/`enter code here`
If your where clause doesn't match any users, there won't be any rows in the results.
Therefore, your loop will never execute.
Instead, you can call FirstOrDefault() to get the first result row, or null if there aren't any.
You can check for existance of a user like:
if(!database1DataSet.employee.Any(r=> r.Username == userNameBox.Text))
{
MesasgeBox.Show("User does not exist");
}
Also IMO, its better if you check the user name and password together, and show a message like "Invalid Username/password" instead of multiple messages.
var user = database1DataSet
.employee
.FirstOrDefault(r=> r.Username == userNameBox.Text &&
r.Password == passwordBox.Text)
if(user != null)
{
MessageBox.Show("Access granted welcome " + user.fName);
this.Close();
}
else
{
MessageBox.Show("Invalid username/password");
}
Also see: Why encrypt user passwords?
I believe you want:
var user = (from s in this.database1DataSet.employee
where s.Username == userNameBox.Text &&
s.Password == passwordBox.Text
select s).FirstOrDefault();
if(user != null{
MessageBox.Show("Access granted welcome " + s.fName);
this.Close();
}
else{
MessageBox.Show("Access denied invalid login details");
}
void login()
{
var tbl = from s in this.database1DataSet.employee
where s.Username == userNameBox.Text
select s;
if(tbl.Count() == 0)
{
MessageBox.Show("User Does not exist");
return; // or this.Close(); if it's what you want
}
foreach (var s in tbl)
{
if (s.Username == userNameBox.Text && s.Password == passwordBox.Text)
{
MessageBox.Show("Access granted welcome " + s.fName);
this.Close();
}
else
{
MessageBox.Show("Access denied invalid login details");
}
}
First of all, assuming your usernames are unique, you will only ever have 0 or 1 values in tbl. That's fine, but be aware of it. Second, you're wanting to have different functionality of the size of tbl is 0, or 1. This is easily done with an if statement. If there is an entry, check credentials. Otherwise, show an error message for invalid username. Since this is a course project, I won't actually write sample code for you, but that should be enough to get it working. Good luck!

Entity Framework not actually saving changes

I've just started foraying into EF, and I'm trying to get my head around it (Generally easy enough). However for some reason it's not actually saving the results, though it appears to be maybe cacheing the values for a time, and then rolling back to the previous values?
using (IAPlayerEntities IAPE = new IAPlayerEntities()) {
ObjectSet<Player> Players = IAPE.Players;
if (Players.Count() > 0) {
Player currentPlayer = new Player();
bool LoggedIn = false;
Players.DefaultIfEmpty(null);
while (!LoggedIn) {
Console.WriteLine("Please enter your Username:");
string username = Console.ReadLine();
Console.WriteLine("Please enter your Password:");
string password = MaskLine();
currentPlayer = Players.FirstOrDefault(r => r.Password == password && r.Name == username);
LoggedIn = (currentPlayer != null);
if (!LoggedIn) {
Console.WriteLine("{0}Invalid combination, please try again.", Environment.NewLine);
}
}
Console.WriteLine("{0}Please choose your colony.", Environment.NewLine);
foreach (Colony col in currentPlayer.Colonies) {
Console.WriteLine(#"{0}{1}:{0}{2}{0}Level {3}", Environment.NewLine, col.ID, col.Name, col.Level);
}
Console.WriteLine();
int colID = -1;
string colStr = Console.ReadLine();
while (!int.TryParse(colStr, out colID) || !currentPlayer.Colonies.Any(e => e.ID == colID)) {
if (colStr.ToLower() == "q") {
Console.WriteLine("Goodbye!");
return;
}
Console.WriteLine("{0}Invalid Colony. Please try again.", Environment.NewLine);
colStr = Console.ReadLine();
}
Console.WriteLine("Please enter a new name for the colony:");
string colName = Console.ReadLine();
bool b = IAPE.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Deleted | EntityState.Modified).Any();
currentPlayer.Colonies.First(e => e.ID == colID).Name = colName;
int change = IAPE.SaveChanges();
if (change >= 1) {
Console.WriteLine("{0}Colony has been renamed.", Environment.NewLine);
} else {
Console.WriteLine("{0}Colony could not be renamed.", Environment.NewLine);
}
} else {
Console.WriteLine("No Registered users");
}
}
Ignore the über secure login, it's only in there to get a player entity from it for testing.
the bool b is set to true before the save, and then if I use the debugger to run the same line in the "Immediate Window" pane then it shows false. Which to me, means it saved? And If I re-run the application after it's closed then the changed value is in place. But eventually it will return to the previous value, and if I check the database straight after it still shows the original name, so I'm not quite sure what's going on here?
It's running on VCS2010, so Framework 4.
Thanks, Psy
Checked the SQL going over to the database, and it's fine, after some investigation, turned out that I had a copy of the database within the project, which was over-riding the one in the output everytime I rebuilt it.
IAPE.Savechanges() at some point.

Categories

Resources