Eistee
Eistee
CC#
Created by Eistee on 12/27/2023 in #help
Image upload and hosting
How do you host images securely? The images would only be uploaded by admins and displayed to users. The upload should take place via the ASP.NET Core App, but where to? How do you do that? The app is small and would have a few hundred users. So far I have only published internally on the intranet. This time the project should be accessible from the Internet 😨 and I don't know how to make the image upload possible and secure.
7 replies
CC#
Created by Eistee on 7/26/2023 in #help
❔ ConfigureAwait(false) (IntelliCode Suggestion)
Can someone help me to understand why IntelliCode is suggesting ConfigureAwait(false) at line 16 await Dns.GetHostEntryAsync(ipAddress);? Would this really result in an advantage?
private async Task<List<DeviceInfo>> GetDevices(XDocument xDocument)
{
List<DeviceInfo> deviceList = new List<DeviceInfo>();

var itemElements = xDocument.Descendants("item");
foreach (var itemElement in itemElements)
{
string? deviceName = itemElement.Element("device")?.Value;
string? host = itemElement.Element("host")?.Value;
string? objId = itemElement.Element("objid")?.Value;

if (IPAddress.TryParse(host, out IPAddress? ipAddress) && ipAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
try
{
var hostEntry = await Dns.GetHostEntryAsync(ipAddress);
host = hostEntry.HostName;
}
catch
{
_logger.LogError($"There is an error occured while resolving {ipAddress}: {host}");
}
}

// remove all possible domains from FQDNs to get hostnames even if they include dots
if (_optionsAccessor.PossibleOccuringDomains is not null && !string.IsNullOrEmpty(host))
{
deviceName = host;
_optionsAccessor.PossibleOccuringDomains.ForEach(item =>
{
deviceName = deviceName.Replace(item, string.Empty);
});
}

deviceList.Add(new DeviceInfo { HostName = deviceName, FQDN = host, ObjID = objId });
}
return deviceList;
}
private async Task<List<DeviceInfo>> GetDevices(XDocument xDocument)
{
List<DeviceInfo> deviceList = new List<DeviceInfo>();

var itemElements = xDocument.Descendants("item");
foreach (var itemElement in itemElements)
{
string? deviceName = itemElement.Element("device")?.Value;
string? host = itemElement.Element("host")?.Value;
string? objId = itemElement.Element("objid")?.Value;

if (IPAddress.TryParse(host, out IPAddress? ipAddress) && ipAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
try
{
var hostEntry = await Dns.GetHostEntryAsync(ipAddress);
host = hostEntry.HostName;
}
catch
{
_logger.LogError($"There is an error occured while resolving {ipAddress}: {host}");
}
}

// remove all possible domains from FQDNs to get hostnames even if they include dots
if (_optionsAccessor.PossibleOccuringDomains is not null && !string.IsNullOrEmpty(host))
{
deviceName = host;
_optionsAccessor.PossibleOccuringDomains.ForEach(item =>
{
deviceName = deviceName.Replace(item, string.Empty);
});
}

deviceList.Add(new DeviceInfo { HostName = deviceName, FQDN = host, ObjID = objId });
}
return deviceList;
}
23 replies
CC#
Created by Eistee on 7/25/2023 in #help
✅ Dealing/resolving nullable warnings
I try to deal with nullable warnings among others e. g. CS8604 "Possible null reference argument for parameter." I have the following sample code of a C# 7.0 worker service:
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
if (!PrerequisitesMet())
{
_logger.LogError("the options checked an is NULL");
throw new InvalidOperationException("prerequisites not met.");
}

while (!stoppingToken.IsCancellationRequested)
{
try
{
XDocument doc;

if (_options.ApiQueryURL is not null)
{
doc = await _httpService.GetXmlResponseAsync(_options.ApiQueryURL);

if (doc.Nodes().Any())
{
devices = GetDevices(doc);
await _dataService.UpdateDevicesAsync(devices);
}
}
}
catch (Exception ex)
{
if (OperatingSystem.IsWindows() && _eventLog != null)
{
_eventLog.WriteEntry($"Error occurred: {ex.Message}", EventLogEntryType.Error);
}
}

await Task.Delay(TimeSpan.FromHours(1), stoppingToken);
}
}

