Wie stellen Sie grundlegende Verbindungen ohne diesen Fehler her?C#

Ein Treffpunkt für C#-Programmierer
Anonymous
 Wie stellen Sie grundlegende Verbindungen ohne diesen Fehler her?

Post by Anonymous »

howtoSolve < /h1>
Allgemeines Handbuch < /h2>
Projektverzeichnis im Terminal erstellen < /h3>

Code: Select all

mkdir "Project name"
cd "Project name"

mkdir backend
mkdir "subdirectory2"
mkdir "subdirectory3"
< /code>
[h4] Nützliche Webseiten < /h4>

[*] Stackoverflow < /li>
 w3schools < /li>
 Bootstrap < /li> < /> < />
 VSC -Ausstreckungen: < /h4>

 vscs: < /h4>

 vscs: < /h4>

 vscs: < /h4>

 vscs: < /h4>

 vscs: < /h4>

 vscs: < /h4>

 vscs: < /h4>

 vsc. />  Easyzoom < /li>
 Live -Server < /li>
 Thunder Client < /li>
 automatisch umbenennen. C: \ xampp \ mysql \ backup 
[*] Drücken Sie Strg + x Um die Inhalte zu schneiden
[*] Navigieren Sie zu: c: \ xampp \ mysql \ data
[*] c/> c/> c/> c/> c/> cll + a [*] Einfügen

Desktop
Ziel Finish-Zeit: ~ 1H 25min
Klassen und Konstruktoren
class Person
{
public int id { get; set; }
public double average { get; set; }
public string name { get; set; }
public DateTime date { get; set; }

public Person(int id, double average, string name, DateTime date)
{
this.id = id;
this.average = average;
this.name = name;
this.date = date;
}
}
< /code>
Textmanipulation < /h3>

Code: Select all

Replace(',','-');  // 2019-2-12
Trim('-');  // 2019212
Split(',');  // {apple, banana, orange}
Contains("YES") // returns true

char[] nameArray = {'A', 'l', 'i', 'c', 'e'};
string name = new string(nameArray);

Math.Round(number, 2)); // 5.43529 -> 5.44 (Honorable mention: Floor(), Ceiling())
< /code>
 Lesen einer Datei < /h3>
using System.IO;
< /code>
List peopleList = new List();

using (StreamReader sr = new StreamReader("filename.txt"))
{
while (!sr.EndOfStream)
{
string line = sr.ReadLine();
string[] data = line.Split(';');
int id = int.Parse(data[0]);
data[1] = data[1].Replace(',', '.');
double atlag = double.Parse(data[1]);
string name = data[2];
DateTime date = Convert.ToDateTime(data[3]);
Person person = new Person(id, average, name, date);
peopleList.Add(person);
}
}
< /code>
 Erstellen einer Datei < /h3>
using (StreamWriter sw = File.CreateText("filename.txt"))
{
sw.WriteLine("...");
}
< /code>
 linq Beispiele < /h3>
using System.Linq;
< /code>
foreach (var group in groupedByYear)
{
Console.WriteLine($"Year: {group.Year}");
foreach (var person in group.People)
{
Console.WriteLine($"- {person.Name}");
}
}
< /code>
 1. Aggregation (Anzahl, Summe, Durchschnitt, max, min) < /h4>
Statistik berechnen.int count = people.Count(); // Total people
int over30Count = people.Count(p => p.Age > 30); // People over 30
double totalSalary = people.Sum(p => p.Salary); // Total salary
double avgSalary = people.Average(p => p.Salary); // Average salary
int maxAge = people.Max(p => p.Age); // Oldest age
< /code>
 2. Filterung (wo) < /h4>
Wählen Sie Personen, die älter als 25 Jahre alt sind.var olderThan25 = people.Where(p => p.Age > 25);
< /code>
 3. Sortieren (orderby, thenby) < /h4>
Sortieren Sie Personen nach Alter, dann nach Namen.var sortedPeople = people.OrderBy(p => p.Age).ThenBy(p => p.Name);
< /code>
 4.  Auswählen spezifischer Felder (auswählen) < /h4>
eine Liste von Namen und Gehältern abrufen.var namesAndSalaries = people.Select(p => new { p.Name, p.Salary });
< /code>
 5. Gruppierung (GroupBy) < /h4>
Gruppenpersonen nach Alter.var groupedByAge = people.GroupBy(p => p.Age).Select(g => new { Age = g.Key, People = g });
< /code>
 6. Erstens zuletzt einzeln < /h4>
