C
C#9mo ago
Mekasu0124

✅ Adding A Project Reference

https://learn.microsoft.com/en-us/troubleshoot/developer/visualstudio/csharp/language-compilers/store-custom-information-config-file#:~:text=Add%20a%20reference,select%20OK. According to this section, I'm supposed to be able to add a reference for my App.config file. However, when I right click my project, there is no Add Reference button to click. I tried going to Add > Project Reference, but there is no .Net tab to select from. I'm honestly lost on how to do this. I'm starting on the C# Academy Project; Coding Tracker and it's one of the initial steps which is where I go the link from. Thanks in advance
No description
No description
240 Replies
Pobiega
Pobiega9mo ago
"Add -> Project Reference" is for referencing other projects, not individual files. "App.config" is a .net framework thing, is this a framework project?
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
Mekasu0124
Mekasu01249mo ago
I fell asleep at my computer. Why was the thread marked solved? It’s a C# Console Based application project given as the final beginner section project on the C# Academy Website.
Pobiega
Pobiega9mo ago
Yeah but is it a .net framework project or not?
Mekasu0124
Mekasu01249mo ago
https://www.thecsharpacademy.com/project/13 I’m not entirely sure how to answer that. It is using Net6.0
Pobiega
Pobiega9mo ago
This is not how we recommend doing configuration anymore, and if its using modern .NET you should absolutely not be using .config files
Mekasu0124
Mekasu01249mo ago
Oh I didn’t know that. I was just following and completing the projects they had listed out.
Pobiega
Pobiega9mo ago
Well, thats what that page tells you to do indeed...
Mekasu0124
Mekasu01249mo ago
Each project comes with requirements and challenges. So I do the requirements first and then submit for review. Once complete I go back and try the challenges
Pobiega
Pobiega9mo ago
so you have two options - Follow their recommendations and use the "old" style configuration - ignore their recommendations and use the more modern style of configuration
Mekasu0124
Mekasu01249mo ago
I’d love to use more recommended methods but as stated here by the owner of the discord and site, if I don’t follow their requirements for the requirements section of the project then it will get failed
No description
Pobiega
Pobiega9mo ago
ok well that answers that question
Mekasu0124
Mekasu01249mo ago
So how would I go about adding the project reference like they want?
Pobiega
Pobiega9mo ago
well, https://learn.microsoft.com/en-us/troubleshoot/developer/visualstudio/csharp/language-compilers/store-custom-information-config-file refers to .NET framework, not .NET 5+ so to follow their tutorial exactly, you'd need to use .net framework that said, I do believe there is a nuget for config manager in modern .NET
Pobiega
Pobiega9mo ago
System.Configuration.ConfigurationManager 6.0.1
Provides types that support using configuration files. Commonly Used Types: System.Configuration.Configuration System.Configuration.ConfigurationManager
Mekasu0124
Mekasu01249mo ago
Ok. Can you unmake this post solved? I’ll check out the nuget package later today after work and get back to you if that’s alright
Pobiega
Pobiega9mo ago
I didn't mark it
Mekasu0124
Mekasu01249mo ago
I didn’t either
Pobiega
Pobiega9mo ago
try editing the title
Mekasu0124
Mekasu01249mo ago
Thank you and I’ll get back to you this afternoon. Thanks for your help so far!
Pobiega
Pobiega9mo ago
Looking closer at the project page, it doesnt explicitly say you NEED to use the config manager it just links to that as a suggested resource you could thus implement this using the modern ConfigurationBuilder and still use xml files
Pobiega
Pobiega9mo ago
Configuration - .NET
Learn how to use the Configuration API to configure .NET applications. Explore various inbuilt configuration providers.
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
Mekasu0124
Mekasu01249mo ago
All good. And so far it’s public and free
Pobiega
Pobiega9mo ago
there is no authorization to reach the pages, but the links is behind a registration portal
Mekasu0124
Mekasu01249mo ago
All I know is it says "You'll need to create a configuration file that you'll contain your database path and connection strings." under the requirements
Pobiega
Pobiega9mo ago
yep thats what I gathered as well
Mekasu0124
Mekasu01249mo ago
I was just assuming that since that was the method they linked to that project, that that was how they wanted us to go about it
Pobiega
Pobiega9mo ago
so you could easily do that with xml on the modern config builder, or even use json if you'd prefer that tbh, ask on their discord say that "Hey I'm doing this with .net 6, and Microsoft.Extensions.Configuration seems to be the more modern way of doing configs, do we have to use ConfigrationManager?"
Mekasu0124
Mekasu01249mo ago
ok I've asked in the interum, can I ask another question? that's unrelated
Pobiega
Pobiega9mo ago
yes
Mekasu0124
Mekasu01249mo ago
public static void CreateDatabase()
{
Console.WriteLine("Creating Database");
SQLiteConnection.CreateFile("habits.db");

using (var sqlite = new SQLiteConnection(@"Data Source=habits.db"))
{
sqlite.Open();
string sql = @"CREATE TABLE IF NOT EXISTS
[habits] (
[Id] INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
[Name] VARCHAR(70) NULL,
[Date] VARCHAR(50) NULL,
[Count] INTEGER NULL,
[Description] VARCHAR(2048))";
SQLiteCommand command = new SQLiteCommand(sql, sqlite);
command.ExecuteNonQuery();
}

Console.WriteLine("New Database Created");
}
public static void DeleteEntry(Habit habit)
{
using (SQLiteConnection sqlite = new SQLiteConnection(@"Data Source=habits.db"))
{
using (SQLiteCommand cmd = new SQLiteCommand(sqlite))
{
sqlite.Open();

cmd.CommandText = "DELETE FROM habits WHERE Name=@CurrentName";
cmd.Parameters.Add(new SQLiteParameter("@CurrentName", habit.Name));
cmd.ExecuteNonQuery();

sqlite.Close();
}
}
}
public static void CreateDatabase()
{
Console.WriteLine("Creating Database");
SQLiteConnection.CreateFile("habits.db");

using (var sqlite = new SQLiteConnection(@"Data Source=habits.db"))
{
sqlite.Open();
string sql = @"CREATE TABLE IF NOT EXISTS
[habits] (
[Id] INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
[Name] VARCHAR(70) NULL,
[Date] VARCHAR(50) NULL,
[Count] INTEGER NULL,
[Description] VARCHAR(2048))";
SQLiteCommand command = new SQLiteCommand(sql, sqlite);
command.ExecuteNonQuery();
}

Console.WriteLine("New Database Created");
}
public static void DeleteEntry(Habit habit)
{
using (SQLiteConnection sqlite = new SQLiteConnection(@"Data Source=habits.db"))
{
using (SQLiteCommand cmd = new SQLiteCommand(sqlite))
{
sqlite.Open();

cmd.CommandText = "DELETE FROM habits WHERE Name=@CurrentName";
cmd.Parameters.Add(new SQLiteParameter("@CurrentName", habit.Name));
cmd.ExecuteNonQuery();

sqlite.Close();
}
}
}
when I delete an item from the database, how do I get the Id's of the remaining items to decrease by one? What I mean is, if I store 4 items, they have an Id of 1, 2, 3, and 4. If I go through my menu options of my console project and selected to delete number 2, then I'm left with 1, 3, and 4 and when I try to delete 3, this function is triggered
public static int ValidateIndexSelection(int selectedIndex, List<Habit> habits, string sentence)
{
List<int> currentIds = new();

for (int i = 0; i < habits.Count; i++)
{
int habId = i + 1;
currentIds.Add(habId);
}

while (!currentIds.Contains(selectedIndex))
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[Error] Selected Number Does Not Exist");

Console.ForegroundColor = ConsoleColor.White;
Console.Write($"{sentence}: ");

string input = Console.ReadLine();
selectedIndex = ValidateNumericInput(input, "Your Selection");
return ValidateIndexSelection(selectedIndex, habits, sentence);
}

