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.
Related
I'm trying to create a project of an ATM where you have to enter the card number and pin but it's not working when I put the right pin says "Pin not found!" which is the catch but I copied the code from above and just changed what I thought necessary, does anyone know what's wrong?
static void Main()
{
using (var cn = new SqlConnection("Data Source=MAD-PC-023;Database=atmbd;Trusted_Connection=True;"))
{
cn.Open();
string debitCard = "";
Console.WriteLine("Insert your card number: ");
while (true)
{
try
{
debitCard = Console.ReadLine();
if (debitCard.Length != 8)
{
Console.WriteLine("Wrong format!");
}
else
{
// falta algum IF EXISTS IN DB
using (var cmd = new SqlCommand() { Connection = cn, CommandText = "SELECT FirstName FROM atm WHERE CardNumber = '" + debitCard + "'" })
{
var reader = cmd.ExecuteReader();
if (reader.Read() == true)
{
Console.WriteLine("Hi, " + reader.GetString(0));
break;
}
else
{
Console.WriteLine("Not found");
}
}
}
}
catch
{
Console.WriteLine("Not found!");
}
}
string pin = "";
Console.WriteLine("Insert pin ");
while (true)
{
try
{
pin = Console.ReadLine();
using (var cmd = new SqlCommand() { Connection = cn, CommandText = "SELECT FirstName, LastName FROM atm WHERE Pin = '" + pin + "'" })
{
var reader = cmd.ExecuteReader();
if (reader.Read() == true)
{
Console.WriteLine("User Found");
break;
}
else
{
Console.WriteLine("Not found!");
}
}
}
catch
{
Console.WriteLine("Pin not found!");
}
}
}
}
I've tried many different ways and I can't do it. If anyone can help me, I'd be grateful
There are many issues in your existing code. Let me highlight few of them.
You should use parameterized query, you code is open to SQL Injection.
I don’t know why are you storing card number and pin in your database tables. It’s against PCIDSS standards, you need to read about it.
You cannot store the card number as plain text, I don’t know about current standards, but earlier it was that you should mask the card while storing and now I think it’s token based ( at lest in india now).
And you can’t at all store the PIN number in database as plain text.
You need to store the encrypted PIN number.
And there is no one-one mapping for your card number and pin. Because same pin can be used by many people, so you need one-one mapping as well.
You should simplify your query to IF EXISTS SELECT 1 FROM …
If you simplify your code then you will realize that you need to rerun only one item from database, so you could use ExecuteScalar for the same.
And last but not the least, put breakpoint and debug your code.
Currently, your catch block not taking exception object. So it is difficult to find the exact root cause of this issue. So change your catch block as below
catch(Exception ex) { Console.WriteLine(ex.Message); }
From the exception object, you will get the exact root cause of your issue.
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()
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();
I currently have a bool called debug. I want it so that when I press F10 it will set the bool to true, then if I press it again back to false and so on.
This is the code I am using:
bool debug = false;
if (cVersion < oVersion)
{
Process.Start("http://consol.cf/update.php");
return;
}
for (; ; )
{
if (debug)
{
Console.WriteLine("Please type in a command");
cmd = Console.ReadLine();
p.Send(cmd);
}
else
{
Console.WriteLine("Press enter to execute config");
Console.ReadLine();
WebConfigReader conf =
new WebConfigReader(url);
string[] tokens = Regex.Split(conf.ReadString(), #"\r?\n|\r");
foreach (string s in tokens)
//ConsoleConfig cons = new ConsoleConfig();
{
p.Send(s);
//p.Send(test);
}
}
Thanks in advance.
It depends on the exact behaviour you want. You're probably best off rolling your own version of Console.WriteLine.
The following toggles debug and instantly switch to the other mode, ignoring any partially entered command.
private static bool InterruptableReadLine(out string result)
{
var builder = new StringBuilder();
var info = Console.ReadKey(true);
while (info.Key != ConsoleKey.Enter && info.Key != ConsoleKey.F10)
{
Console.Write(info.KeyChar);
builder.Append(info.KeyChar);
info = Console.ReadKey(true);
}
Console.WriteLine();
result = builder.ToString();
return info.Key == ConsoleKey.F10;
}
// reading input, or just waiting for enter in your infinite loop
string command;
var interrupted = InterruptableReadLine(out command);
if (interrupted)
{
debug = !debug;
continue;
}
// do stuff with command if necessary
bool debug = false;
public void Toggle()
{
ConsoleKeyInfo keyinfo = Console.ReadKey();
if (keyinfo.Key == ConsoleKey.F10)
{
debug = !debug;
if(debug)
{
//Your code here if debug = true
}
else
{
//Your code here if debug = false
}
}
else
{
//Your code here if key press other than F10
}
}
ConsoleKeyInfo: Describes the console key that was pressed, including the character represented by the console key and the state of the SHIFT, ALT, and CTRL modifier keys.
Try once may it help you.
I am writing a small data migration tools from one big database to another small database. All of the others data migration method worked satisfactorily, but the following method has given an exception from the SKIP VALUE IS 100. I run this console script remotely as well as inside of the source server also. I tried in many different was to find the actual problem what it is. After then I found that only from the SKIP VALUE IS 100 it is not working for any TAKE 1,2,3,4,5 or ....
Dear expertise, I don't have any prior knowledge on that type of problem. Any kind of suggestions or comments is appreciatable to resolve this problem. Thanks for you time.
I know this code is not clean and the method is too long. I just tried solve this by adding some line of extra code. Because the problem solving is my main concern. I just copy past the last edited method.
In shot the problem I can illustrate with this following two line
var temp = queryable.Skip(90).Take(10).ToList(); //no exception
var temp = queryable.Skip(100).Take(10).ToList(); getting exception
private static void ImporterDataMigrateToRmgDb(SourceDBEntities sourceDb, RmgDbContext rmgDb)
{
int skip = 0;
int take = 10;
int count = sourceDb.FormAs.Where(x=> x.FormAStateId == 8).GroupBy(x=> x.ImporterName).Count();
Console.WriteLine("Total Possible Importer: " + count);
for (int i = 0; i < count/take; i++)
{
IOrderedQueryable<FormA> queryable = sourceDb.FormAs.Where(x => x.FormAStateId == 8).OrderBy(x => x.ImporterName);
List<IGrouping<string, FormA>> list;
try
{
list = queryable.Skip(skip).Take(take).GroupBy(x => x.ImporterName).ToList();
//this line is getting timeout exception from the skip value of 100.
}
catch (Exception exception)
{
Console.WriteLine(exception.Message);
sourceDb.Dispose();
rmgDb.Dispose();
sourceDb = new SourceDBEntities();
rmgDb = new RmgDbContext();
skip += take;
continue;
}
if (list.Count > 0)
{
foreach (var l in list)
{
List<FormA> formAs = l.ToList();
FormA formA = formAs.FirstOrDefault();
if (formA == null) continue;
Importer importer = formA.ConvertToRmgImporterFromFormA();
Console.WriteLine(formA.FormANo + " " + importer.Name);
var importers = rmgDb.Importers.Where(x => x.Name.ToLower() == importer.Name.ToLower()).ToList();
//bool any = rmgDb.Importers.Any(x => x.Name.ToLower() == formA.ImporterName.ToLower());
if (importers.Count() == 1)
{
foreach (var imp in importers)
{
Importer entity = rmgDb.Importers.Find(imp.Id);
entity.Country = importer.Country;
entity.TotalImportedAmountInUsd = importer.TotalImportedAmountInUsd;
rmgDb.Entry(entity).State = EntityState.Modified;
}
}
else
{
rmgDb.Importers.Add(importer);
}
rmgDb.SaveChanges();
Console.WriteLine(importer.Name);
}
}
skip += take;
}
Console.WriteLine("Importer Data Migration Completed");
}
I have fixed my problem by modifying following code
var queryable =
sourceDb.FormAs.Where(x => x.FormAStateId == 8)
.Select(x => new Adapters.ImporterBindingModel()
{
Id = Guid.NewGuid().ToString(),
Active = true,
Created = DateTime.Now,
CreatedBy = "System",
Modified = DateTime.Now,
ModifiedBy = "System",
Name = x.ImporterName,
Address = x.ImporterAddress,
City = x.City,
ZipCode = x.ZipCode,
CountryId = x.CountryId
})
.OrderBy(x => x.Name);