malkav
malkav
CC#
Created by malkav on 6/20/2024 in #help
WPF Styling of a button
I have this button Style in WPF that I am trying to make https://pastebin.com/xCTrerLg The problem with this at the moment being that the following states: Hover, Pressed, and Disabled are not changing their colors appropriately. When I use the Warning class for example, I seem to get the Primary colors on those states, but the Warning color on the base button. When I use Secondary it changes everything to just the Secondary color, and not the state colors I defined at the top of the file. etc, etc. So now I come here for help, in the hopes of seeing what I did wrong 😅 Additional resources: ButtonHelper class: https://pastebin.com/9DZ09La9 How I implement the button in the pages:
<Page x:Class="CrystalTrack.Gui.Pages.Settings"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:CrystalTrack.Gui.Pages"
xmlns:controls="clr-namespace:CrystalTrack.Gui.Controls"
mc:Ignorable="d">
<!-- ... -->
<Button Grid.Column="2" Grid.Row="0"
Style="{StaticResource InformButton}"
controls:ButtonHelper.ColorClass="Warning"
Click="ApiKeyButton_OnClick">
Text here
</Button>
<!-- ... -->
<Page x:Class="CrystalTrack.Gui.Pages.Settings"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:CrystalTrack.Gui.Pages"
xmlns:controls="clr-namespace:CrystalTrack.Gui.Controls"
mc:Ignorable="d">
<!-- ... -->
<Button Grid.Column="2" Grid.Row="0"
Style="{StaticResource InformButton}"
controls:ButtonHelper.ColorClass="Warning"
Click="ApiKeyButton_OnClick">
Text here
</Button>
<!-- ... -->
5 replies
CC#
Created by malkav on 6/13/2024 in #help
Trying to add Fonts to a Style.xaml in WPF
I have a folder containing the fonts I wish to use in my application. namely; RnC-Demo.otf as well as the complete Roboto-*.ttf [black, blackitalic, bold, boldcondensed, boldcondenseditalic, bolditalic, condensed, condenseditalic, italic, light, lightitalic, medium, mediumitalic, regular, thin, thinitalic] Now I wanted to add these to my Styles/Root.xaml file in such a way that later in my application the default font for various items (like headers, base-text, buttons, etc) will be set by default, or I override them at the point of usage. However, with all the examples and documentations I found online, there seem to be so many variations, and none seem to work. I am aware that might be me and not the documentation... Here's what I'm trying now, but I'm not sure if this is right.
<FontFamily x:Key="CrystalTrack.Gui.Fonts.Family.RnC">RnC Demo Fonts,/CrystalTrack.Gui;component/Fonts/#RnC-Demo Fonts</FontFamily>
<FontFamily x:Key="CrystalTrack.Gui.Fonts.Family.Roboto">RnC Demo Fonts,/CrystalTrack.Gui;component/Fonts/#RnC-Demo Fonts</FontFamily>
<FontFamily x:Key="CrystalTrack.Gui.Fonts.Family.RnC">RnC Demo Fonts,/CrystalTrack.Gui;component/Fonts/#RnC-Demo Fonts</FontFamily>
<FontFamily x:Key="CrystalTrack.Gui.Fonts.Family.Roboto">RnC Demo Fonts,/CrystalTrack.Gui;component/Fonts/#RnC-Demo Fonts</FontFamily>
My file locations are as follows:
|-- Solution/
| |-- CrystalTrack.Gui/
| | |-- Fonts/
| | | |-- *.otf/*.ttf files
| | |-- Style/
| | | |-- Root.xaml
| | | |-- App.xaml
| |-- App.xaml
| |-- MainPage.xaml
|-- Solution/
| |-- CrystalTrack.Gui/
| | |-- Fonts/
| | | |-- *.otf/*.ttf files
| | |-- Style/
| | | |-- Root.xaml
| | | |-- App.xaml
| |-- App.xaml
| |-- MainPage.xaml
1 replies
CC#
Created by malkav on 6/5/2024 in #help
✅ Trying to edit button onMouseOver styles, but to no avail
I'm trying to get my MouseOver effects altered in my styles, but so far I've not been able to edit the mouseover styles. It keeps reverting back to the default blue style when IsMouseOver = true My current style (attempt?)
<Style TargetType="{x:Type Button}" x:Key="BtnOutlinePrimary">
<Setter Property="Background" Value="Transparent" />
<Setter Property="BorderBrush" Value="{DynamicResource CtPrimary}" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Button Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{DynamicResource BorderThickness}"
FontFamily="{DynamicResource Roboto-Regular}"
Foreground="Black" >
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
</Button>
</ControlTemplate>
</Setter.Value>
</Setter>

<!-- On Hover -->
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="{DynamicResource CtPrimary}" />
<Setter Property="BorderBrush" Value="{DynamicResource CtDark}" />
</Trigger>
</Style.Triggers>
</Style>
<Style TargetType="{x:Type Button}" x:Key="BtnOutlinePrimary">
<Setter Property="Background" Value="Transparent" />
<Setter Property="BorderBrush" Value="{DynamicResource CtPrimary}" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Button Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{DynamicResource BorderThickness}"
FontFamily="{DynamicResource Roboto-Regular}"
Foreground="Black" >
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
</Button>
</ControlTemplate>
</Setter.Value>
</Setter>

<!-- On Hover -->
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="{DynamicResource CtPrimary}" />
<Setter Property="BorderBrush" Value="{DynamicResource CtDark}" />
</Trigger>
</Style.Triggers>
</Style>
32 replies
CC#
Created by malkav on 6/5/2024 in #help
WPF Fonts in a ResourceDictionary
No description
2 replies
CC#
Created by malkav on 6/5/2024 in #help
✅ Mapping IDataReader into typed class
I'm trying to get data from IDataReader into a typed model object. What I'm trying in my model is the following method:
public static TestDataObject Create(IDataRecord record)
{
return new TestDataObject
{
Id = (Guid)record["id"],
Name = (string)record["name"],
Value = (string)record["value"]
};
}
public static TestDataObject Create(IDataRecord record)
{
return new TestDataObject
{
Id = (Guid)record["id"],
Name = (string)record["name"],
Value = (string)record["value"]
};
}
and at my API class where I'm trying to fetch data from the ADX cluster, I'm calling the following method:
private static IEnumerable<T> BuildResult<T>(IDataReader response, Func<IDataRecord, T> buildObject)
{
Console.WriteLine("Building result");
try
{
while (response.Read())
{
Console.WriteLine($"Working on nth response {response.NextResult()}");

yield return buildObject(response);
}
}
finally
{
response.Dispose();
}
}

// Calling it like this:
TestDataObject[] result = BuildResult(response, TestDataObject.Create).ToArray();
private static IEnumerable<T> BuildResult<T>(IDataReader response, Func<IDataRecord, T> buildObject)
{
Console.WriteLine("Building result");
try
{
while (response.Read())
{
Console.WriteLine($"Working on nth response {response.NextResult()}");

yield return buildObject(response);
}
}
finally
{
response.Dispose();
}
}

// Calling it like this:
TestDataObject[] result = BuildResult(response, TestDataObject.Create).ToArray();
However I keep getting Index was outside the bounds of the array as error Which index? the ["id"] ones? what am I missing?
6 replies
CC#
Created by malkav on 5/27/2024 in #help
Kusto Ingestion queue
Hey all, wondering if anyone knows this: I'm trying to queue a list of models into a kusto cluster (ADX) and I figured I could basically turn each of these data models into a string and queue from MemoryStream, though I do realize that might not be optimal for the system. Adding to queue from a local database might be better but that creates other latency issues that I wish to avoid. So for now the memorystream is my to-go option. However... I would need to know if I can queue all items in one go? Like for example:
foreach (T model in models) {
stringStream.Append($"[{model.ToString}]");
}
foreach (T model in models) {
stringStream.Append($"[{model.ToString}]");
}
Where I have overwrite ToString() on the models that look like:
public override ToString() {
return $"{prop1},{prop2},...";
}
public override ToString() {
return $"{prop1},{prop2},...";
}
Is this the right way to do this? or should I queue all items individually?
3 replies
CC#
Created by malkav on 3/12/2024 in #help
CommunityTools.Maui.Markup ColectionView
I'm trying to get a grip on the CommunityToolkit.Maui.Markup extensions, to create the MAUI application in C#, but I'm unsure how to bind my ItemSource to my labels. I've bound a mode to my ItemSource, but now in my Label() I'm trying to bind one of the properties of that model to that specific label. Here's what I've got so far: https://hastebin.com/share/rucosemalu.cpp In here you'll see my Children = { new Label().Text("ID: ").Row(Row.Id).Column(Column.Label), new Label().Text("id") ... This last Text("id") is where I'm trying to bind the Id property of my ItemSource (RespSubjectType) Basically what I've done is bind my ItemsSource to my ViewModel's SubjectTypes property. Which is RespSubjectType[] an array. And with my ItemTemplate I'm trying to get Maui to render the same template for each of the items in that array. Now for the Label.TextProperty value, I would like the Current item's Id, and Name properties set to their respective labels. I was hoping I could use BindContext to approach the SubjectTypes variable, but then I still don't have a way to approach the Id and Name values respectively. So if anyone could help me out to figure how I can (and probably should) set this up? Note: I am trying to create the MAUI app without xaml, hence the CommunityToolkit.Maui.Markup package Note_2: Even with hard-coded content, I still only are able to see my button, no singe CollectionItem. If anyone can share the issues with my code, or a solution to the problem at hand.
1 replies
CC#
Created by malkav on 5/23/2023 in #help
❔ The search for information
So I've been struggling to find a decent source or topic somewhere on how to write your own framework. I know it probably requires a lot more knowledge than I have, but I would still like to read up on it. There is most likely a difference between various frameworks. So questions like "What kind of framework" and "What is the goal of the framework" come to mind. Answering those is relatively simple at this point in time. I'd like to build a .NET/ ASP.NET framework like Blazor, but combined with its own database driven CMS. So like Orchard maybe? And instead of using .razor or .liquid I'd like to add my own .[extension] files to them. The idea is to make a component based web app framework that can build from a ModelViewController base to a static app, or server hosted. That's the questions of what kind, and what is the goal. But my question, or discussion topic, would be where to find good sources to read up on the how, and where to begin if you would like to create your own framework. The second question I have, would be what a decent "convention" would be on the structure of files, and the organization of it all. I know these are probably two questions that can be discussed separately but they do align eventually.
20 replies
CC#
Created by malkav on 5/19/2023 in #help
❔ ASP.NET Core, OrchardCore, OrchardCMS
I am starting to lose it, I've been following the tutorials of the OrchardCore documentation to add MVC and CMS to an ASP.NET Core web application, but every time I either get orchardcore.theme.targets.targets(30, 11): [msb4057] the target "orchardcorefiltermodules" does not exist in the project. when I try to add a theme to the solution, or I get View not found errors and can't seem to be able to get OrchardCore running entirely. I'm using Rider, and are trying to build an SWA with a CMS that can handle the various content files, and blogs, and more but we've been coming up against various walls so far. Either WASM (webassembly) can't reach a file system (obvious now..) and we have to parse markdowns as yaml and then to JSON and can't even get the data to work in the SWA during build. Or we are running into CMS that are database dependant. Orchard seems to be not really Headless, but a full blown framework. Which I don't mind much, but I am running in circles, and continuously hitting walls, and I'm a little stuck.. Is there someone that can help me figure out what framework to use to build a static website, that can handle CMS based content texts, and images, for pretty much the entire website. We would be having a "home" page with almost all content on it, and a few sub-pages. One for each "employee" and one with "all blogs" (which also all have their own page, preferred with custom styling) and two more for the privacy statements and terms&conditions Most preferred would be serverless, but I've found nothing but issues so far and I'm stuck. Please help?
2 replies
CC#
Created by malkav on 5/10/2023 in #help
❔ Reading multiple files/folders inside root/subfolder
So since I'm working with Blazor WASM, apparently there is no way of reading files using Directory.ReadAllFiles() because the Directory returns / and nothing else. At runtime this won't read any folders or files. So I was bound to using HttpClient to do so. However, the folder I'm reaching, will eventually have a CMS created number of files (All .md files) and I need a way of reading them all, and then using my parser for each files it finds. I was hoping there was a way to do this with HttpClient like for example client.GetAsync("localhost:0000/uploads/**/*.md"); but this seems like it isn't possible. So I come here asking for help finding a way of readnig all .md files inside the /uploads/ folder (this can be /uploads/fpsettings/settings.md, or /uploads/blogs/blog-slug.md or many more.)
27 replies
CC#
Created by malkav on 5/10/2023 in #help
✅ My stringbuilder is skipping lines
Aside from a previous post I made: https://discord.com/channels/143867839282020352/1105409576586715166/1105409576586715166 I am trying to parse some strings lines, but the stringbuilder itself is already skipping lines and I'm not entirely sure why it skips those lines. The builder part (see the stream variable later):
StringBuilder builder = new();
using StreamReader reader = new(stream);
await reader.ReadLineAsync();