return selectedIndex;
}
public static int ValidateIndexSelection(int selectedIndex, List<Habit> habits, string sentence)
{
List<int> currentIds = new();

for (int i = 0; i < habits.Count; i++)
{
int habId = i + 1;
currentIds.Add(habId);
}

while (!currentIds.Contains(selectedIndex))
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[Error] Selected Number Does Not Exist");

Console.ForegroundColor = ConsoleColor.White;
Console.Write($"{sentence}: ");

string input = Console.ReadLine();
selectedIndex = ValidateNumericInput(input, "Your Selection");
return ValidateIndexSelection(selectedIndex, habits, sentence);
}

return selectedIndex;
}
No description
Pobiega
Pobiega9mo ago
when I delete an item from the database, how do I get the Id's of the remaining items to decrease by one?
you don't thats not how IDs work
Mekasu0124
Mekasu01249mo ago
ok then my trigger function si written wrong then
Pobiega
Pobiega9mo ago
trigger? I mean, you wouldn't validate the ID before querying the database
Mekasu0124
Mekasu01249mo ago
the helper function. ValidateIndexSelection. Instead of building the Id's based off the for-loop, it should be built based off the items Id's
Pobiega
Pobiega9mo ago
if you want to see if there is an item with id 2 in the database, you ask the database
Mekasu0124
Mekasu01249mo ago
right. In my DeleteHabit() function, it gathers the list of habits with List<Habit> currentHabits = Database.GetHabits(); This query's the database for the currently tracked habits and returns them. Then it prints that chart of those currentHabits and prompts the user for their selection of which Id they want to delete and passes the user's input, the list of currentHabits, and the action string to the helper function ValidateIndexSelection. Since I'm already returning the it'd in the Database.GetHabits() function, I can build my list to check from using those item's id's instead of using the for-loops counting index
Pobiega
Pobiega9mo ago
yeah that sounds like a good idea. Im not sure why you're building a new list actually
Mekasu0124
Mekasu01249mo ago
I wrote my helper function wrong
Pobiega
Pobiega9mo ago
List<int> currentIds = new();
for (int i = 0; i < habits.Count; i++)
{
int habId = i + 1;
currentIds.Add(habId);
}
List<int> currentIds = new();
for (int i = 0; i < habits.Count; i++)
{
int habId = i + 1;
currentIds.Add(habId);
}
this is very weird. If you just want the IDs of all existing items, use habits.Select(x => x.Id).ToHashSet();
Mekasu0124
Mekasu01249mo ago
public static void DeleteHabit()
{
Console.Clear();
Console.WriteLine("------------------------");
Console.WriteLine("Deleting A Current Habit");
Console.WriteLine("------------------------");
Console.WriteLine("Select A Habit Below To Delete");

List<Habit> currentHabits = Database.GetHabits();
Helpers.PrintHabitChart(currentHabits);

Console.Write("Your Selection: ");
string input = Console.ReadLine();
int selectedIndex = Helpers.ValidateNumericInput(input, "Your Selection");
selectedIndex = Helpers.ValidateIndexSelection(selectedIndex, currentHabits, "Your Selection");

Habit selectedHabit = Database.GetSelectedHabit(selectedIndex);

Database.DeleteEntry(selectedHabit);

Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Your Habit Has Been Deleted");
Thread.Sleep(2000);
Console.Clear();
Console.ForegroundColor = ConsoleColor.White;
MainMenu.ShowMenu();
}
public static void DeleteHabit()
{
Console.Clear();
Console.WriteLine("------------------------");
Console.WriteLine("Deleting A Current Habit");
Console.WriteLine("------------------------");
Console.WriteLine("Select A Habit Below To Delete");

List<Habit> currentHabits = Database.GetHabits();
Helpers.PrintHabitChart(currentHabits);

Console.Write("Your Selection: ");
string input = Console.ReadLine();
int selectedIndex = Helpers.ValidateNumericInput(input, "Your Selection");
selectedIndex = Helpers.ValidateIndexSelection(selectedIndex, currentHabits, "Your Selection");

Habit selectedHabit = Database.GetSelectedHabit(selectedIndex);

Database.DeleteEntry(selectedHabit);

Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Your Habit Has Been Deleted");
Thread.Sleep(2000);
Console.Clear();
Console.ForegroundColor = ConsoleColor.White;
MainMenu.ShowMenu();
}
this is the function that is executed when the user selects to delete a habit from the menu.
public static Habit GetSelectedHabit(int index)
{
Habit selectedHabit = new();

using (SQLiteConnection sqlite = new SQLiteConnection(@"Data Source=habits.db"))
{
using (SQLiteCommand cmd = new SQLiteCommand(sqlite))
{
SQLiteDataReader reader;

sqlite.Open();

cmd.CommandText = "SELECT * FROM habits WHERE Id=@SelectedID";
cmd.Parameters.Add(new SQLiteParameter("@SelectedID", index));

reader = cmd.ExecuteReader();

try
{
while (reader.Read())
{
int id = int.Parse(reader["Id"].ToString());
string name = reader["Name"].ToString();
DateTime date = DateTime.Parse(reader["Date"].ToString());
int count = int.Parse(reader["Count"].ToString());
string description = reader["Description"].ToString();

selectedHabit = new()
{
Id = id,
Name = name,
Date = date,
Count = count,
Description = description
};
}

sqlite.Close();
}
catch (SQLiteException e)
{
Console.WriteLine(e.Message);
}
}
}

return selectedHabit;
}
public static Habit GetSelectedHabit(int index)
{
Habit selectedHabit = new();

using (SQLiteConnection sqlite = new SQLiteConnection(@"Data Source=habits.db"))
{
using (SQLiteCommand cmd = new SQLiteCommand(sqlite))
{
SQLiteDataReader reader;

sqlite.Open();

cmd.CommandText = "SELECT * FROM habits WHERE Id=@SelectedID";
cmd.Parameters.Add(new SQLiteParameter("@SelectedID", index));

reader = cmd.ExecuteReader();

try
{
while (reader.Read())
{
int id = int.Parse(reader["Id"].ToString());
string name = reader["Name"].ToString();
DateTime date = DateTime.Parse(reader["Date"].ToString());
int count = int.Parse(reader["Count"].ToString());
string description = reader["Description"].ToString();

selectedHabit = new()
{
Id = id,
Name = name,
Date = date,
Count = count,
Description = description
};
}

sqlite.Close();
}
catch (SQLiteException e)
{
Console.WriteLine(e.Message);
}
}
}

return selectedHabit;
}
it then calls this function to get the list of currentHabits
public static int ValidateIndexSelection(int selectedIndex, List<Habit> habits, string sentence)
{
List<int> currentIds = new();

for (int i = 0; i < habits.Count; i++)
{
int habId = habits[i].Id;
currentIds.Add(habId);
}

while (!currentIds.Contains(selectedIndex))
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[Error] Selected Number Does Not Exist");

Console.ForegroundColor = ConsoleColor.White;
Console.Write($"{sentence}: ");

string input = Console.ReadLine();
selectedIndex = ValidateNumericInput(input, "Your Selection");
return ValidateIndexSelection(selectedIndex, habits, sentence);
}

