diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..96fd954 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,35 @@ +{ + "version": "0.2.0", + "configurations": [ + { + // Use IntelliSense to find out which attributes exist for C# debugging + // Use hover for the description of the existing attributes + // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md + "name": ".NET Core Launch (web)", + "type": "coreclr", + "request": "launch", + "preLaunchTask": "build", + // If you have changed target frameworks, make sure to update the program path. + "program": "${workspaceFolder}/bin/Debug/net7.0/LiveChat.dll", + "args": [], + "cwd": "${workspaceFolder}", + "stopAtEntry": false, + // Enable launching a web browser when ASP.NET Core starts. For more information: https://aka.ms/VSCode-CS-LaunchJson-WebBrowser + "serverReadyAction": { + "action": "openExternally", + "pattern": "\\bNow listening on:\\s+(https?://\\S+)" + }, + "env": { + "ASPNETCORE_ENVIRONMENT": "Development" + }, + "sourceFileMap": { + "/Views": "${workspaceFolder}/Views" + } + }, + { + "name": ".NET Core Attach", + "type": "coreclr", + "request": "attach" + } + ] +} \ No newline at end of file diff --git a/.vscode/tasks.json b/.vscode/tasks.json new file mode 100644 index 0000000..5352df8 --- /dev/null +++ b/.vscode/tasks.json @@ -0,0 +1,41 @@ +{ + "version": "2.0.0", + "tasks": [ + { + "label": "build", + "command": "dotnet", + "type": "process", + "args": [ + "build", + "${workspaceFolder}/LiveChat.csproj", + "/property:GenerateFullPaths=true", + "/consoleloggerparameters:NoSummary" + ], + "problemMatcher": "$msCompile" + }, + { + "label": "publish", + "command": "dotnet", + "type": "process", + "args": [ + "publish", + "${workspaceFolder}/LiveChat.csproj", + "/property:GenerateFullPaths=true", + "/consoleloggerparameters:NoSummary" + ], + "problemMatcher": "$msCompile" + }, + { + "label": "watch", + "command": "dotnet", + "type": "process", + "args": [ + "watch", + "run", + "--project", + "${workspaceFolder}/LiveChat.csproj" + ], + "problemMatcher": "$msCompile" + } + ] +} \ No newline at end of file diff --git a/App.razor b/App.razor index 6fd3ed1..34eb49d 100644 --- a/App.razor +++ b/App.razor @@ -6,7 +6,7 @@ Not found -

Sorry, there's nothing at this address.

+
diff --git a/Data/WeatherForecast.cs b/Data/WeatherForecast.cs deleted file mode 100644 index 59137c3..0000000 --- a/Data/WeatherForecast.cs +++ /dev/null @@ -1,13 +0,0 @@ -namespace LiveChat.Data -{ - public class WeatherForecast - { - public DateOnly Date { get; set; } - - public int TemperatureC { get; set; } - - public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); - - public string? Summary { get; set; } - } -} \ No newline at end of file diff --git a/Data/WeatherForecastService.cs b/Data/WeatherForecastService.cs deleted file mode 100644 index d1422a4..0000000 --- a/Data/WeatherForecastService.cs +++ /dev/null @@ -1,20 +0,0 @@ -namespace LiveChat.Data -{ - public class WeatherForecastService - { - private static readonly string[] Summaries = new[] - { - "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" - }; - - public Task GetForecastAsync(DateOnly startDate) - { - return Task.FromResult(Enumerable.Range(1, 5).Select(index => new WeatherForecast - { - Date = startDate.AddDays(index), - TemperatureC = Random.Shared.Next(-20, 55), - Summary = Summaries[Random.Shared.Next(Summaries.Length)] - }).ToArray()); - } - } -} \ No newline at end of file diff --git a/Hubs/ChatHub.cs b/Hubs/ChatHub.cs index b7f0526..b26866d 100644 --- a/Hubs/ChatHub.cs +++ b/Hubs/ChatHub.cs @@ -1,24 +1,9 @@ using Microsoft.AspNetCore.SignalR; -using Microsoft.EntityFrameworkCore; namespace LiveChat.Server.Hubs; public class ChatHub : Hub { - private readonly ChattingContext _context; - public override async Task OnConnectedAsync() - { - using (var db = new ChattingContext()) - { - var messages = db.Messages.ToList(); - - messages.ForEach(Console.WriteLine); - - // Send the messages to the caller - await Clients.Caller.SendAsync("ReceiveMessages", messages); - } - } - public async Task SendMessage(string user, string message) { using (var db = new ChattingContext()) @@ -28,9 +13,7 @@ public class ChatHub : Hub User = user, Message = message, }; - Console.WriteLine(messageData); var dbSave = db.Messages.Add(messageData); - Console.WriteLine(dbSave); await Clients.All.SendAsync("ReceiveMessage", user, message); db.SaveChanges(); } diff --git a/LiveChat.csproj b/LiveChat.csproj index 94b4a55..7106317 100644 --- a/LiveChat.csproj +++ b/LiveChat.csproj @@ -8,6 +8,7 @@ + runtime; build; native; contentfiles; analyzers; buildtransitive @@ -16,6 +17,11 @@ + + + + + diff --git a/LiveChat.sln b/LiveChat.sln index 814ecb2..faaf21c 100644 --- a/LiveChat.sln +++ b/LiveChat.sln @@ -3,7 +3,7 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.5.33424.131 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LiveChat", "LiveChat.csproj", "{FDCEF6A6-0F83-47A1-AD48-2603502392F8}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LiveChat", "LiveChat.csproj", "{FDCEF6A6-0F83-47A1-AD48-2603502392F8}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution diff --git a/Model.cs b/Model.cs index 975cfbd..ae24265 100644 --- a/Model.cs +++ b/Model.cs @@ -22,6 +22,20 @@ public class ChattingContext : DbContext => options.UseSqlite($"Data Source={DbPath}"); } +public class Room +{ + [Key] + [DatabaseGenerated(DatabaseGeneratedOption.Identity)] + public string? Id { get; set; } + + public string? RoomJoinCode { get; set; } + + // koble tilsammen ChatMessage til Room + // https://www.entityframeworktutorial.net/efcore/one-to-many-conventions-entity-framework-core.aspx + public ChatMessage? ChatMessage { get; set; } + +} + public class ChatMessage { [Key] diff --git a/Models/User.cs b/Models/User.cs new file mode 100644 index 0000000..87461fe --- /dev/null +++ b/Models/User.cs @@ -0,0 +1,14 @@ +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; + +namespace LiveChat.Models +{ + public class UserModel + { + [Required] // påkrevd + [DataType(DataType.Text)] // datatype er tekst + [StringLength(16, ErrorMessage = "Navnet ditt er for langt! (maks 16 bokstaver)")] // sett maksimal lenge til 16 bokstaver + [DisplayName("Navnet ditt")] // navnet til User på appen + public string User { get; set; } + } +} diff --git a/Pages/Chat.razor b/Pages/Chat.razor new file mode 100644 index 0000000..8fcd58b --- /dev/null +++ b/Pages/Chat.razor @@ -0,0 +1,13 @@ +@page "/chat/{room?}" + +Chat room + +@if(Room is null or "") +{ +

Ingen rom ble avgitt. Lag et rom og putt det i URLen.

+} + +@code { + [Parameter] + public string? Room { get; set; } +} diff --git a/Pages/Counter.razor b/Pages/Counter.razor deleted file mode 100644 index ef23cb3..0000000 --- a/Pages/Counter.razor +++ /dev/null @@ -1,18 +0,0 @@ -@page "/counter" - -Counter - -

Counter

- -

Current count: @currentCount

- - - -@code { - private int currentCount = 0; - - private void IncrementCount() - { - currentCount++; - } -} diff --git a/Pages/FetchData.razor b/Pages/FetchData.razor deleted file mode 100644 index ea546c9..0000000 --- a/Pages/FetchData.razor +++ /dev/null @@ -1,47 +0,0 @@ -@page "/fetchdata" -@using LiveChat.Data -@inject WeatherForecastService ForecastService - -Weather forecast - -

Weather forecast

- -

This component demonstrates fetching data from a service.

- -@if (forecasts == null) -{ -

Loading...

-} -else -{ - - - - - - - - - - - @foreach (var forecast in forecasts) - { - - - - - - - } - -
DateTemp. (C)Temp. (F)Summary
@forecast.Date.ToShortDateString()@forecast.TemperatureC@forecast.TemperatureF@forecast.Summary
-} - -@code { - private WeatherForecast[]? forecasts; - - protected override async Task OnInitializedAsync() - { - forecasts = await ForecastService.GetForecastAsync(DateOnly.FromDateTime(DateTime.Now)); - } -} diff --git a/Pages/Index.razor b/Pages/Index.razor index 7ff6158..3414a33 100644 --- a/Pages/Index.razor +++ b/Pages/Index.razor @@ -1,56 +1,90 @@ @page "/" @using LiveChat.Models; @using Microsoft.AspNetCore.SignalR.Client +@inject Blazored.LocalStorage.ILocalStorageService localStorage @inject NavigationManager Navigation @implements IAsyncDisposable LiveChat app -

Sortert fra topp-bunn

+
+ + + + + + +
+ @if (msgs != null) { -
+ -} else +} +else {

Ingen meldinger tilgjengelig.

} -
-@if (messageModel == null) -{ -

laster inn meldingsboks

-} -else -{ - - -
- -
- -
- - - -
-
-} + @code { private HubConnection? hubConnection; + + private bool ModalIsVisible = true; private MessageModel messageModel = new MessageModel() { User = "", Message = "" }; + private UserModel userModel = new UserModel() { User = "" }; private List msgs = new List(); protected override async Task OnInitializedAsync() { - Console.WriteLine(messageModel); hubConnection = new HubConnectionBuilder() .WithUrl(Navigation.ToAbsoluteUri("/chathub")) .Build(); @@ -63,11 +97,12 @@ else { var encodedMsg = $"{msg.User}: {msg.Message}"; msgs.Add(encodedMsg); - InvokeAsync(StateHasChanged); } + await InvokeAsync(StateHasChanged); } - hubConnection.On("ReceiveMessage", (user, message) => { + hubConnection.On("ReceiveMessage", (user, message) => + { var encodedMsg = $"{user}: {message}"; msgs.Add(encodedMsg); InvokeAsync(StateHasChanged); @@ -76,13 +111,35 @@ else await hubConnection.StartAsync(); } + private async Task SetUser() + { + ModalIsVisible = false; + messageModel.User = userModel.User; + await localStorage.SetItemAsync("user", userModel.User); + } + private async Task HandleSubmit() { + var filter = new ProfanityFilter.ProfanityFilter(); + + // Kjempegøy + filter.AddProfanity("faen"); + filter.AddProfanity("jævla"); + filter.AddProfanity("jævel"); + filter.AddProfanity("homse"); + filter.AddProfanity("homo"); + filter.AddProfanity("neger"); + filter.AddProfanity("transe"); + filter.AddProfanity("dritt"); + + messageModel.User = filter.CensorString(messageModel.User); + messageModel.Message = filter.CensorString(messageModel.Message); + if (hubConnection is not null) { await hubConnection.SendAsync("SendMessage", messageModel.User, messageModel.Message); } - } + } public bool IsConnected => hubConnection?.State == HubConnectionState.Connected; diff --git a/Pages/_Host.cshtml b/Pages/_Host.cshtml index 04f924c..dc5aaa5 100644 --- a/Pages/_Host.cshtml +++ b/Pages/_Host.cshtml @@ -10,6 +10,7 @@ + diff --git a/Program.cs b/Program.cs index c719e68..c269145 100644 --- a/Program.cs +++ b/Program.cs @@ -1,15 +1,15 @@ -using LiveChat.Data; using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Web; using Microsoft.AspNetCore.ResponseCompression; using LiveChat.Server.Hubs; +using Blazored.LocalStorage; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddRazorPages(); builder.Services.AddServerSideBlazor(); -builder.Services.AddSingleton(); +builder.Services.AddBlazoredLocalStorage(); builder.Services.AddResponseCompression(opts => { opts.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat( diff --git a/README.md b/README.md index 3edbebf..82dba7b 100644 --- a/README.md +++ b/README.md @@ -2,4 +2,10 @@ LiveChat er mitt siste programmeringsprosjekt for ungdomsskolen, og er skrevet med ASP.NET Core, EF Core, SignalR Core og Blazor (Server). Jeg jobber fortsatt med den :P -Den bruker SQLite for database, det er ikke det raskeste men er rask nok for en liten app som dette. Det går også an å bruke andre databasesystemer hvis du installerer støtte for det. \ No newline at end of file +Den bruker SQLite for database, det er ikke det raskeste men er rask nok for en liten app som dette. Det g�r ogs� an � bruke andre databasesystemer hvis du installerer st�tte for det. + +For Ã¥ kjøre programmet, mÃ¥ du ha .NET SDK installert. + +Installer ``dotnet-ef`` verktøyet ogsÃ¥ kjør ``dotnet ef database update`` for Ã¥ lage databasen. + +SÃ¥ kan du kjøre ``dotnet build`` for Ã¥ bygge LiveChat, du finner han i bin/Debug/LiveChat.exe \ No newline at end of file diff --git a/wwwroot/css/site.css b/wwwroot/css/site.css index ecf599d..76d92cb 100644 --- a/wwwroot/css/site.css +++ b/wwwroot/css/site.css @@ -43,7 +43,7 @@ a, .btn-link { } #blazor-error-ui { - background: lightyellow; + background: #151515; bottom: 0; box-shadow: 0 -1px 2px rgba(0, 0, 0, 0.2); display: none; @@ -86,21 +86,27 @@ a, .btn-link { } .MessageForm { - background-color: #202020; - width: fit-content; - border-radius: 2rem; - - display: flex; - flex-direction: column; - gap: 0.25rem; - - text-align: center; - align-items: center; - justify-content: center; padding: 1rem; margin-top: 1rem; } +.giveName { + display: flex; + flex-direction: column; + justify-content: center; + align-items: center; +} + +@media screen and (max-width: 768px) { + .messageFormContainer { + bottom: 0; + } + .MessageForm { + border-radius: initial; + width: initial; + } +} + .MessageFormValidation > ul { display: flex; flex-direction: row;