while (await reader.ReadLineAsync() is { } line && line != "---")
{
builder.AppendLine(await reader.ReadLineAsync());
}
StringBuilder builder = new();
using StreamReader reader = new(stream);
await reader.ReadLineAsync();

while (await reader.ReadLineAsync() is { } line && line != "---")
{
builder.AppendLine(await reader.ReadLineAsync());
}
The stream variable:
---
title: FP Config
hero_settings:
title: my title
subtitle: test meuk
button_text: mail
client_header:
title: clients
subtitle: of us
clients: []
services_header:
title: services
subtitle: services
expertise_header:
title: expertise
subtitle: stuff
about_header:
title: about
subtitle: about
about:
- leadmct: true
mct: true
mvp: true
title: bryce
subtitle: manager
image: url.to/image/path.png
partnerships_header:
title: partnerships
subtitle: partners
---
---
title: FP Config
hero_settings:
title: my title
subtitle: test meuk
button_text: mail
client_header:
title: clients
subtitle: of us
clients: []
services_header:
title: services
subtitle: services
expertise_header:
title: expertise
subtitle: stuff
about_header:
title: about
subtitle: about
about:
- leadmct: true
mct: true
mvp: true
title: bryce
subtitle: manager
image: url.to/image/path.png
partnerships_header:
title: partnerships
subtitle: partners
---
And what I get in the console is the following:
hero_settings:
subtitle: test meuk
client_header:
subtitle: of us
services_header:
subtitle: services
title: expertise
about_header:
subtitle: about
- leadmct: true
mvp: true
subtitle: manager
partnerships_header:
subtitle: partners
hero_settings:
subtitle: test meuk
client_header:
subtitle: of us
services_header:
subtitle: services
title: expertise
about_header:
subtitle: about
- leadmct: true
mvp: true
subtitle: manager
partnerships_header:
subtitle: partners
So my stringbuilder already fails 😅 I get more when I just do reader.ReadToEnd().Replace("---", "").Trim() but that will skip the body which could come after the last "---" part. So I need a way to include the body as well
19 replies
CC#
Created by malkav on 5/9/2023 in #help
✅ Familiarity with `YamlDotNet` package, parsing to strongly typed object keeps failing
So I have this .md to .yaml parser written, and a package that parses a yaml into a .NET object class, however it keeps telling me the properties cannot be found. For example, when I parse with the example class shown in https://dotnetfiddle.net/k1d6I2 my fiddle. The method I use for parsing is in there too. However, when I try to parse a markdown file:
---
title: FP Config
hero_settings:
title: my title
subtitle: test meuk
button_text: mail
client_header:
title: clients
subtitle: of us
clients: []
services_header:
title: services
subtitle: services
expertise_header:
title: expertise
subtitle: stuff
about_header:
title: about
subtitle: about
about:
- leadmct: true
mct: true
mvp: true
title: bryce
subtitle: manager
image: url.to/image/path.png
partnerships_header:
title: partnerships
subtitle: partners
---
---
title: FP Config
hero_settings:
title: my title
subtitle: test meuk
button_text: mail
client_header:
title: clients
subtitle: of us
clients: []
services_header:
title: services
subtitle: services
expertise_header:
title: expertise
subtitle: stuff
about_header:
title: about
subtitle: about
about:
- leadmct: true
mct: true
mvp: true
title: bryce
subtitle: manager
image: url.to/image/path.png
partnerships_header:
title: partnerships
subtitle: partners
---
I get the following error:
Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
Unhandled exception rendering component: Property 'hero_settings' not found on type 'My.Namespace.Data.FrontPageSettings'.
Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
Unhandled exception rendering component: Property 'hero_settings' not found on type 'My.Namespace.Data.FrontPageSettings'.
Can anyone help me out here? Or is there an easier way to parse .md files into JSON instead? (not using a console application, like this git linkhttps://github.com/markjulmar/MarkdownToJson
2 replies
CC#
Created by malkav on 5/5/2023 in #help
✅ Parse .md like .json in C# class
Does anyone know how I can parse a "settings markdown" file into a C# class, like I could do with newtonsoft for JSON files? Example: I have this "settings.md" file
---
Title: myTitle
first_object_settings:
title: some_title
subtitle: some-subtitle
button_content: my button content
second_object_header:
title: another_title
subtitle: another_subtitle
second_object_settings:
url: some.url.here
image: path/or/url/to/image
---
---
Title: myTitle
first_object_settings:
title: some_title
subtitle: some-subtitle
button_content: my button content
second_object_header:
title: another_title
subtitle: another_subtitle
second_object_settings:
url: some.url.here
image: path/or/url/to/image
---
How can I parse this into a C# class like this:
public class Setting
{
public string Title {get;set;}
public FirstObject FirstObject {get;set;}
public Header SecondObjectHeader {get;set;}
public SecondObject SecondObjectContent {get;set;}
//...
}

public class Header
{
public string Title {get;set;}
public string Subtitle {get;set;}
}

public class SecondObject
{
public string Url {get;set;}
public string Image {get;set;}
}
public class Setting
{
public string Title {get;set;}
public FirstObject FirstObject {get;set;}
public Header SecondObjectHeader {get;set;}
public SecondObject SecondObjectContent {get;set;}
//...
}

public class Header
{
public string Title {get;set;}
public string Subtitle {get;set;}
}

public class SecondObject
{
public string Url {get;set;}
public string Image {get;set;}
}
(and following the same structure any number of other objects) I'm using DecapCMS in my Blazor project, but DecapCMS creates markdown files that I want to render the content into my blazor project The "settings" are also created in markdown, and regular content is written under the "header" from the markdown (blog example)
---
title: Blog Title
date: Creation Date
tags: Array of Tags
---
## Blog
some actual blog content written here like regular markdown
---
title: Blog Title
date: Creation Date
tags: Array of Tags
---
## Blog
some actual blog content written here like regular markdown
I'd want to parse that into a C# class too 😅 (and the regular content I can parse into HTML without issue)
133 replies
CC#
Created by malkav on 5/3/2023 in #help
❔ JSON To Excel
I have a console app that takes a folder of JSON objects, and deserializes them into Classes From here, I want to map these classes into excel sheets (I will link the models in a sec via hastebin) What I want is to map these json to excel tables by making a worksheet based on the "skill" property The thing is that these things are nested, and so far it results in my excel giving me a single sheet, with System.Collection[...] values in the cells, instead of recursively getting all nested properties, and mapping them internally.. So basically here's the schema I use for the JSONs https://pastebin.com/CbgdUpt0 And these are the models I made: https://pastebin.com/N4y3ciRy Most of my program works fine, but what I can't seem to figure is the excel part. Here's the method I use to generate a DataTable, which is not looking into nested properties, and I don't know how
public static DataTable ConvertToDataTable<T>(this IEnumerable<T> models)
{
DataTable dataTable = new DataTable(typeof(T).Name);
PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo prop in props)
{
dataTable.Columns.Add(prop.Name);
}
foreach (T item in models)
{
object[] values = new object[props.Length];
for (int i = 0; i < props.Length; i++)
{
values[i] = props[i].GetValue(item, null);
}
dataTable.Rows.Add(values);
}
return dataTable;
}
public static DataTable ConvertToDataTable<T>(this IEnumerable<T> models)
{
DataTable dataTable = new DataTable(typeof(T).Name);
PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo prop in props)
{
dataTable.Columns.Add(prop.Name);
}
foreach (T item in models)
{
object[] values = new object[props.Length];
for (int i = 0; i < props.Length; i++)
{
values[i] = props[i].GetValue(item, null);
}
dataTable.Rows.Add(values);
}
return dataTable;
}
3 replies
CC#
Created by malkav on 4/20/2023 in #help
❔ Blazor WASM & NetlifyCMS
not sure if the right discord for this. but here goes: I have a blazor wasm application that I want to use netlifycms on. However so far I've noticed that the admin panel part of the cms doesn't work as intended... Currently my project folder looks like follows:
|-- wwwroot
| |-- admin
| | |-- config.yml
| | |-- index.html
| |-- css
| | |-- **/*.css
| |-- images
| |-- sass
| |-- static
| |-- favicon.ico
| |-- icon-192.png
| |-- index.html
| |-- netlify.toml
|-- Pages
| |-- index.razor
|-- Shared
| ... contents
|-- wwwroot
| |-- admin
| | |-- config.yml
| | |-- index.html
| |-- css
| | |-- **/*.css
| |-- images
| |-- sass
| |-- static
| |-- favicon.ico
| |-- icon-192.png
| |-- index.html
| |-- netlify.toml
|-- Pages
| |-- index.razor
|-- Shared
| ... contents
but going to my http://localhost:3000/admin/ results in a "page not found" if I place my entire contents of /admin folder in my wwwroot the netlify login with azure button is shown at the same time as the rest of the page, which is also not waht I wanted. I am considering to place the admin folder in the parent folder instead, but I don't know if this will work. Can someone help me set this up so I can actually reach both my SWA as well as my /admin/ route to login to netlify cms with azure? (Note the tenant and app Id both are already set in my config.yml, I know that this works as I've tested it when it showed up at the same time as the rest of the SWA.
2 replies
CC#
Created by malkav on 4/5/2023 in #help
❔ Translation from visual studio to rider, client-side-package
So I'm trying to figure out how to add Bootrap in SCSS files to generate these for me, and add them to the wwwroot/css folder. Now I found something on stackoverflow https://stackoverflow.com/questions/68236284/how-to-setup-bootstrap-5-to-blazor-client-project but this tells me how to do this with Visual Studio and the Web Compiler extension, but I cannot find the way to do this with Rider. Can someone help me explain this?
6 replies
CC#
Created by malkav on 3/8/2023 in #help
❔ Convert nested JObjects into Dictionary<string, object>
What I want is like the title, to convert any json given by the user into a Dictionary<string, object> but keep the JSON structure. Especially if it's nested. So I figured I'd start recursively, in a sense, but I am getting stuck on the point where I attack the child tokens, since they are JToken and not JObject. And I'm not sure if they will keep working if I use OfType<JObject>(). So I could use some help converting a JObject that a user inputs to a Dictionary that keeps the JSON structure. Here's what I've got so far:
public static Dictionary<string,object> Convert(this JObject source)
{
Dictionary<string,object> result = new();
foreach (KeyValuePair<string, JToken> kvp in source)
{
if (kvp.Value.HasValues) // aka if it has child tokens according to NewtonSoft.Json docs??
{
foreach (var childToken in kvp.Value.Children().OfType<JObject>())
{
childToken.Convert();
}
}
}
}
public static Dictionary<string,object> Convert(this JObject source)
{
Dictionary<string,object> result = new();
foreach (KeyValuePair<string, JToken> kvp in source)
{
if (kvp.Value.HasValues) // aka if it has child tokens according to NewtonSoft.Json docs??
{
foreach (var childToken in kvp.Value.Children().OfType<JObject>())
{
childToken.Convert();
}
}
}
}
but as you can see I'm not doing anything with childTokens at the moment because I'm not sure how to keep the original JSON structure The reason I am trying to convert it, is because I have to do two of these mappings, and then map user-given keys of the one JSON object to the other (the values) So this part:
foreach (var prop in PropertiesToMap)
{
if (!dataTo.ContainsKey(prop.To) || !dataFrom.ContainsKey(prop.From)) continue;
dataTo[prop.To] = dataFrom[prop.From];
}
foreach (var prop in PropertiesToMap)
{
if (!dataTo.ContainsKey(prop.To) || !dataFrom.ContainsKey(prop.From)) continue;
dataTo[prop.To] = dataFrom[prop.From];
}
Please halp with my recursive function to map any json into a dictionary And afterwards, but this is optional for me, a query question
48 replies
CC#
Created by malkav on 2/16/2023 in #help
✅ Trying to trigger Azure Function with OpenApi
So right, never had an issue with this but now all of a sudden... (I might have done something wrong, but can't find it... Right.. So I created an Azure Function with OpenApi tags, so I can call the Azure function from ../api/swagger/ui and test the various parameters and such. The way I setup my OpenApi tags above the Azure Function is the way I always did things, so I can secure them later. But when using them in localhost I never had to Authorize before being able to push the blue Execute button. But right now I've got the blue button but it won't trigger anything, and above the function it says I need to authorize??? I don't have an ApiKey since it's currently localhost. Unless I am missing something?? Here's the OpenApi tags:
[FunctionName("Execute")]
[OpenApiOperation("Run", tags: new[] { "Run" }, Visibility = OpenApiVisibilityType.Important)]
[OpenApiSecurity("function", SecuritySchemeType.ApiKey, Name = "code", In = OpenApiSecurityLocationType.Query)]
[OpenApiRequestBody(contentType: "application/json; charset=utf-8", bodyType: typeof(RequestBody),
Description = "The example request JSON body", Example = typeof(RequestBodyExample))]
[OpenApiResponseWithBody(contentType: "application/json", bodyType: typeof(ResponseBody),
statusCode: HttpStatusCode.OK, Description = "The result", Example = typeof(ResponseBodyExample))]
public static async Task<IActionResult> RunAsync(
[FunctionName("Execute")]
[OpenApiOperation("Run", tags: new[] { "Run" }, Visibility = OpenApiVisibilityType.Important)]
[OpenApiSecurity("function", SecuritySchemeType.ApiKey, Name = "code", In = OpenApiSecurityLocationType.Query)]
[OpenApiRequestBody(contentType: "application/json; charset=utf-8", bodyType: typeof(RequestBody),
Description = "The example request JSON body", Example = typeof(RequestBodyExample))]
[OpenApiResponseWithBody(contentType: "application/json", bodyType: typeof(ResponseBody),
statusCode: HttpStatusCode.OK, Description = "The result", Example = typeof(ResponseBodyExample))]
public static async Task<IActionResult> RunAsync(
What am I missing?
1 replies
CC#
Created by malkav on 2/10/2023 in #help
❔ Trying to return the result of Fan Out Fan In Azure Function
So I've been trying to build my Azure function with a Fan-Out Fan-In method. But when the function completed I keep returning the wrong results. Which I figured since it's creating a new instance, and turning that into an instanceId. I kind of want the result of my [OrchestrationTrigger] to be returned to the http_start section of my Azure Function. Here is a simplified version of my current structure:
[FunctionName("Fetching")]
public static async Task<List<string>> RunFetching([OrchestrationTrigger] IDurableOrchestrationContext ctx, ILogger log)
{
// Some Code
}

[FunctionName("Fetching_Secondary")]
public static async Task<string[]> Secondary([ActivityTrigger] string input, ILogger log)
{
// Some code that returns to "Fetching"
}

[FunctionName("Fetching_HttpStart")]
public static async Task<IActionResult> HttpStart([HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequestMessage req, [DurableClient] IDurableOrchestrationClient starter, Ilogger log)
{
string input = await req.Content.ReadAsStringAsync();
try
{
var inputData = JsonConvert.DeserializeObject<object>(input): // This has other types but I figure irrelevant for now
var instanceId = await starter.StartNewAsync("Fetching", null, inputData);

return new OkObjectResult(await starter.CreateCheckStatusResponse(req, instanceId).Content.ReadAsStringAsync());
} catch (Exception e)
{
log.LogDebug(e.Message);
}
}
[FunctionName("Fetching")]
public static async Task<List<string>> RunFetching([OrchestrationTrigger] IDurableOrchestrationContext ctx, ILogger log)
{
// Some Code
}

[FunctionName("Fetching_Secondary")]
public static async Task<string[]> Secondary([ActivityTrigger] string input, ILogger log)
{
// Some code that returns to "Fetching"
}

[FunctionName("Fetching_HttpStart")]
public static async Task<IActionResult> HttpStart([HttpTrigger(AuthorizationLevel.Anonymous, "post")] HttpRequestMessage req, [DurableClient] IDurableOrchestrationClient starter, Ilogger log)
{
string input = await req.Content.ReadAsStringAsync();
try
{
var inputData = JsonConvert.DeserializeObject<object>(input): // This has other types but I figure irrelevant for now
var instanceId = await starter.StartNewAsync("Fetching", null, inputData);

return new OkObjectResult(await starter.CreateCheckStatusResponse(req, instanceId).Content.ReadAsStringAsync());
} catch (Exception e)
{
log.LogDebug(e.Message);
}
}
Now the issue I am having is that my "Fetching" function should return a List<string> but in my "Fetching_HttpStart" I am returning just information about the instances. How can I turn this so that it returns whatever my "fetching" is returning?
3 replies
CC#
Created by malkav on 2/7/2023 in #help
❔ ✅ Scrape all <table> </table> elements
I'm trying to use AngleSharp to scrape any url (that is given as parameter) for all table elements on that page's HTML code, and parse the contents into a json. Here's an example of what I'm trying to achieve:
<table>
<thead>
<tr>
<th scope="col">Header 1</th>
<th scope="col">Header 2</th>
<!-- etc -->
</tr>
</thead>
<tbody>
<tr>
<th>1</th>
<td>data</td>
<!-- etc -->
</tr>
<!-- etc -->
</tbody>
</table>
<table>
<thead>
<tr>
<th scope="col">Header 1</th>
<th scope="col">Header 2</th>
<!-- etc -->
</tr>
</thead>
<tbody>
<tr>
<th>1</th>
<td>data</td>
<!-- etc -->
</tr>
<!-- etc -->
</tbody>
</table>
the json output:
[
{
"Header 1": "1",
"Header 2": "data",
// etc
},
// etc
]
[
{
"Header 1": "1",
"Header 2": "data",
// etc
},
// etc
]
The code I'm trying so far seems to make it hard to reach this actual element, even when trying to use QuerySelectorAll("table")
45 replies