return selectedIndex;
}
public static int ValidateIndexSelection(int selectedIndex, List<Habit> habits, string sentence)
{
List<int> currentIds = new();

for (int i = 0; i < habits.Count; i++)
{
int habId = habits[i].Id;
currentIds.Add(habId);
}

while (!currentIds.Contains(selectedIndex))
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[Error] Selected Number Does Not Exist");

Console.ForegroundColor = ConsoleColor.White;
Console.Write($"{sentence}: ");

string input = Console.ReadLine();
selectedIndex = ValidateNumericInput(input, "Your Selection");
return ValidateIndexSelection(selectedIndex, habits, sentence);
}

return selectedIndex;
}
then when the user makes a selection, their input goes through a validation
Pobiega
Pobiega9mo ago
right yeah okay here is what I would do instead of making an ID list, just use the list of habits you already have
Mekasu0124
Mekasu01249mo ago
it displays correctly in the table that is printed to the console, however, I messed up my validation function by using the int habId = i + 1 instead of int habId = habits[i].Id;
Pobiega
Pobiega9mo ago
so if you want the ID to match, check with habits.FirstOrDefault(x => x.Id == selectedIndex); if thats not null, there was a match if its null, no match no that wouldn't work either habits[i] the i doesnt match the id in the database oh nvm, right youre picking an index from the list, not the ID and then getting the ID from there to pass to delete. yeah that works
Mekasu0124
Mekasu01249mo ago
public static int ValidateIndexSelection(int selectedIndex, List<Habit> habits, string sentence)
{
while (habits.FirstOrDefault(x => x.Id == selectedIndex) == null)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[Error] Selected Number Does Not Exist");

Console.ForegroundColor = ConsoleColor.White;
Console.Write($"{sentence}: ");

string input = Console.ReadLine();
selectedIndex = ValidateNumericInput(input, "Your Selection");
return ValidateIndexSelection(selectedIndex, habits, sentence);
}

return selectedIndex;
}
public static int ValidateIndexSelection(int selectedIndex, List<Habit> habits, string sentence)
{
while (habits.FirstOrDefault(x => x.Id == selectedIndex) == null)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[Error] Selected Number Does Not Exist");

Console.ForegroundColor = ConsoleColor.White;
Console.Write($"{sentence}: ");

string input = Console.ReadLine();
selectedIndex = ValidateNumericInput(input, "Your Selection");
return ValidateIndexSelection(selectedIndex, habits, sentence);
}