private bool PrerequisitesMet()
{
// options
if (_options == null)
return false;

// option "ApiQueryURL"
if (string.IsNullOrWhiteSpace(_options.ApiQueryURL))
return false;

// option "TargetString"
if (string.IsNullOrWhiteSpace(_options.TargetString))
return false;

return true;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
if (!PrerequisitesMet())
{
_logger.LogError("the options checked an is NULL");
throw new InvalidOperationException("prerequisites not met.");
}

while (!stoppingToken.IsCancellationRequested)
{
try
{
XDocument doc;

if (_options.ApiQueryURL is not null)
{
doc = await _httpService.GetXmlResponseAsync(_options.ApiQueryURL);

if (doc.Nodes().Any())
{
devices = GetDevices(doc);
await _dataService.UpdateDevicesAsync(devices);
}
}
}
catch (Exception ex)
{
if (OperatingSystem.IsWindows() && _eventLog != null)
{
_eventLog.WriteEntry($"Error occurred: {ex.Message}", EventLogEntryType.Error);
}
}

await Task.Delay(TimeSpan.FromHours(1), stoppingToken);
}
}

private bool PrerequisitesMet()
{
// options
if (_options == null)
return false;

// option "ApiQueryURL"
if (string.IsNullOrWhiteSpace(_options.ApiQueryURL))
return false;

// option "TargetString"
if (string.IsNullOrWhiteSpace(_options.TargetString))
return false;

return true;
}
Is that so well solved that you always check for is not null?
10 replies
CC#
Created by Eistee on 5/6/2023 in #help
❔ Import github library (maybe also via npm?)
11 replies
CC#
Created by Eistee on 4/23/2023 in #help
❔ Razor Pages Session for revalidating Page Model
Can someone help me to configure the Session for Razor Pages, that I can use TryValidateModel()?
TryValidateModel(this);"
TryValidateModel(this);"
is throwing a InvalidOperationException: Session has not been configured for this application or request.error? I can't find any hint about the online https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.razorpages.pagemodel.tryvalidatemodel?view=aspnetcore-7.0 The debugger is actually stepping over it, but the trace says:
Microsoft.AspNetCore.Http.DefaultHttpContext.get_Session()
Microsoft.Extensions.Internal.PropertyHelper.CallNullSafePropertyGetter<TDeclaringType, TValue>(Func<TDeclaringType, TValue> getter, object target)
Microsoft.AspNetCore.Mvc.ModelBinding.Validation.ValidationEntry.get_Model()
Microsoft.AspNetCore.Mvc.ModelBinding.Validation.ValidationVisitor.VisitChildren(IValidationStrategy strategy)
Microsoft.AspNetCore.Mvc.ModelBinding.Validation.ValidationVisitor.VisitComplexType(IValidationStrategy defaultStrategy)
Microsoft.AspNetCore.Http.DefaultHttpContext.get_Session()
Microsoft.Extensions.Internal.PropertyHelper.CallNullSafePropertyGetter<TDeclaringType, TValue>(Func<TDeclaringType, TValue> getter, object target)
Microsoft.AspNetCore.Mvc.ModelBinding.Validation.ValidationEntry.get_Model()
Microsoft.AspNetCore.Mvc.ModelBinding.Validation.ValidationVisitor.VisitChildren(IValidationStrategy strategy)
Microsoft.AspNetCore.Mvc.ModelBinding.Validation.ValidationVisitor.VisitComplexType(IValidationStrategy defaultStrategy)
The server side page Post method looks like this:
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
for (int x = ThirdPartyInformations.Count -1; x >= 0; x--)
{
if (ThirdPartyInformations[x].HiddenEntry == true)
{
ThirdPartyInformations.RemoveAt(x);
}
}

ModelState.Clear();
TryValidateModel(this); // <--
}

if (!ModelState.IsValid ||
....
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
for (int x = ThirdPartyInformations.Count -1; x >= 0; x--)
{
if (ThirdPartyInformations[x].HiddenEntry == true)
{
ThirdPartyInformations.RemoveAt(x);
}
}

ModelState.Clear();
TryValidateModel(this); // <--
}

if (!ModelState.IsValid ||
....
2 replies
CC#
Created by Eistee on 2/23/2023 in #help
✅ When and how should I use the Windows EventLog?
Hello, do I need to create proper source via EventLog.CreateEventSource? If I need to, what is the proper way to create this source if the application has no setup and should run without elevated rights? I could imagine to add another executable, which only registers the source, that you can get those from the actual program with System.Diagnostics.Process.Start and startInfo.Verb = "runas"; Do you have an opinion on this or can you give me some tips?
5 replies
CC#
Created by Eistee on 2/5/2023 in #help
❔ Handling of objects which correspond to a given rule by editing again.
The situation: The user can create objects in a list via the UI. If there are already one or more objects in this list and they have the same properties name and color, all these objects are invalid. The creation of the object should not be interrupted, there is only a warning at time of creation. I would check this logic with the warning and setting the invalidity when creating the object. The question now is, how is it design wise good to make these objects valid again by editing each one? Should this also be done only by editing the individual objects? If there is more than 1 duplicate with these two properties, only the currently edited object should be made valid again. If there is only one duplicate, the other object must also be found in the list and validated. I am having trouble implementing this logic 😓
3 replies