|
You need to deserialize the existing file contents, and overwrite the entire file. If you just serialize the new users and append it to the file, you'll end up with multiple XML documents in a single file, which is not valid.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Take a look at your Serialization method. Why are you creating a new list of Users, adding one user to it, and then overwriting the file you already have?
Method should do one thing and only one thing. Your Serialization method is not responsible for creating a list of users and adding users to it. It should be renamed SerializeUsersToFile and do only that job.
Maintaining a list of users should be done by your Users class. It should expose methods for adding and removing them.
Another class can be created that handles Serializing and Deserializing a Users class to the file. When you want to update the file, you call the SerializeUsersToFile method and pass the Users object to it. When you want the users to be loaded from the file, you call another method, DeserializeUsersFromFile, and it should return a populated Users object.
|
|
|
|
|
To add to what the others have said, I'd suggest that you read this: That's not a database, dude![^] XML is a transfer format, not a data storage format.
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
"Common sense is so rare these days, it should be classified as a super power" - Random T-shirt
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
Please help make this code work. I'm trying to run it in Visual Studio 2022. Thanks.
<pre lang="C#">
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Numpy;
using Python.Runtime;
using Keras;
using Keras.Layers;
using Keras.Models;
using Keras.Optimizers;
using Keras.losses;
namespace SQLInjectionDetection
{
class Program
{
static void Main(string[] args)
{
var trainData = File.ReadAllLines("tokens.csv")
.Select(l => l.Split(','))
.Select(s => new { Token = s[0], Label = int.Parse(s[1]) })
.ToList();
var random = new Random();
trainData = trainData.OrderBy(d => random.Next()).ToList();
var splitIndex = (int)(trainData.Count * 0.8);
var trainDataSubset = trainData.Take(splitIndex).ToList();
var testDataSubset = trainData.Skip(splitIndex).ToList();
var vocabulary = new HashSet<char>(trainDataSubset.SelectMany(d => d.Token).Distinct());
var tokenToIndex = vocabulary.Select((c, i) => new { Token = c, Index = i }).ToDictionary(t => t.Token, t => t.Index);
var maxSequenceLength = trainDataSubset.Max(d => d.Token.Length);
var trainTokenized = Tokenize(trainDataSubset, tokenToIndex, maxSequenceLength);
var testTokenized = Tokenize(testDataSubset, tokenToIndex, maxSequenceLength);
using (Py.GIL())
{
dynamic keras = Py.Import("keras");
dynamic np = Py.Import("numpy");
var input = new Input(shape: 1000);
var embedding = new Embedding(vocabulary.Count, 32).Apply(input);
var lstm = new LSTM(32).Apply(embedding);
var output = new Dense(1, activation: keras.activations.sigmoid).Apply(lstm);
var model = new Model(inputs: input, outputs: output);
model.Compile(optimizer: new Adam(), loss: new BinaryCrossentropy(), metrics: new[] { "accuracy" });
var trainX = trainTokenized.Item1;
var trainY = trainTokenized.Item2;
var testX = testTokenized.Item1;
var testY = testTokenized.Item2;
model.Fit(trainX, trainY, batchSize: 32, epochs: 10, validationData: (testX, testY));
Console.Write("Enter user input: ");
var userInput = Console.ReadLine();
var inputTokenized = TokenizeInput(userInput, tokenToIndex, maxSequenceLength);
var prediction = model.Predict(inputTokenized).GetData<float>()[0, 0];
Console.WriteLine($"Prediction: {(prediction > 0.5 ? "Malicious" : "Safe")} (Score: {prediction:F4})");
var testMetrics = model.Evaluate(testX, testY);
Console.WriteLine($"Test loss: {testMetrics[0]:F4}");
Console.WriteLine($"Test accuracy: {testMetrics[1]:F4}");
}
}
private static (NDarray, NDarray) Tokenize(List<dynamic> data, Dictionary<char, int> tokenToIndex, int maxSequenceLength)
{
var numExamples = data.Count;
var X = np.zeros((numExamples, maxSequenceLength));
var Y = np.zeros((numExamples, 1));
for (var i = 0; i < numExamples; i++)
{
var tokens = data[i].Token;
var label = data[i].Label;
Y[i] = label;
for (var j = 0; j < tokens.Length; j++)
{
var token = tokens[j];
var index = tokenToIndex[token];
X[i, j] = index;
}
}
return (X, Y);
}
}
}
|
|
|
|
|
We have no idea what it is fully supposed to do, or what it does that you didn't expect / doesn't do that you did. And we have no access to your data so we couldn't test it if we wanted to.
So, it's going to be up to you.
Fortunately, you have a tool available to you which will help you find out what is going on: the debugger. If you don't know how to use it then a quick Google for "Visual Studio debugger" should give you the info you need.
Put a breakpoint on the first line in the function, and run your code through the debugger. Then look at your code, and at your data and work out what should happen manually. Then single step each line checking that what you expected to happen is exactly what did. When it isn't, that's when you have a problem, and you can back-track (or run it again and look more closely) to find out why.
Sorry, but we can't do that for you - time for you to learn a new (and very, very useful) skill: debugging!
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
"Common sense is so rare these days, it should be classified as a super power" - Random T-shirt
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
Hello, I just started working with NAudio with the hope that it will provide the required MIDI and audio routines for a personal project I am working on. I have been programming since 1980 but basically stopped for several decades until I recently retired from Engineering. I have attempted an initial small app with NAudio in .netMAUI but it is not working. I used the following link (http://truelogic.org/wordpress/2021/01/28/using-midi-with-naudio/) to input a small console app based upon the creators description of the midi capabilities. This worked great. I then tried to make it into a MAUI app. The devices are found but it never passes into the "midiIn_MessageReceived" function??
The project can be found at https://github.com/handysharp/Maui-NAudio.
Can you think of any reason why this simple app would not be picking up the keyboard midi messages. The setup works, as it runs great with the console app.
TIA
Dave Handy
|
|
|
|
|
I think mating Naudio (".Net") and Maui (cross-platform) would be considered a kludge when "native" audio controls are available.
Dave's Tech Blog: Playing audio with .NET MAUI
"Before entering on an understanding, I have meditated for a long time, and have foreseen what might happen. It is not genius which reveals to me suddenly, secretly, what I have to say or to do in a circumstance unexpected by other people; it is reflection, it is meditation." - Napoleon I
|
|
|
|
|
Thx Gerry, forgive my ignorance but I am new to all of this .Net, Maui, UI3, etc. I would really like to do the prog in C# with .Net MAUI because I have devoted the most learning time to them...seemed to be the best way to go at the time. What "native" audio controls do you speak of???
|
|
|
|
|
Also, kludge, great word. Just looked it up.
|
|
|
|
|
Quote: Android has MediaPlayer, iOS/Mac Catalyst has AVPlayer, and WinUI has MediaPlayerElement (only available in WinAppSDK 1.2-preview).
"Before entering on an understanding, I have meditated for a long time, and have foreseen what might happen. It is not genius which reveals to me suddenly, secretly, what I have to say or to do in a circumstance unexpected by other people; it is reflection, it is meditation." - Napoleon I
|
|
|
|
|
i am doing an application of online examination system and i want to design the test page that contain count down timer and when time is end expired time is showhing
thanks
|
|
|
|
|
And?
What have you tried?
Where are you stuck?
What help do you need?
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
"Common sense is so rare these days, it should be classified as a super power" - Random T-shirt
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
Member 15923846 wrote: online examination system
Then you will not be doing it in C#. At least not the UI part.
I suppose a true formal testing system would need to retrieve the time from a server and show that. But for a simple system you can probably find something in javascript that does that.
|
|
|
|
|
What is the difference between the following, or is there anything?
public async Task SomeFunc()
{
await Task.Run(() =>
{
var reader = com.ExecuteReader();
...
}
}
public async Task SomeFunc()
{
var reader = await com.ExecuteReaderAsync();
....
}
|
|
|
|
|
Quite a significant difference.
In the first example, you essentially spin up a new thread, block that thread waiting for a synchronous network call to complete, and sign up the calling thread to be notified when the new thread completes. Whilst it may sometimes be useful for keeping a desktop UI responsive, it's not great for performance.
In the second example, you kick off an asynchronous network call, and sign up the calling thread to be notified when that call completes. That's a much more efficient approach.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
|
Greetings experts,
The following is a linq to sql code that I am trying to convert to for lack of a better work, regular .net framework code:
protected void updateSal_Click(object sender, EventArgs e)
{
newTotal.Text = theLinq.Salary.Single(s => s.Salary_Year == DateTime.Now.Year).Total_Salary.ToString();
}
'//This is my attempted conversion to vb.net
Protected Sub updateSal_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim rowsAffected As Integer
Dim currYear As Integer = Date.Now.Year
Using con As New SqlConnection("server=.;database=Test;integrated security=true")
Using cmd As New SqlCommand("UPDATE Salary Set Total_Salary=@totsal WHERE Salary_Year = @currentYear", con)
cmd.Parameters.Add("@totsal", SqlDbType.Decimal).Value = newTotal.Text
cmd.Parameters.Add("@currentYear", SqlDbType.Integer).Value = currYear
con.Open()
rowsAffected = cmd.ExecuteNonQuery()
End Using
End Using
End Sub
My result is coming up empty even though the update code works when I run it in SSMS.
Am I doing the conversion incorrectly.
modified 9-Feb-23 0:23am.
|
|
|
|
|
The LINQ code is not an UPDATE query. It's a SELECT, and one that doesn't make much sense.
The LINQ query is selecting a single record from a possible list of records where Salary_Year matches the current year. The returned record better have a Total_Salary field to return a string for.
|
|
|
|
|
WOW!
But you can understand why I was confused.
The method says Update(...)
Thank you.
|
|
|
|
|
The thing is, what is the method updating? In this case, it looks like it's updating the UI, not the database.
|
|
|
|
|
Thank you so very much Dave for the prompt response.
|
|
|
|
|
samflex wrote: The method says Update(...) No, it says updateSal_Click(object sender, EventArgs e) , which is clearly an event handler that is called when the user clicks a button or other control. And the result of the LINQ query is returned in the Text field of the newTotal item, which is most likely a field on the form.
|
|
|
|
|
i advised an article writer (newbie), here, that his use of the above syntax is not a good programming practice.
my thought is why would you have a potentially 'newable class (since it gets a default constructor) where calling 'new meant a "useless" instance.
thinking that over ... given VS and ReSharper don't flag that ,,, i lean towards thinking maybe during development: who cares, as long as it compiles; you might want to add 'public stuff later, but, for production code, that is a code smell.
i have never used that syntax, and never put a static class in a public class, either.
your thoughts ?
«The mind is not a vessel to be filled but a fire to be kindled» Plutarch
modified 8-Feb-23 20:13pm.
|
|
|
|
|
My feeling is that overuse of static generally means they don't understand OOPs properly - it's often a "it worked in C" approach to an app rather than using objects to avoid unnecessary globals (both methods and variables)
If he's a coding newbie, it's likely that his tutor grew up in a procedural environment and has just learned the syntax of an OOPs language rather the principles behind it.
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
"Common sense is so rare these days, it should be classified as a super power" - Random T-shirt
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
I don't see the point of creating a singleton when there is a class that will never be a component of anything else. My apps usually have some sort of "data repository" in memory that needs to be accessed from all over the app; a static class is supremely convenient in this case. "Static" doesn't define the data; it only defines the "references". They could all be observable collections with different subscribers. Dependency injection in this case is obsessing (IMO).
"Before entering on an understanding, I have meditated for a long time, and have foreseen what might happen. It is not genius which reveals to me suddenly, secretly, what I have to say or to do in a circumstance unexpected by other people; it is reflection, it is meditation." - Napoleon I
|
|
|
|
|