return selectedIndex;
}
so like this?
Pobiega
Pobiega9mo ago
depends? if there are 3 items (ids 7 8 9), what do you want the user to enter to delete the 2nd item? 1, 2 or 8?
Mekasu0124
Mekasu01249mo ago
They enter the Id of the habit shown in the table
Pobiega
Pobiega9mo ago
oh, so it is selectedId then, not selectedIndex index != id
Mekasu0124
Mekasu01249mo ago
I mean yea you're right. I can change the variable name
Pobiega
Pobiega9mo ago
that would probably be good to increase readability but yeah, then that would work you can actually simplify it further while (habits.FirstOrDefault(x => x.Id == selectedIndex) == null) can be...
while (!habits.Any(x => x.Id == selectedIndex))
while (!habits.Any(x => x.Id == selectedIndex))
I prefer that I think since you want a boolean
Mekasu0124
Mekasu01249mo ago
- public static void DeleteEntry(Habit habit)
+ public static void DeleteEntry(int selectedId)
{
using (SQLiteConnection sqlite = new SQLiteConnection(@"Data Source=habits.db"))
{
using (SQLiteCommand cmd = new SQLiteCommand(sqlite))
{
sqlite.Open();

- cmd.CommandText = "DELETE FROM habits WHERE Name=@CurrentName";
+ cmd.CommandText = "DELETE FROM habits WHERE Id=@selectedId";
- cmd.Parameters.Add(new SQLiteParameter("@CurrentName", habit.Name));
+ cmd.Parameters.Add(new SQLiteParameter("@selectedId", selectedId));
cmd.ExecuteNonQuery();

sqlite.Close();
}
}
}
- public static void DeleteEntry(Habit habit)
+ public static void DeleteEntry(int selectedId)
{
using (SQLiteConnection sqlite = new SQLiteConnection(@"Data Source=habits.db"))
{
using (SQLiteCommand cmd = new SQLiteCommand(sqlite))
{
sqlite.Open();

- cmd.CommandText = "DELETE FROM habits WHERE Name=@CurrentName";
+ cmd.CommandText = "DELETE FROM habits WHERE Id=@selectedId";
- cmd.Parameters.Add(new SQLiteParameter("@CurrentName", habit.Name));
+ cmd.Parameters.Add(new SQLiteParameter("@selectedId", selectedId));
cmd.ExecuteNonQuery();

sqlite.Close();
}
}
}
that means I can simply re-write this too which also negates my DeleteEntry function from having to query my database twice.
Pobiega
Pobiega9mo ago
I'm not sure you needed that in the first place either, you could have fetched the desired item from the habits list itself but yeah, this works
Mekasu0124
Mekasu01249mo ago
what do you mean? This is my first time working with a database in c#. It's so different, but yet semi-similar to python
Pobiega
Pobiega9mo ago
This is your delete method the way it looked before
public static void DeleteHabit()
{
Console.Clear();
Console.WriteLine("------------------------");
Console.WriteLine("Deleting A Current Habit");
Console.WriteLine("------------------------");
Console.WriteLine("Select A Habit Below To Delete");

List<Habit> currentHabits = Database.GetHabits();
Helpers.PrintHabitChart(currentHabits);

Console.Write("Your Selection: ");
string input = Console.ReadLine();
int selectedIndex = Helpers.ValidateNumericInput(input, "Your Selection");
selectedIndex = Helpers.ValidateIndexSelection(selectedIndex, currentHabits, "Your Selection");

Habit selectedHabit = Database.GetSelectedHabit(selectedIndex);

Database.DeleteEntry(selectedHabit);

Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Your Habit Has Been Deleted");
Thread.Sleep(2000);
Console.Clear();
Console.ForegroundColor = ConsoleColor.White;
MainMenu.ShowMenu();
}
public static void DeleteHabit()
{
Console.Clear();
Console.WriteLine("------------------------");
Console.WriteLine("Deleting A Current Habit");
Console.WriteLine("------------------------");
Console.WriteLine("Select A Habit Below To Delete");

List<Habit> currentHabits = Database.GetHabits();
Helpers.PrintHabitChart(currentHabits);

Console.Write("Your Selection: ");
string input = Console.ReadLine();
int selectedIndex = Helpers.ValidateNumericInput(input, "Your Selection");
selectedIndex = Helpers.ValidateIndexSelection(selectedIndex, currentHabits, "Your Selection");

Habit selectedHabit = Database.GetSelectedHabit(selectedIndex);

Database.DeleteEntry(selectedHabit);

Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Your Habit Has Been Deleted");
Thread.Sleep(2000);
Console.Clear();
Console.ForegroundColor = ConsoleColor.White;
MainMenu.ShowMenu();
}
currentHabits is a list of all habits, as fetched from your database. We don't need to query the database a second time to get an item we already have in that list we can just do var selectedHabit = currentHabits.FirstOrDefault(x => x.Id == selectedId);
Mekasu0124
Mekasu01249mo ago
right. I removed the line Habit selectedHabit = Database.GetSelectedHabit(selectedIndex); and just passed the selectedId to the Database.DeleteEntry(selectedHabit); to negate doing that or am I missing what you're saying?
Pobiega
Pobiega9mo ago
well, both are valid you can fetch the ID and pass the ID to your database.delete method, thats fine but since you already have the the Habit that you want to delete, you could have kept the old delete method (that took a Habit, not an id) that would also work, same amount of database queries it was specifically Habit selectedHabit = Database.GetSelectedHabit(selectedIndex); that could be removed, as you already had that habit in memory, in this method
Mekasu0124
Mekasu01249mo ago
oh ok. I got you
Pobiega
Pobiega9mo ago
the benefit of that is it makes it harder to accidentally pass the wrong id database.DeleteEntry(6); is valid, but might do the wrong thing Database.DeleteEntry(habit); is harder to get wrong, as its unlikely you created a new habit and manually gave it the wrong id. In fact, you can make that impossible. both are perfectly fine for a beginner thou, this is something I think about as its the stuff I work with daily and trying to design the "perfect" interfaces for my coworkers to use 🙂
Mekasu0124
Mekasu01249mo ago
Habit habit = currentHabits.Where(x => x.Id == selectedId);
Database.DeleteEntry(habit);
Habit habit = currentHabits.Where(x => x.Id == selectedId);
Database.DeleteEntry(habit);
so I should've done something like this instead?
Pobiega
Pobiega9mo ago
not should've per se, but could've. And First instead of Where (Where gives you 0..N results, First gives you 1)
Mekasu0124
Mekasu01249mo ago
so Any instead of Where
Pobiega
Pobiega9mo ago
no, Any returns true or false it checks if "any item matches this filter" first gives back the first item that does match the filter, and throws an error if no item did
Mekasu0124
Mekasu01249mo ago
oh ok so First instead of Where
Pobiega
Pobiega9mo ago
yeah where gives you back ALL the items that matched the filter 🙂
Mekasu0124
Mekasu01249mo ago
and First gives back the first matching, yea?
Pobiega
Pobiega9mo ago
granted, in this situation that would be 0 or 1, but its still in an enumerable, instead of just as a direct reference yes
Mekasu0124
Mekasu01249mo ago
oh ok
public static void DeleteHabit()
{
var habit = currentHabits.First(x => x.Id == selectedId);
Database.DeleteEntry(habit);
}
public static void Datbase.DeleteEntry(Habit habit)
{
using SQLiteConnection sqlite = new SQLiteConnection(@"Data Source=habits.db");
using SQLiteCommand cmd = new SQLiteCommand(sqlite);

sqlite.Open();
cmd.CommandText = "DELETE FROM habits WHERE Id=@selectedId";
cmd.Parameters.AddWithValue("@selectedId", habit.Id);
cmd.ExecuteNonQuery();
}
public static void DeleteHabit()
{
var habit = currentHabits.First(x => x.Id == selectedId);
Database.DeleteEntry(habit);
}
public static void Datbase.DeleteEntry(Habit habit)
{
using SQLiteConnection sqlite = new SQLiteConnection(@"Data Source=habits.db");
using SQLiteCommand cmd = new SQLiteCommand(sqlite);

sqlite.Open();
cmd.CommandText = "DELETE FROM habits WHERE Id=@selectedId";
cmd.Parameters.AddWithValue("@selectedId", habit.Id);
cmd.ExecuteNonQuery();
}
so this would be the more efficient alternative
Pobiega
Pobiega9mo ago
same efficiency, just harder to accidentally fuck up this is a good quality in a codebase 🙂
Mekasu0124
Mekasu01249mo ago
I got you. Cool. thank you 🙂
Mekasu0124
Mekasu01249mo ago
as far as which config file style to use from earlier in this post, this is the only response I've received since asking about it
No description
Pobiega
Pobiega9mo ago
hm well, his words dont confirm or deny he just says "a configuration manager of some sort" that could be Microsoft.Extensions.Configuration, or it could be ConfigurationManager. he is also wrong about the config being provided, its not you're supposed to make it
Mekasu0124
Mekasu01249mo ago
ok I'm going to look at other entries and see how they went abou tit so from what I can see, a lot of users went with an App.config xml file.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key ="connString" value="Data Source=TrackingData.db"/>
<add key ="DBLocation" value="TrackingData.db"/>
</appSettings>
</configuration>
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key ="connString" value="Data Source=TrackingData.db"/>
<add key ="DBLocation" value="TrackingData.db"/>
</appSettings>
</configuration>
like that. I can't see what dependencies they used though
Pobiega
Pobiega9mo ago
if thats their file, its almost guaranteed to be ConfigurationManager thats exactly how it structures things
Mekasu0124
Mekasu01249mo ago
ok then i'll have to do that
Pobiega
Pobiega9mo ago
yep, go for it you'll learn the new way eventually anyways, when you start with asp.net
Mekasu0124
Mekasu01249mo ago
does that ivolve adding a project reference though?
MODiX
MODiX9mo ago
Pobiega
Embed Type
Link
Quoted by
<@105026391237480448> from #Adding A Project Reference (click here)
From Pobiega
React with ❌ to remove this embed.
Mekasu0124
Mekasu01249mo ago
ok ty
Pobiega
Pobiega9mo ago
its a nuget reference thou not a project reference
Mekasu0124
Mekasu01249mo ago
ok I'll figure it out after class
Pobiega
Pobiega9mo ago
I'm sure you've added package references before. VS/Rider both have built-in GUIs for it, and dotnet add package <package name> works too
Pobiega
Pobiega9mo ago
no, it doesnt there is a version of ConfigurationManager available for .net 6 its just an updated version of the old one, so it behaves exactly as that one did
Mekasu0124
Mekasu01249mo ago
this one?
No description
Pobiega
Pobiega9mo ago
yes the top one, you want version 6 as you are on .NET 6 version 7.* is for .NET 7 etc
Mekasu0124
Mekasu01249mo ago
ok I've got it installed right
Pobiega
Pobiega9mo ago
so 6.0.1 is your latest
Mekasu0124
Mekasu01249mo ago
right
Pobiega
Pobiega9mo ago
so, now you have access to the ConfigurationManager class that means you can skip step 10 in that guide
Mekasu0124
Mekasu01249mo ago
ok awesome. thank you
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
Mekasu0124
Mekasu01249mo ago
understandable. The person who responded isn't the owner of the academia so I took what they said as a grain of salt and am just going with the nuget package manager that Pobeiga discussed earlier. I'm just currently in class and can't do anything with it yet. Apologies. I'm currently trying to figure out how in the hell sin ^ -1 (4/7) = 0.61 when if you divide 4 by 7 you get 0.57
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
Mekasu0124
Mekasu01249mo ago
I'm trying to figure out how this equation equals 0.61
No description
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
Mekasu0124
Mekasu01249mo ago
idk what aresin is
Pobiega
Pobiega9mo ago
arcsin
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
Pobiega
Pobiega9mo ago
yes the inverse sine
Mekasu0124
Mekasu01249mo ago
I have still yet to get a solid answer to my greatest lifetime question. What does Trig, Calculus, and Physics have to do with being getting a Bachelor's in Computer Science with a focus in Software Development and Cyber Security
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
Pobiega
Pobiega9mo ago
for computer science, math is important. For software development, its not really.
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
Pobiega
Pobiega9mo ago
kekw
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
Pobiega
Pobiega9mo ago
(obviously in stuff like 3d games or complicated financial simulations math becomes important again, but for general programming its kinad secondary) cryptography is very reliant on math thou so if you wanna dive into that (as part of security?) then you'll need some math
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
Mekasu0124
Mekasu01249mo ago
omg of all the times I have sat here and gave up on assignments because I couldn't figure out the solution. I'm a fucking programmer. what's the evaluate command? !e?
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
Mekasu0124
Mekasu01249mo ago
!e
MODiX
MODiX9mo ago
TeBeCo
REPL Result: Success
"loul"
"loul"
Result: string
loul
loul
Compile: 366.102ms | Execution: 27.277ms | React with ❌ to remove this embed.
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
Mekasu0124
Mekasu01249mo ago
oh jk it only does c# either way, I can use Python to give me my answers 😂
MODiX
MODiX9mo ago
TeBeCo
REPL Result: Success
var a = Math.Asin(2.0f/5.0f);
Console.WriteLine(a);
var b = Math.PI - a;
Console.WriteLine(b);
var a = Math.Asin(2.0f/5.0f);
Console.WriteLine(a);
var b = Math.PI - a;
Console.WriteLine(b);
Console Output
0.41151685257088794
2.7300758010189052
0.41151685257088794
2.7300758010189052
Compile: 701.232ms | Execution: 89.251ms | React with ❌ to remove this embed.
Mekasu0124
Mekasu01249mo ago
right
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
Mekasu0124
Mekasu01249mo ago
I'm a programmer lmao I forgot that most languages can do math equations if you set them up correctly I do
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
Mekasu0124
Mekasu01249mo ago
well no. Not windows terminal. I use command prompt
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
Mekasu0124
Mekasu01249mo ago
lol wait
Mekasu0124
Mekasu01249mo ago
this is what I mean
No description
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
Mekasu0124
Mekasu01249mo ago
I don't use Windows Powershell only Command Prompot yes 😂 sorry my brain is confused with the math at the moment
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
Mekasu0124
Mekasu01249mo ago
what does that do?
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
Mekasu0124
Mekasu01249mo ago
does nothing for me
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
Mekasu0124
Mekasu01249mo ago
this is the same thing as having Python installed, opening cmd and typing Python. I can now program in python in my windows terminal
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
Mekasu0124
Mekasu01249mo ago
"profiles":
{
"defaults": {},
"list":
[
{
"commandline": "%SystemRoot%\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",
"guid": "{61c54bbd-c2c6-5271-96e7-009a87ff44bf}",
"hidden": false,
"name": "Windows PowerShell"
},
{
"commandline": "%SystemRoot%\\System32\\cmd.exe",
"guid": "{0caa0dad-35be-5f56-a8ff-afceeeaa6101}",
"hidden": false,
"name": "Command Prompt"
},
{
"guid": "{b453ae62-4e3d-5e58-b989-0a998ec441b8}",
"hidden": false,
"name": "Azure Cloud Shell",
"source": "Windows.Terminal.Azure"
},
{
"guid": "{16208362-94fc-5b1f-a491-5b2624d5ab56}",
"hidden": true,
"name": "Visual Studio Debug Console",
"source": "VSDebugConsole"
},
{
"guid": "{f1efd43c-0060-5b86-9b25-61a550ff06ea}",
"hidden": false,
"name": "Developer Command Prompt for VS 2022",
"source": "Windows.Terminal.VisualStudio"
},
{
"guid": "{c94bc30e-0dd4-5775-87cc-c6fc534064f5}",
"hidden": false,
"name": "Developer PowerShell for VS 2022",
"source": "Windows.Terminal.VisualStudio"
}
]
},
"profiles":
{
"defaults": {},
"list":
[
{
"commandline": "%SystemRoot%\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",
"guid": "{61c54bbd-c2c6-5271-96e7-009a87ff44bf}",
"hidden": false,
"name": "Windows PowerShell"
},
{
"commandline": "%SystemRoot%\\System32\\cmd.exe",
"guid": "{0caa0dad-35be-5f56-a8ff-afceeeaa6101}",
"hidden": false,
"name": "Command Prompt"
},
{
"guid": "{b453ae62-4e3d-5e58-b989-0a998ec441b8}",
"hidden": false,
"name": "Azure Cloud Shell",
"source": "Windows.Terminal.Azure"
},
{
"guid": "{16208362-94fc-5b1f-a491-5b2624d5ab56}",
"hidden": true,
"name": "Visual Studio Debug Console",
"source": "VSDebugConsole"
},
{
"guid": "{f1efd43c-0060-5b86-9b25-61a550ff06ea}",
"hidden": false,
"name": "Developer Command Prompt for VS 2022",
"source": "Windows.Terminal.VisualStudio"
},
{
"guid": "{c94bc30e-0dd4-5775-87cc-c6fc534064f5}",
"hidden": false,
"name": "Developer PowerShell for VS 2022",
"source": "Windows.Terminal.VisualStudio"
}
]
},
I have multiple. What am I doing with it now?
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
Mekasu0124
Mekasu01249mo ago
I did the dotnet tool install -g csharprepl and it works lol
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
Mekasu0124
Mekasu01249mo ago
yea you got me lost junebug
Mekasu0124
Mekasu01249mo ago
No description
Mekasu0124
Mekasu01249mo ago
what am I doing now 😕 duplicate an entry
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
Mekasu0124
Mekasu01249mo ago
ok did that. change the first number to 9?
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
Mekasu0124
Mekasu01249mo ago
I didn't know it was a thing. I just open it from my taskbar, and click the drop down and click cmd
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
Mekasu0124
Mekasu01249mo ago
ok so now that I have the profile setup, how do I use it? If I do ctrl + shift + 3 on my desktop, it zooms everything the fuck in lol
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
Mekasu0124
Mekasu01249mo ago
mhm it's a profile with ctrl + shift + 2
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
Mekasu0124
Mekasu01249mo ago
ok I'm guessing you're not understanding
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
Mekasu0124
Mekasu01249mo ago
my desktop
No description
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
Mekasu0124
Mekasu01249mo ago
if I am on the desktop, and I do the command ctrl + shift + 1, it does this
No description
Mekasu0124
Mekasu01249mo ago
ctrl + shift + 2
No description
Mekasu0124
Mekasu01249mo ago
ctrl + shift + 3 puts it back to normal
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
Mekasu0124
Mekasu01249mo ago
no that's what I was asking you. lol
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
Mekasu0124
Mekasu01249mo ago
yes it does lol ty
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
Mekasu0124
Mekasu01249mo ago
ok cool. sorry on phone with therapist when creating a new table, I want to have a value that holds a boolean.
string sql2 = @"CREATE TABLE IF NOT EXISTS
[goals] (
[Id] INTEGER PRIMARY KEY NOT NULL AUTOINCREMENT,
[Name] VARCHAR(75) NULL,
[DateStarted] VARCHAR(75) NULL,
[DateEnded] VARCHAR(75) NULL<
[TimePerDay] INTEGER,
[Achieved] // boolean here";
string sql2 = @"CREATE TABLE IF NOT EXISTS
[goals] (
[Id] INTEGER PRIMARY KEY NOT NULL AUTOINCREMENT,
[Name] VARCHAR(75) NULL,
[DateStarted] VARCHAR(75) NULL,
[DateEnded] VARCHAR(75) NULL<
[TimePerDay] INTEGER,
[Achieved] // boolean here";
how would I do that using sqlite?
Pobiega
Pobiega9mo ago
Tinyint Sqlite doesn't have bools, it uses 0 and 1
Mekasu0124
Mekasu01249mo ago
I went with a varchar(5) for a yes/no value DateTIme question. When formatting the date time like so
Console.WriteLine($"Current Date: {DateTime.Now.ToString("MM/dd/yyyy - hh:MM")}");
Console.WriteLine($"Current Date: {DateTime.Now.ToString("MM/dd/yyyy - hh:MM")}");
it gives me 04:10pm for my current time, but that's off by 45 minutes. It's currently 4:55pm my time so how do I fix the format so that it always shows my current date time? and also, no matter how many times I run the program, it consistently gives me 4:10 pm every single time. The time isn't changing and that's strange fixed it thank you both for your help small question. Are these the same thing?
// Example 1
using SQLiteConnection conn = new SQLiteConnection(dbFile);
using SQLiteCommand cmd = new SQLiteCommand(conn);

// Example 2
using SQLiteConnection conn = new SQLiteConnection(dbFile);
using SQLiteCommand cmd = conn.CreateCommand();
// Example 1
using SQLiteConnection conn = new SQLiteConnection(dbFile);
using SQLiteCommand cmd = new SQLiteCommand(conn);

// Example 2
using SQLiteConnection conn = new SQLiteConnection(dbFile);
using SQLiteCommand cmd = conn.CreateCommand();
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
Mekasu0124
Mekasu01249mo ago
Ummmm lol I forgot already. System.Data.SQLite I believe
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
Mekasu0124
Mekasu01249mo ago
Oh ok so either way is correct as they’re both the same
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
Mekasu0124
Mekasu01249mo ago
Isn’t that already being done with the using statement? It discards after the call is done?
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
MODiX
MODiX9mo ago
TeBeCo
in both case you'd have to handle the connection lifetime anyway
Quoted by
React with ❌ to remove this embed.
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
Mekasu0124
Mekasu01249mo ago
So how would I go about handling it?
Pobiega
Pobiega9mo ago
use CreateCommand, its the safer option even if by a tiny margin
Mekasu0124
Mekasu01249mo ago
So go with example 2?
Pobiega
Pobiega9mo ago
yes
Mekasu0124
Mekasu01249mo ago
Ok. I’ll give it a shot. Thank you 🥰 so I'm using Stopwatch. I want to get the start time and the end time. I know I can use Elapsed to get the total time, but I want to be able to display the watch's start and end time. I've looked across google, but can't find anything with an example or explanation of how to do so, so how do I do it? Visual Studio won't let me do var start = watch.Start() nvm found a work around
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
Mekasu0124
Mekasu01249mo ago
public static void NewSessionStopWatch()
{
string date = Helpers.GetDate(false);
string today = Helpers.GetDate(true);

Stopwatch watch = new();

Console.Clear();
Console.WriteLine("-----------------------");
Console.WriteLine("Recording A New Session");
Console.WriteLine("-----------------------");

watch.Start();
// get start time here
Console.WriteLine($"\nTimer Started On: {date}");
Console.WriteLine("\nPress SPACEBAR To Stop Timer At Any Time");

do
{
if (Console.ReadKey().Key == ConsoleKey.Spacebar)
{
watch.Stop();
// get end time here
Console.WriteLine($"\nTimer Stopped On: {date}");

CodeSession newSession = new()
{
TodaysDate = today,
StartTime = // start time here => HH:MM:SS,
EndTime = // end time here => HH:MM:SS,
Duration = watch.Elapsed; // formated to HH:MM:SS
}
}
else if (Console.ReadKey().Key != ConsoleKey.Spacebar)
{
Console.WriteLine("\nOnly The Spacebar Will Stop The Session");
}
}
while (!(Console.KeyAvailable));
}
public static void NewSessionStopWatch()
{
string date = Helpers.GetDate(false);
string today = Helpers.GetDate(true);

Stopwatch watch = new();

Console.Clear();
Console.WriteLine("-----------------------");
Console.WriteLine("Recording A New Session");
Console.WriteLine("-----------------------");

watch.Start();
// get start time here
Console.WriteLine($"\nTimer Started On: {date}");
Console.WriteLine("\nPress SPACEBAR To Stop Timer At Any Time");

do
{
if (Console.ReadKey().Key == ConsoleKey.Spacebar)
{
watch.Stop();
// get end time here
Console.WriteLine($"\nTimer Stopped On: {date}");

CodeSession newSession = new()
{
TodaysDate = today,
StartTime = // start time here => HH:MM:SS,
EndTime = // end time here => HH:MM:SS,
Duration = watch.Elapsed; // formated to HH:MM:SS
}
}
else if (Console.ReadKey().Key != ConsoleKey.Spacebar)
{
Console.WriteLine("\nOnly The Spacebar Will Stop The Session");
}
}
while (!(Console.KeyAvailable));
}
the reason I'm wanting to get the start and end time is for the new session after the timer has stopped. I'm trying to write a helper function that can get me the time formatted to hh:mm:ss and return it as a string as the CodeSession class has the variables set to strings except for the Id. I'm just struggling to write the helper function.
Pobiega
Pobiega9mo ago
DateTime and friends have very nifty methods available on them. Such as Add
Mekasu0124
Mekasu01249mo ago
tbh I don't need to use the stop watch itself. I can just use time stamps as I already have a function to calculate the difference between start and end, I just figured stopwatch would be more appropriate in this instance
arion
arion9mo ago
I didn't get to read everything, since i see a ton's been said in the thread already, lmk if its already been addressed or not. But user submitted strings + touching the database is usually not a good idea without some sort of validation.
cmd.Parameters.Add(new SQLiteParameter("@CurrentName", habit.Name));
Pobiega
Pobiega9mo ago
It's parameterized, no SQL injection possible
arion
arion9mo ago
ah gotcha nod only really touched Dapper and EF Core
Mekasu0124
Mekasu01249mo ago
I have validations that happen for everything in the code. It's part of the challenge is preventing the program from failing or stopping due to an error. ok let's say I Have this
DateTime now = DateTime.UtcNow;
TimeZoneInfo systemTimeZone = TimeZoneInfo.Local;
DateTime localDateTime = TimeZoneInfo.ConvertTimeFromUtc(now, systemTimeZone);
DateTime now = DateTime.UtcNow;
TimeZoneInfo systemTimeZone = TimeZoneInfo.Local;
DateTime localDateTime = TimeZoneInfo.ConvertTimeFromUtc(now, systemTimeZone);
which returns 10/4/2023 2:21:33 what would be the best way to format the return information into two variables, date and time, since ToString doesn't have an overload for formatting? I've been working with this in a playground, and although I know I can use .ToString("MM/dd/yyyy"); and .ToString(@"hh\:mm\:ss");, I do recall Pobiega saying that .ToString(); doesn't have an overload for formatting like that
MODiX
MODiX9mo ago
arion
REPL Result: Success
var now = DateTime.UtcNow;
var systemTimeZone = TimeZoneInfo.Local;
var localDateTime = TimeZoneInfo.ConvertTimeFromUtc(now, systemTimeZone);
localDateTime.ToString("hh:mm:ss")
var now = DateTime.UtcNow;
var systemTimeZone = TimeZoneInfo.Local;
var localDateTime = TimeZoneInfo.ConvertTimeFromUtc(now, systemTimeZone);
localDateTime.ToString("hh:mm:ss")
Result: string
07:30:32
07:30:32
Compile: 534.070ms | Execution: 35.404ms | React with ❌ to remove this embed.
arion
arion9mo ago
Adding an escape returns the same result (ToString(@"hh\:mm\:ss"))
Mekasu0124
Mekasu01249mo ago
so just use .ToString()
arion
arion9mo ago
Just .ToString() would return 4/10/23 7:30:06 PM
Pobiega
Pobiega9mo ago
no that was for when you did string.Format("hh/mm") == input 😄
Mekasu0124
Mekasu01249mo ago
yea I went back and looked and saw that. that's my bad
Pobiega
Pobiega9mo ago
it cant do that. but it can certainly format datetimes etc because each type owns its own implementation of ToString
MODiX
MODiX9mo ago
Mekasu0124
REPL Result: Success
using System.Globalization;

DateTime now = DateTime.UtcNow;
TimeZoneInfo systemTimeZone = TimeZoneInfo.Local;
DateTime localDateTime = TimeZoneInfo.ConvertTimeFromUtc(now, systemTimeZone);

CultureInfo provider = CultureInfo.InvariantCulture;
DateTimeStyles style = DateTimeStyles.None;

string formatDate = "MM/dd/yyyy";
string date = localDateTime.ToString(formatDate);

string formatTime = @"hh\:mm\:ss";
string time = localDateTime.ToString(formatTime);

Console.WriteLine("Current UTC Date: {0}", now);
Console.WriteLine("Current System Time Zone: {0}", systemTimeZone);
Console.WriteLine("Converted Local Date Time: {0}", localDateTime);
Console.WriteLine("Date Format: {0}", formatDate);
Console.WriteLine("Formatted Date: {0}", date);
Console.WriteLine("Time Format: {0}", formatTime);
Console.WriteLine("Formatted Time: {0}", time);
using System.Globalization;

DateTime now = DateTime.UtcNow;
TimeZoneInfo systemTimeZone = TimeZoneInfo.Local;
DateTime localDateTime = TimeZoneInfo.ConvertTimeFromUtc(now, systemTimeZone);

CultureInfo provider = CultureInfo.InvariantCulture;
DateTimeStyles style = DateTimeStyles.None;

string formatDate = "MM/dd/yyyy";
string date = localDateTime.ToString(formatDate);

string formatTime = @"hh\:mm\:ss";
string time = localDateTime.ToString(formatTime);

Console.WriteLine("Current UTC Date: {0}", now);
Console.WriteLine("Current System Time Zone: {0}", systemTimeZone);
Console.WriteLine("Converted Local Date Time: {0}", localDateTime);
Console.WriteLine("Date Format: {0}", formatDate);
Console.WriteLine("Formatted Date: {0}", date);
Console.WriteLine("Time Format: {0}", formatTime);
Console.WriteLine("Formatted Time: {0}", time);
Console Output
Current UTC Date: 10/04/2023 19:36:00
Current System Time Zone: (UTC) Coordinated Universal Time
Converted Local Date Time: 10/04/2023 19:36:00
Date Format: MM/dd/yyyy
Formatted Date: 10/04/2023
Time Format: hh\:mm\:ss
Formatted Time: 07:36:00
Current UTC Date: 10/04/2023 19:36:00
Current System Time Zone: (UTC) Coordinated Universal Time
Converted Local Date Time: 10/04/2023 19:36:00
Date Format: MM/dd/yyyy
Formatted Date: 10/04/2023
Time Format: hh\:mm\:ss
Formatted Time: 07:36:00
Compile: 526.881ms | Execution: 35.952ms | React with ❌ to remove this embed.
Mekasu0124
Mekasu01249mo ago
so this is what I've got is this the best/efficient practice?
arion
arion9mo ago
DateTime now = DateTime.UtcNow;
TimeZoneInfo systemTimeZone = TimeZoneInfo.Local;
DateTime localDateTime = TimeZoneInfo.ConvertTimeFromUtc(now, systemTimeZone);
DateTime now = DateTime.UtcNow;
TimeZoneInfo systemTimeZone = TimeZoneInfo.Local;
DateTime localDateTime = TimeZoneInfo.ConvertTimeFromUtc(now, systemTimeZone);
regarding this
DateTime.Now
DateTime.Now
exists
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
MODiX
MODiX9mo ago
TeBeCo
REPL Result: Success
DateTimeOffset.Now.ToString("u")
DateTimeOffset.Now.ToString("u")
Result: string
2023-10-04 19:39:56Z
2023-10-04 19:39:56Z
Compile: 469.202ms | Execution: 39.524ms | React with ❌ to remove this embed.
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
Mekasu0124
Mekasu01249mo ago
why is it so important that I don't use DateTime but use DateTimeOffset instead?
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
MODiX
MODiX9mo ago
please please please get into the habit of using DateTimeOffset instead of DateTime in your code everywhere you possibly can. DateTimeOffset contains the UTC offset with the data so is lossless. DateTime is very very weird in how it stores data. DateTime only knows UTC and "local" time. But your local time zone can change! Laptops easily move across state lines, even while an app is currently running. (So you are in California running an app, put some DateTime instance in memory, hop on a plane to New York, then resume your app 3 time zones ahead. What on earth will be contained within the DateTime instance?) But wait, this was a lie. DateTime actually has 3 ways it keeps track of time: UTC, local (which can change while an app is running), and unspecified (unknown, essentially). (Unknown = I don't know if it's UTC or local, the app will figure it out later and call ToUniversal or ToLocal before calling ToString or any comparison routine.) But wait, this was a lie. DateTime actually has a secret fourth way of storing data that's not exposed in the standard API surface! It's truly an abomination of a type. All of this nonsense is irrelevant if we just pretend DateTime doesn't exist and we instead use DateTimeOffset everywhere.
- GrabYourPitchforks (start: https://discord.com/channels/143867839282020352/143867839282020352/988353756108312607)
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
Mekasu0124
Mekasu01249mo ago
so then I'm assuming that I need to use TimeSpanOffset instead of TimeSpan
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
Pobiega
Pobiega9mo ago
10 hours is 10 hours 🙂
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
Pobiega
Pobiega9mo ago
but "the first of april 2017" is different for you and me
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
Mekasu0124
Mekasu01249mo ago
didn't get a chance to read it, but what parts I did read didn't make sense to me as it's code I've never used
arion
arion9mo ago
I flew across the world from west coast to east coast, no time passed when
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
Pobiega
Pobiega9mo ago
You don't truly need to fully understand why, just know that DateTimeOffset is the modern, non-problematic version of DateTime we prefer one over the other
Mekasu0124
Mekasu01249mo ago
public static string GetDate(bool formatted)
{
if (formatted)
{
DateTimeOffset now = DateTimeOffset.UtcNow;
TimeZoneInfo systemTimeZone = TimeZoneInfo.Local;
DateTimeOffset localDateTime = TimeZoneInfo.ConvertTimeFromUtc(now, systemTimeZone);

return localDateTime.ToString("MM/dd/yyyy");
}
else
{
DateTimeOffset now = DateTimeOffset.UtcNow;
TimeZoneInfo timeZone = TimeZoneInfo.Local;
DateTimeOffset localDateTime = TimeZoneInfo.ConvertTimeFromUtc(now, timeZone);
return localDateTime.ToString();
}
}
public static string GetDate(bool formatted)
{
if (formatted)
{
DateTimeOffset now = DateTimeOffset.UtcNow;
TimeZoneInfo systemTimeZone = TimeZoneInfo.Local;
DateTimeOffset localDateTime = TimeZoneInfo.ConvertTimeFromUtc(now, systemTimeZone);

return localDateTime.ToString("MM/dd/yyyy");
}
else
{
DateTimeOffset now = DateTimeOffset.UtcNow;
TimeZoneInfo timeZone = TimeZoneInfo.Local;
DateTimeOffset localDateTime = TimeZoneInfo.ConvertTimeFromUtc(now, timeZone);
return localDateTime.ToString();
}
}
well now I'm just more confused than ever, but it's whatever honestly. Switching to DateTimeOffset has caused this function to error on both conversions. I have no idea how to fix it. Cannot convert from DateTImeOffset to DateTime so there's that. besides that, I just need a helper function to return the current time so that I can finish the other function that I've been working on
Pobiega
Pobiega9mo ago
thats because you were compensating for how garbage DateTIme is before and with DateTimeOffset, you don't need to you JUST need return DateTimeOffset.Now.ToString("MM/dd/yyyy");
Mekasu0124
Mekasu01249mo ago
thanks. that also helped with my helper function for getting the time.
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
Mekasu0124
Mekasu01249mo ago
yes I'm aware. That's why I said thanks
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
MODiX
MODiX9mo ago
TeBeCo
REPL Result: Failure
DateTimeOffset.Now.ToString(null);
DateTimeOffset.Now.ToString(null);
Exception: CompilationErrorException
- The call is ambiguous between the following methods or properties: 'DateTimeOffset.ToString(string?)' and 'DateTimeOffset.ToString(IFormatProvider?)'
- The call is ambiguous between the following methods or properties: 'DateTimeOffset.ToString(string?)' and 'DateTimeOffset.ToString(IFormatProvider?)'
Compile: 468.118ms | Execution: 0.000ms | React with ❌ to remove this embed.
MODiX
MODiX9mo ago
TeBeCo
REPL Result: Success
DateTimeOffset.Now.ToString("")
DateTimeOffset.Now.ToString("")
Result: string
10/04/2023 20:03:20 +00:00
10/04/2023 20:03:20 +00:00
Compile: 447.940ms | Execution: 29.337ms | React with ❌ to remove this embed.
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
Mekasu0124
Mekasu01249mo ago
?
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
Mekasu0124
Mekasu01249mo ago
I don't know. I don't like, or use, ternary operators
Pobiega
Pobiega9mo ago
lol That is such a mekasu statement.
Mekasu0124
Mekasu01249mo ago
what's wrong with me not liking ternary operators 😐
Pobiega
Pobiega9mo ago
its a bit like saying "I don't like hammers. So I use screwdrivers instead" an if statement is a statement. a ternary is an expression so they are actually different, and you cant use statements everywhere like in Expression<Func<T>> chains what I mean is that its perfectly fine to "not like" them for now, but eventually you'll need to get over that and learn to use them where they make sense.
Mekasu0124
Mekasu01249mo ago
To clarify, I know how to use them. I responded like I did, not because of the person or trying to help, but because I just don't like them and don't want to use them. I've had to use them periodically in my Python code as well, and I just dislike them because I like to keep my code sections separate for easier debugging and working with on my end. Ternary lines just annoy me because all of my code blocks are in a single line and although I understand that they're better in certain use cases, it annoys me when it comes to debugging. It's hard for me to explain honestly, but I get your point
Pobiega
Pobiega9mo ago
I write mine like
isTrue
? one
: two;
isTrue
? one
: two;
makes it nice and easy to read 🙂
Mekasu0124
Mekasu01249mo ago
i changed it
Unknown User
Unknown User9mo ago
Message Not Public
Sign In & Join Server To View
Mekasu0124
Mekasu01249mo ago
I can see how that helps to keep the conditions separate as well instead of an if statement but I am curious about something
bool conditionCheck = CheckSomeCondition();
if (condition == true)
{
Console.WriteLine("Condition True");
Console.WriteLine("Some other yielded results");
}
else
{
Console.WriteLine("[Error] Condition False");
MainMenu.ShowMenu();
}
bool conditionCheck = CheckSomeCondition();
if (condition == true)
{
Console.WriteLine("Condition True");
Console.WriteLine("Some other yielded results");
}
else
{
Console.WriteLine("[Error] Condition False");
MainMenu.ShowMenu();
}
when you have an if/else statement where both code blocks have multiple items in them, would it be more efficient to leave them as they are, or can they be turned ternary? I've tried to one-line something like this the other day when we were talking about this, but couldn't figure it out. I imagined it was something like
conditionCheck ? Console.WriteLine("Condition True"); Console.WriteLine("Some other yielded results"); : Console.WriteLine("[Error] Condition False"); MainMenu.ShowMenu();
conditionCheck ? Console.WriteLine("Condition True"); Console.WriteLine("Some other yielded results"); : Console.WriteLine("[Error] Condition False"); MainMenu.ShowMenu();
but I couldn't get it to work eith if/else statements that have code blocks with at least 2 lines of code in each and return a value. I've only been able to get them to work like
return conditionCheck ? Console.WriteLine("Condition True"); : MainMenu.ShowMenu();
return conditionCheck ? Console.WriteLine("Condition True"); : MainMenu.ShowMenu();
Pobiega
Pobiega9mo ago
ternaries are expressions, so you can only have one thing in each branch, and that thing must be something that returns something they are not a replacement for if-statements so this code would be written as is, except perhaps inlining the condition and without the recursion :p
Mekasu0124
Mekasu01249mo ago
what recursion? I didn't do that in the example I don't think? and ok I got you. makes sense
Pobiega
Pobiega9mo ago
MainMenu.ShowMenu(); smells like recursion to me, but it was just a guess :p
Mekasu0124
Mekasu01249mo ago
It's calling the main menu when the current process is done.
Pobiega
Pobiega9mo ago
but only on failure thou, in that case which is why I assumed recursion as your "reset" and thats an anti pattern, you should just use a loop instead. recursion builds up the call stack
Mekasu0124
Mekasu01249mo ago
ok I'll look at it later. I have to go take a midterm. I'll be back
Pobiega
Pobiega9mo ago
good luck
Want results from more Discord servers?
Add your server
More Posts