bestimmte Elemente abrufen.Person firstPerson = people.First(); // First person
Person lastPerson = people.Last(); // Last person
Person singlePerson = people.Single(p => p.Id == 1); // Person with Id 1
< /code>
 7. Alle und alle < /h4>
Überprüfen Sie die Bedingungen.bool hasYoung = people.Any(p => p.Age < 25); // True if any person is under 25
bool allHighEarners = people.All(p => p.Salary > 40000); // True if all earn > 40k
< /code>
 Tipps für effektives linq < /h4>

 [b] Leistung < /strong>: [url=viewtopic.php?t=15143]Vermeiden[/url] Sie mehrere Aufzählungen; Ergebnisse mit .tolist () 
falls erforderlich. Express
installiert die erforderlichen Pakete im Backend-Ordner und erstellt app.js/index.js-Datei mit grundlegendem Inhalt [/h4]

Code: Select all

cd backend
npm install express mysql2 cors
npm pkg set type=module
cd backend
echo "import express from 'express';" > app.js
echo "import cors from 'cors';" >> app.js
echo "import mysql from 'mysql2';" >> app.js
echo "" >> app.js
echo "const app = express();" >> app.js
echo "app.use(cors());" >> app.js
echo "app.use(express.json());" >> app.js
echo "" >> app.js
echo "const db = mysql.createConnection({" >> app.js
echo "    host: 'localhost'," >> app.js
echo "    user: 'root'," >> app.js
echo "    password: ''," >> app.js
echo "    database: '', // Database name goes here" >> app.js
echo "    port: 3306" >> app.js
echo "});" >> app.js
echo "" >> app.js
echo "// endpoints" >> app.js
echo "" >> app.js
echo "app.listen(3000, () => {" >> app.js
echo "    console.log('Server is running on http://localhost:3000');" >> app.js
echo "});" >> app.js
< /code>
 Endpunkte < /h3>
import express from "express";
import mysql from "mysql2";
import cors from "cors";

const app = express();
const port = 3000;

app.use(express.json());
app.use(cors());

const db = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "namedays",
});

// API endpoint to get nameday by date
app.get("/api/nameday/", (req, res) => {
// Extract "date" from query parameter
const date = req.query.date; // KEY

// Check if date is specified
if (!date) {
return res.status(400).json({ error: "Date parameter is required" });
}

// get the month and day
const month = date.split("-")[0];
const monthName = convertMonthNumberToName(month);
const day = date.split("-")[1];
const sql = SELECT name1, name2 FROM nameday WHERE month = ${month} AND day = ${day};

db.query(sql, (err, result) => {
if (err) {
console.log("Server error");
}
if (result.length === 0) {
console.log("No nameday found");
}
const nameday = result[0];

// Send response with formatted date and nameday data
res.json({ // KEY
date: `${monthName} ${day}.`,
name1: nameday.name1,
name2: nameday.name2,
});
});
});

// Function to convert month number to month name
function convertMonthNumberToName(monthNumber) {
switch (monthNumber) {
case "1":
return "January";
case "2":
return "February";
...
}
}

// Delete data by ID
app.delete("/api/nameday/:id", async (req, res)=>{
const id = req.params.id; // Extracts the ID from the URL parameter, e.g., /api/nameday/123
const sql = "DELETE FROM nameday WHERE id = ?";
const [result] = await database.execute(sql, [id]);
res.status(200).json(result);
})

app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});

Frontend
Ziel-Endzeit: ~ 1H 30min [/b]
stootstrap import

Code: Select all

< /code>
 Anzeige und Senden von Karten dynamisch mit Bootstrap < /h3>
  



Select Date:


Get Nameday





// Place for the cards


// Handle form submission
document.getElementById('dateForm').addEventListener('submit', async (e) => {
e.preventDefault();
const date = document.getElementById('dateInput').value;
if (!date) return;

// Clear previous cards
const cardContainer = document.getElementById('namedayCards');
cardContainer.innerHTML = '';

// Fetch data from API
try {
const response = await fetch(`http://localhost:3000/api/nameday/?date=${date}`);
if (!response.ok) {
throw new Error('Failed to fetch nameday data');
}
const data = await response.json();

// Check for error response
if (data.error) {
cardContainer.innerHTML = `${data.error}`;
return;
}

// Create Bootstrap cards for each name
const names = [data.name1, data.name2];
names.forEach(name => {
const card = document.createElement('div');
card.className = 'col';
card.innerHTML = `


${name}
Nameday on ${data.date}


`;
cardContainer.appendChild(card);
});
} catch (error) {
console.error('Error:', error);
cardContainer.innerHTML = `Error fetching data`;
}
});

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post