Skip to content

Commit

Permalink
upload files added
Browse files Browse the repository at this point in the history
  • Loading branch information
vellt committed Aug 27, 2024
1 parent 8bcd60f commit 4e04ff4
Show file tree
Hide file tree
Showing 11 changed files with 149 additions and 16 deletions.
Binary file modified .vs/NetworkHelper/v16/.suo
Binary file not shown.
Binary file added ClassDiagram1.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
133 changes: 118 additions & 15 deletions NetworkHelper/Backend.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using System.Linq.Expressions;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
Expand All @@ -22,8 +23,8 @@ public class Response
/// <param name="jsonData">A válasz JSON formátumú adata.</param>
private Response(string jsonData)
{
JsonData = jsonData;
SelectedData = jsonData;
this.jsonData = jsonData;
selectedData = jsonData;
}

internal static Response Create(string jsonData)
Expand All @@ -34,11 +35,11 @@ internal static Response Create(string jsonData)
/// <summary>
/// A válasz teljes JSON adata.
/// </summary>
private string JsonData { get; }
private string jsonData;
// <summary>
/// Az éppen kiválasztott JSON (részleges) adat, amely az aktuális feldolgozás eredménye.
/// </summary>
private string SelectedData { get; set; }
private string selectedData;

/// <summary>
/// Kiválasztja a JSON adatban található értéket az adott index alapján.
Expand All @@ -51,14 +52,14 @@ public Response ValueAt(int index)
{
try
{
JObject response = JObject.Parse(SelectedData);
JObject response = JObject.Parse(selectedData);
var keys = response.Properties().Select(p => p.Name).ToList();

if (index < 0 || index >= keys.Count)
throw new ArgumentOutOfRangeException(nameof(index), "Index is out of range.");

string key = keys[index];
SelectedData = response[key]?.ToString();
selectedData = response[key]?.ToString();
}
catch (JsonException ex)
{
Expand All @@ -82,8 +83,8 @@ public Response ValueOf(string name)
{
try
{
JObject response = JObject.Parse(SelectedData);
SelectedData = response[name]?.ToString();
JObject response = JObject.Parse(selectedData);
selectedData = response[name]?.ToString();
}
catch (JsonException ex)
{
Expand All @@ -103,15 +104,15 @@ public T As<T>()
{
try
{
if (string.IsNullOrWhiteSpace(SelectedData))
if (string.IsNullOrWhiteSpace(selectedData))
{
throw new InvalidOperationException("SelectedData is null or empty.");
}

if (typeof(T) == typeof(string))
{
var result = (T)(object)SelectedData;
SelectedData = JsonData;
var result = (T)(object)selectedData;
selectedData = jsonData;
return result;
}
else if (typeof(T) == typeof(DateTime))
Expand Down Expand Up @@ -143,9 +144,9 @@ public T As<T>()
"yyyy-MM-ddTHH:mm:ss.fff" // Pl. "2007-05-12T00:00:00.000"
};

if (DateTime.TryParseExact(SelectedData, dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime parsedDate))
if (DateTime.TryParseExact(selectedData, dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out DateTime parsedDate))
{
SelectedData = JsonData;
selectedData = jsonData;
return (T)(object)parsedDate;
}
else
Expand All @@ -155,12 +156,12 @@ public T As<T>()
}
else
{
var result = JsonConvert.DeserializeObject<T>(SelectedData);
var result = JsonConvert.DeserializeObject<T>(selectedData);
if (result == null)
{
throw new InvalidOperationException("Deserialization resulted in a null value.");
}
SelectedData = JsonData;
selectedData = jsonData;
return result;
}
}
Expand All @@ -175,6 +176,106 @@ public T As<T>()
}
}

public class UploadBuilder
{
private string url;
private byte[] fileBytes;
private string filePath;
private UploadBuilder(string url)
{
this.url = url;
}
internal static UploadBuilder Create(string from)
{
if (string.IsNullOrEmpty(from))
{
throw new ArgumentException("URL cannot be null or empty.");
}
return new UploadBuilder(from);
}

public UploadBuilder File(string filePath)
{
if (string.IsNullOrEmpty(filePath))
{
throw new ArgumentException("File path cannot be null or empty.");
}

this.filePath = filePath;

try
{
// Olvassuk be a fájlt byte tömbbé
fileBytes = System.IO.File.ReadAllBytes(this.filePath);
return this;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}

public async Task<Response> SendAsync()
{
try
{

using (HttpClient client = new HttpClient())
{
using (MultipartFormDataContent form = new MultipartFormDataContent())
{
// Hozzáadjuk a fájlt a form-hoz
ByteArrayContent fileContent = new ByteArrayContent(fileBytes);
fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
form.Add(fileContent, "file", Path.GetFileName(filePath)); // "file" az a mezőnév, amit a szerver vár

// HTTP POST kérés küldése
HttpResponseMessage response = await client.PostAsync(url, form);

// Ellenőrizzük, hogy a válasz sikeres volt-e
response.EnsureSuccessStatusCode();
string json = await response.Content.ReadAsStringAsync();
return Response.Create(jsonData: json);
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}

public Response Send()
{
try
{

using (HttpClient client = new HttpClient())
{
using (MultipartFormDataContent form = new MultipartFormDataContent())
{
// Hozzáadjuk a fájlt a form-hoz
ByteArrayContent fileContent = new ByteArrayContent(fileBytes);
fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
form.Add(fileContent, "file", Path.GetFileName(filePath)); // "file" az a mezőnév, amit a szerver vár

// HTTP POST kérés küldése
HttpResponseMessage response = client.PostAsync(url, form).Result;

// Ellenőrizzük, hogy a válasz sikeres volt-e
response.EnsureSuccessStatusCode();
string json= response.Content.ReadAsStringAsync().Result;
return Response.Create(jsonData: json);
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
}

/// <summary>
/// HTTP kérések építéséhez és küldéséhez használt osztály.
/// </summary>
Expand Down Expand Up @@ -301,6 +402,8 @@ public static class Backend
/// <param name="url">Az URL a kéréshez.</param>
/// <returns>A DELETE kéréshez használható <see cref="RequestBuilder"/> példány.</returns>
public static RequestBuilder DELETE(string from) => RequestBuilder.Create(MethodBase.GetCurrentMethod().Name, from);

public static UploadBuilder UPLOAD(string from) => UploadBuilder.Create(from);
}
}

Expand Down
32 changes: 31 additions & 1 deletion NetworkHelper/ClassDiagram1.cd
Original file line number Diff line number Diff line change
@@ -1,2 +1,32 @@
<?xml version="1.0" encoding="utf-8"?>
<ClassDiagram />
<ClassDiagram MajorVersion="1" MinorVersion="1" MembersFormat="FullSignature">
<Class Name="NetworkHelper.Response">
<Position X="3.5" Y="1" Width="2.5" />
<TypeIdentifier>
<HashCode>ABAAAAAAAAAABAAAAAIACAAAAAAAQEAAAAAAAAAAAAA=</HashCode>
<FileName>Backend.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="NetworkHelper.UploadBuilder">
<Position X="10" Y="1" Width="2.5" />
<TypeIdentifier>
<HashCode>AADAAAAAAAAAAAAAAEAAAAAAAAAMAEAAAAAAAAAAAAA=</HashCode>
<FileName>Backend.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="NetworkHelper.RequestBuilder">
<Position X="6.25" Y="1" Width="3.5" />
<TypeIdentifier>
<HashCode>AABAAAAAAAAAAAAAAEABAACAAAAAAEAAAAAAAAAAAAA=</HashCode>
<FileName>Backend.cs</FileName>
</TypeIdentifier>
</Class>
<Class Name="NetworkHelper.Backend">
<Position X="0.5" Y="1.25" Width="2.75" />
<TypeIdentifier>
<HashCode>AAAIAAAAAAAEAQAAAAAAAAAAACAgAAAAAAAAAAAAAAA=</HashCode>
<FileName>Backend.cs</FileName>
</TypeIdentifier>
</Class>
<Font Name="Segoe UI" Size="9" />
</ClassDiagram>
Binary file modified NetworkHelper/NetworkHelper.dll
Binary file not shown.
Binary file modified NetworkHelper/NetworkHelper.pdb
Binary file not shown.
Binary file modified NetworkHelper/bin/Debug/NetworkHelper.dll
Binary file not shown.
Binary file modified NetworkHelper/bin/Debug/NetworkHelper.pdb
Binary file not shown.
Binary file not shown.
Binary file modified NetworkHelper/obj/Debug/NetworkHelper.dll
Binary file not shown.
Binary file modified NetworkHelper/obj/Debug/NetworkHelper.pdb
Binary file not shown.

0 comments on commit 4e04ff4

Please sign in to comment.