Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Just-In-Timeberlake
Aug 18, 2003
Having a really weird issue here, that I'm not even sure how to google for or dive into to see what is going on.

Have a recordset being returned from MSSQL that I'm loading into a DataTable. When I try to populate a string with one of the data fields the DataRow is showing that field is an empty array (so, db NULL I think) so it throws an error. The thing is when I run that stored procedure in SSMS the returned record most certainly has data in that field. If I wrap that output field in the stored procedure with an ISNULL(result, ' ') then the DataRow shows the data = ' ', even though in SSMS that data is not NULL in the result table.

Not really sure where the error is occurring. The ISNULL check makes me think in MSSQL but there's data being returned in the result set, so maybe it's in the DataRow? Any insight or where I can start looking for a solution would be most appreciated.

Adbot
ADBOT LOVES YOU

Just-In-Timeberlake
Aug 18, 2003

Pilsner posted:

This is very hard to understand for me. Can you give some code samples? What do you mean "try to populate a string with one of the data fields the DataRow is showing that field is an empty array"??


Yeah, sorry, wasn't sure how clear that was

code:
Dim row As DataRow = dt1.Rows(0)

Dim customer As String = row.Item("customerName")
When I hover over the "row" variable and look at the value in column "customerName" it shows {}

It's probably not really an empty array but how VS displays NULL because that's the error being thrown (can't convert null to string)

Munkeymon posted:

Your database driver might be setting an option that causes some operator to act differently than SSMS. Try running select @@options through both your driver and SSMS and see if they're different.


Thanks for this, not sure if it helps yet but it's a place to start looking at least. The settings are different, now to see if it makes any difference syncing them up.

Just-In-Timeberlake
Aug 18, 2003
Is there anything that updating to the latest version of Windows 10 would make this code now return a different value from what it was returning a couple of weeks ago (or on an entirely different computer running Windows 7, they used to match)

code:
	Using sha512 As New System.Security.Cryptography.SHA512Managed
            Return BitConverter.ToString(sha512.ComputeHash(data))
        End Using
The windows update is the only thing I can think of that I've done recently that would cause this. If I run a project on the Windows 7 machine and then copy that exact project over to the Windows 10 machine and run them the outputs are different.

Just-In-Timeberlake
Aug 18, 2003

EssOEss posted:

I see one thing here that might be different between the machines - whatever is in "data"!

If this does not lead to an obvious solution, post the full code with inputs that reproduces the issue.

Fair enough, I just wrote this to test it on each system

code:
    Sub Main()
        Using sha512 As New System.Security.Cryptography.SHA512Managed
            Console.WriteLine(BitConverter.ToString(sha512.ComputeHash(System.Text.Encoding.UTF8.GetBytes(("64338F8C-4EAF-474C-89F9-15F02A760C64").Reverse().ToString))))
        End Using
    End Sub
Now, if I just pass in that GUID into both Win10 & 7, the output matches.

This is used to create some salts so it actually calls another function to garble up some of the input ("data" variable in my previous post), so to mimic part of it I added the .Reverse() part up above and this is where the output differs between Windows versions

Windows 7, VS 2015, .NET 4.5.2
code:
3D-19-F3-F9-1B-57-61-FB-F0-02-9E-41-58-EB-FF-F7-9E-28-3F-B6-83-AE-EF-0F-8E-05-4B-27-F9-DC-A0-14-0E-47-2C-6B-D8-64-BC-3B-1F-B1-67-2E-0D-7D-53-2A-E9-B5-A1-54-4B-8D-2C-EB-3F-66-C4-8F-A6-FE-3B-1A
Windows 10, VS 2017, .NET 4.5.2
code:
4C-F2-B9-FF-25-3C-1B-27-FD-D1-8D-68-66-7F-59-4F-9F-B1-5A-A0-AB-A1-77-32-8E-67-E9-D1-D8-B4-7A-C3-3B-94-46-A1-B7-2E-E2-A8-19-E2-33-64-4F-C6-2D-30-C7-B2-43-3E-15-4E-4D-2B-DB-C9-0D-16-71-7D-B6-5C
The code is identical, I just copied it from one VM to another. So it looks like the hashing isn't the issue, but something is up with what is being hashed when the string gets manipulated. Any ideas?

edit:

If I just run this code:

code:
	Console.WriteLine(("abcdefghijklmnopqrstuvwxyz").Reverse())
I get 2 different outputs

Windows 7:
code:
	System.Linq.Enumerable+<ReverseIterator>d__74`1[System.Char]
Windows 10:
code:
	System.Linq.Enumerable+<ReverseIterator>d__75`1[System.Char]
So, why is Windows 10 outputting something different? I took a snapshot before installing the updates so worst comes to worst I can roll it back, but that means I can never update that VM and I'll be stuck dismissing the nag screen to update every other day.

Just-In-Timeberlake fucked around with this message at 21:34 on Feb 12, 2018

Just-In-Timeberlake
Aug 18, 2003

EssOEss posted:

Oh! If you print out your "data" variable after .Reverse().ToString(), you will find the reason for your conundrum:

code:
System.Linq.Enumerable+<ReverseIterator>d__75`1[System.Char]
The call to .ToString() just returns the type of the iterator, not the value! You need to call the String constructor to actually turn it back into a string.

code:
Console.WriteLine(BitConverter.ToString(sha512.ComputeHash(System.Text.Encoding.UTF8.GetBytes(new string(("64338F8C-4EAF-474C-89F9-15F02A760C64").Reverse().ToArray())))));
I assume you do not actually want to use the type name here, of course. That would be silly.

Ok, I can work around that, thanks for pointing me in the right direction.

Any idea why one is different than the other between Windows versions?

Just-In-Timeberlake
Aug 18, 2003

redleader posted:

How sure are you that data is the same between the two systems? Could there be some invisible characters (e.g. non-breaking spaces) in one of them? You could try comparing a hex dump of the two strings.

Find a third machine and see what that one does.

I literally copied and pasted from one VM to the other, can't see how something extraneous got in there.

Anyway, the problem is solved, I'm just curious why the <ReverseIterator> type returned is different between Windows versions.

Just-In-Timeberlake
Aug 18, 2003
I guess this is a .NET question? If not, let me know.

I have a .netCore AWS Lambda project and I was wondering if there's a way to have different deployment config files (like in ASP.NET, web.debug.config, web.release.config) so I can deploy to different Lambda apps? Like have the following files:

aws-lambda-tools-defaults.development.json => deploy to dev
aws-lambda-tools-defaults.staging.json => deploy to staging
aws-lambda-tools-defaults.production.json => deploy to production

or using the serverless.template file? I can't quite seem to find the documentation I need for this.

Just-In-Timeberlake
Aug 18, 2003

adaz posted:

dotnet lambda deploy-function -C staging

Replacing staging with whatever configs (staging, production, development) you've defined.

exactly what I was looking for, thanks

Just-In-Timeberlake
Aug 18, 2003

Riot Bimbo posted:

At some point in September, my brain finally clicked into place and began building new routines to replace covid-destroyed ones.

One of my partners has a background in self-taught coding, and informed me that visual studio had a good free edition these days, and then I blasted through the intro to c# course on codecademy.

Right now, I'm trying to figure out what my next step is. I am more or less self directed right now. Learning how to do stuff that wasn't covered, or covered well, by the course i've taken. The followup offering on codecademy, is about c# and ASP, and while it seems like a loving cool next step, their teaching environment has a hideously low user cap for the ASP stuff, and tbh the answer checker is busted as gently caress, so I gave up.

I have an ancient java-based comp-sci course in my past; in my noggin, that probably made getting back to this point *far* easier and faster than it is for most starting blind, but yeah... I've got a "C# masterclass" course my partner picked up, where a guy awkwardly puts code on the screen without explaining anything. That's useful as a jumping off point, and I've found some stuff on Skillshare that's similarly useful for short-topic dives.

Insofar as I actually know what I want, I think I'm looking for, I think I'd like to find some solid resources on LINQ+C# operations, because that's what my course finished on, but did frustratingly little with.

I'd also just generally like resources that might firm up a foundation I can turn into a career. I want to also make like, 2D games as a hobby, and anything in that direction is fine, but I'm principally trying to get skills to escape the culinary industry, as I've been made aware that I could just... do that.

To add to the previous answer, check out this blog post with links to a git repo

https://medium.com/@michaeldimoudis...er-6d31cdd6d3f5

The git repo code will handle all the grunt work to spin up a serverless AWS Lambda/CloudFormation stack with a CloudWatch lambda warmer to keep the functions from going dormant.

You get something like 1M lambda function calls/month so it won’t cost anything. Spin up a cheap/free RDS instance and you can work on your database integration.

AWS Lambda makes API development a cinch.

Just-In-Timeberlake
Aug 18, 2003

Riot Bimbo posted:

I feel like a doofus but I am not at a point where this blog post provides enough info to get this running properly right off the bat. I think I'll go a little meta and endeavor to learn how to understand what the hell I'm doing here. That's the best I can do, since this is kind of the direction I wanna go.

You can download the code and just run it locally with no extra configuration and use Postman to test your code.

When you want to get to the point of spinning up a serverless stack on AWS you can mess around with the config files (it’s actually not as hard as it seems)

Just-In-Timeberlake
Aug 18, 2003
Is there a way to get either the HttpContext or just the URL in the Startup.cs of a net core api? I'm trying to load a different configuration based on which environment it's deployed to (ie. dev.mysite.com vs. staging.mysite.com).

One wouldn't think this would be such a pain in the rear end, but gently caress me if I can't figure it out.

Just-In-Timeberlake
Aug 18, 2003
Anybody have any Serilog knowledge/experience?

I have Serilog working locally (sends logs to Elasticsearch), but when I deploy to AWS Lambda, I am getting the following error in the Cloudwatch Logs: System.InvalidOperationException: Unable to resolve service for type 'Serilog.Extensions.Hosting.DiagnosticContext' while attempting to activate 'Serilog.AspNetCore.RequestLoggingMiddleware

Any ideas what the issue could be? Kinda hard to debug this.

Just-In-Timeberlake
Aug 18, 2003

adaz posted:

I only use serilog for a bit before I swapped to NLog, but that looks like you didn't properly setup Serilog. In your app.startup for the 'cloud' config or whatever you use for your lambda are you UseSerilog in your host builder?. I took a look at that third party extension you're using and its just expecting that Diagnostic Context to already be there, and it's not

I think I've got it all set up right looking at that, otherwise I don't think it would work at all, but it does work on my dev machine.

I decided to pare it down to the basics, I removed anything to do with Serilog except the base Serilog.AspNetCore package, and used the most bare bones configuration necessary to log something, and I'm still getting the same error.

LocalEntryPoint.cs:

code:
	public static void Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
                .WriteTo.Console()
                .CreateLogger();

            try
            {
                Log.Information("Starting up");

                CreateHostBuilder(args).Build().Run();
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Application start-up failed");
            }
            finally
            {
                Log.CloseAndFlush();
            }

            CreateHostBuilder(args).Build().Run();
        }

	public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .UseSerilog()
		.ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
and in Startup.cs

code:
	public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
           if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            
            app.UseHttpsRedirection();

            app.UseSerilogRequestLogging();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

        }

Just-In-Timeberlake
Aug 18, 2003
iirc SQL Server will happily use the maximum resources you give it

Just-In-Timeberlake
Aug 18, 2003

GI_Clutch posted:

For example, let's say I built some kind of swiss army knife console application with a variety of utilities in it. The user is presented with with a menu to select the task they would like to perform. Each of the various tasks does something completely different with its own set of dependencies (maybe they hit different database models, work with Windows services, read/build flat files, etc.) In this situation, there is a single entry point. I don't know what is going to be needed until the user makes a selection.

lol'ing hard because I made an application for work that does exactly this and named it Swiss Army Knife (SAK because I'm a child :imunfunny: )

I have no real insight as I made it out of a necessity to get some things quickly done so I'm sure anybody looking at the code would consider it a mess.

Just-In-Timeberlake
Aug 18, 2003

Hammerite posted:

drat, it does the right thing on net core 3.1 as well. Just Framework where it doesn't. Unfortunately the place where I wanted to do this is a framework app. Well, I will just have to do without.

Create a .dll in netCore or .NET 5 that does what you want and reference it? I’ve managed to make things work that way when there was no way to switch to a higher framework that supported TLS2.1

Just-In-Timeberlake
Aug 18, 2003
I feel like I'm missing something simple here, but not sure what. I'm trying to use an online service to convert HTML to PDF, and then return a base64 encoded string of the pdf. I can make the call fine, but when I put the returned base64 string into a decoder, I'm only getting like the first 20% of the pdf, the rest is blank. Using Postman and hitting the HtmlToPdf api directly returns the full pdf. Looking at the base64 string, there's a section of "AAAAAAAAAA......etc" in there, so obviously something is going wrong in the encoding. I suspect it's that I'm encoding the entire response and not just the .pdf part, but I'm not sure, or how to get just that part. Here's the code for the call:

code:
internal async Task<string> ConvertHtmlToPdfAsync(string html)
        {
	
	    string apiKey = "key here";

            try
            {
                byte[] dataStream = Encoding.UTF8.GetBytes($"html={html}");
                
                var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://htmlpdfapi.com/api/v1/pdf");
                
                httpWebRequest.ContentType = "application/json";
                httpWebRequest.Headers.Add("Authentication", apiKey);
                httpWebRequest.Method = "POST";
                httpWebRequest.ContentType = "application/x-www-form-urlencoded";
                httpWebRequest.ContentLength = dataStream.Length;

                using (Stream newStream = await httpWebRequest.GetRequestStreamAsync()) {
                    newStream.Write(dataStream, 0, dataStream.Length);
                };

                var response = await httpWebRequest.GetResponseAsync();
                
                byte[] bytes;
                using (var memoryStream = new MemoryStream())
                {
                    response.GetResponseStream().CopyTo(memoryStream);
                    bytes = memoryStream.ToArray();
                }

                return Convert.ToBase64String(bytes);

            } catch (Exception ex)
            {
                return "";
            }
            
        }

Just-In-Timeberlake
Aug 18, 2003
I rewrote it using HttpClient and it works now, go figure

code:
internal async Task<string> ConvertHtmlToPdfAsync(string html)
        {
            string apiKey = "key";

            try
            {
                using (HttpClient httpClient = new HttpClient())
                {
                    httpClient.DefaultRequestHeaders.Add("Authentication", apiKey);

                    var response = await httpClient.PostAsync("https://htmlpdfapi.com/api/v1/pdf", 
                        new FormUrlEncodedContent(new[]
                            {
                                new KeyValuePair<string, string>("html", html)
                            }
                        ));

                    return Convert.ToBase64String(await response.Content.ReadAsByteArrayAsync());

                }
                
            } catch (Exception ex)
            {
                return "";
            }
            
        }

Just-In-Timeberlake
Aug 18, 2003
Thanks for the heads up on all that.


insta posted:

Glad they didn't waste too much time making the esoteric thing of "web requests" too easy.

for real, there's like 20 different ways to do the same thing.

Just-In-Timeberlake
Aug 18, 2003

LongSack posted:

Umm so am i doing this wrong:
C# code:
using var client = new HttpClient();
client.AddToken(_storage);
var uri = _helper.Create(“Foo”,”ById”,fooId);
using var response = await client.GetAsync(uri);
…

according to everything I read today to make the switch to HttpClientFactory, this will eventually bite you in the rear end, with the bonus knowing that going by the documentation, you're doing the right thing.

Just-In-Timeberlake
Aug 18, 2003

Supersonic posted:

I'm writing an api wrapper and am currently trying to deserialize this JSON response: http://data.nba.net/json/bios/player_201935.json

I'm able to get the response correctly, but my model keeps getting null properties. Is there a step I'm missing in this code?

https://pastebin.com/5g6c32sR

I'm using this deserializer (https://json2csharp.com/json-to-csharp) which outputs a Bio class and a Root class containing a bio object to model the DTOs after.

I’m not near a machine to mess with it so I can’t help with the null issue, but you should stop doing what you’re doing with the HttpClient before you get too far along and it becomes a real pain in the rear end to fix.

https://www.aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/

Just-In-Timeberlake
Aug 18, 2003
Any ASP.NET experts here? Particularly with the web.config and IIS10?

We have a custom error page to handle any errors, and we need that initial form data to go along for the ride.

This works when deployed to our old Server 2012 instance on AWS, and run on localhost via Visual Studio and IISExpress on a Server 2019 machine:

code:
	<customErrors defaultRedirect="~/errors/errorHandler.aspx" mode="On" redirectMode="ResponseRewrite">
        </customErrors>
However, when deployed to an AWS Server 2019/IIS10 instance, while it does go to the error handler page, the form data is not being transferred. I've verified this by using Response.Write(Request.Form()), just blank.

I feel like I'm missing some setting in IIS10, but Googling isn't bringing anything up.

Just-In-Timeberlake
Aug 18, 2003
Can anybody provide some insight as to why this FileSystemWatcher code won't fire on change or rename events, but works just fine for the created event? This folder is an FTP folder (network share, maybe that?) that customers upload files to, there's a delay before processing since some files are large and I want the files to be fully uploaded before trying to process them. I need the rename/change to fire because some FTP clients will upload with a .filepart extension, which then gets changed to the actual filetype extension, which then throws an error because the e.FullPath still has the .filepart extension on the raised create event but that file no longer exists so you get a System.IO.FileNotFoundException. Or maybe there's some other way to deal with that scenario I'm unaware of.

code:
        protected async void OnChanged(object source, FileSystemEventArgs e)
        {
            List<String> acceptedFileTypes = new List<string>() { ".csv", ".txt", ".json" };

            if (e.ChangeType == WatcherChangeTypes.Created				/* fires */
                || e.ChangeType == WatcherChangeTypes.Renamed			/* does not fire */
                || e.ChangeType == WatcherChangeTypes.Changed)			/* does not fire */
            {
                try
                {
                    int delay = 20000;
                    await Task.Delay(delay);

                    if (acceptedFileTypes.FindAll(x => x == System.IO.Path.GetExtension(e.FullPath)).Count > 0)
                    {
                        //do some things

                    }

                }
                catch (Exception ex)
                {
                    // something bad happened that stops the service from starting
                    Log.ForContext("MethodName", System.Reflection.MethodInfo.GetCurrentMethod()).Error("{ex}", ex);

                }

            }
            
        }
These are the notify filters I have assigned:

code:
		NotifyFilter = NotifyFilters.CreationTime | NotifyFilters.LastWrite | NotifyFilters.FileName |
                                      NotifyFilters.DirectoryName | NotifyFilters.LastAccess | NotifyFilters.LastWrite
e: figured it out, wasn't binding the correct event handler

Just-In-Timeberlake fucked around with this message at 15:57 on Jan 31, 2022

Just-In-Timeberlake
Aug 18, 2003
Ok, how the gently caress do you get the request body in a .netCore3.1 api controller? Or just the form part of the request body.

Everything I'm finding online starts and ends with saying to add this to startup.cs

code:
	app.Use((context, next) =>
    		{
        	   context.Request.EnableBuffering();
        	   return next();
    		});

	app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
And..then...?

I can assign the context in the app.Use() part to a static class variable and access it from anywhere, but that seems like the world's second worst idea, only bested by getting involved in a land war in Asia.

Jesus gently caress it should not be this hard.

Just-In-Timeberlake
Aug 18, 2003

Kyte posted:

ControllerBase has Request which has both Form and Body?
Are you not inheriting from ControllerBase?

Well I feel dumb, mainly because I thought it wasn't going to work because VS2022, while often amazing, also slaps red squiggly lines all over valid poo poo.

Did a rebuild and the lines went away.

Thanks, I'm a dope.

Just-In-Timeberlake
Aug 18, 2003
I'd just like to say it's pretty amazing what an absolute pig VS2022 is when it comes to resources.

Just-In-Timeberlake
Aug 18, 2003

riichiee posted:

I've got a WPF .NET Framework application that needs to be distrubuted externally.

Previously I just published it on an internal network share with ClickOnce, and auto-update just took care of itself.

Any ideas on what the cleanest, most reliable way to do this is?

We've got a sharepoint site that the external parties have access to, was thinking of hosting the files there. Not sure how well that would work with the ClickOnce auto-update though?

I considered hosting it on Azure blobs, but whenever setup.exe is downloaded from there, most anti-virus's throw a fit at having to run it. I could probably spin up an instance of IIS for it, but that feels like overkill.

Using Squirrel + Github involves downgrading to .NET Framework 4.6.1, which I'm not sure what knock-on effects that'll have.

Maybe I'm over complicating this!?

Any ideas?

I currently do this by publishing the app to an Amazon S3 bucket, but that'll probably give you the same issue as using an Azure blob solution.

Are you signing the ClickOnce manifests? Pretty sure our users only have to explicitly allow it on the first install, after that it just runs/updates without issue.

Just-In-Timeberlake
Aug 18, 2003

fuf posted:

ok so I should probably just come up with my own little logging service

lol no, don't try to reinvent the wheel, I guarantee what you want exists already.

Here, check this out using Serilog:

https://stackoverflow.com/questions/35567814/is-it-possible-to-display-serilog-log-in-the-programs-gui

Just-In-Timeberlake
Aug 18, 2003

rarbatrol posted:

Man I wish we had performance problems as subtle as that. I'm dealing with legacy code continuously being glued together in new and terrifying ways, and we keep finding code that performs a database lookup per record, which itself usually comes from an initial database lookup.

ah, you’re me, good to know.

Just-In-Timeberlake
Aug 18, 2003

fuf posted:

I'm trying to test a .net app using my phone so I want to access it via the local network.

I added this to launchSettings.json:
"applicationUrl": "http://0.0.0.0:5001",

and it works for accessing the app via http://192.168.0.24:5001/ but it doesn't work with https.

Is there a way to get https working? I read something about https not working with IP addresses because it needs a domain name? Do I need to give my development PC a domain name on the local network somehow?

Doesn't the HTTPS endpoint need to be on a different port? In ASP.NET in the applicationhost.config you need something like this:

code:
<bindings>
	<binding protocol="http" bindingInformation="*:3778:localhost" />
        <binding protocol="https" bindingInformation="*:44345:localhost" />
</bindings>

Just-In-Timeberlake
Aug 18, 2003

zokie posted:

I would really like to make the application window me an exotic shape.


There are easier ways to make Winamp skins

Just-In-Timeberlake
Aug 18, 2003

Hammerite posted:

Visual Studio on my work machine is frequently getting itself into a state where it doesn't acknowledge certain keyboard inputs. It accepts printable characters, but it won't react to (for example) the enter key, the delete or backspace key, function keys, or combinations of meta and regular keys. The only way to fix it is to close and reopen VS. Anyone else had this?

What version? Used to happen to me on 2019 but I can't recall it happening since I upgraded to 2022.

Just-In-Timeberlake
Aug 18, 2003

LongSack posted:

CORS question.

I have an API running as an Azure app service. I also have a web front end in React, also running on an Azure web app.

When I first "installed" the two apps, everything worked fine. But suddenly I am getting CORS errors, and I have no clue as to why. I've tried using .AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod() to no avail. I originally used a named policy, but switched to a default policy. with no luck.

First appsettings.json:
code:
  "CORSOrigins": [
    "http://localhost:3000",
    "https://localhost:3000",
    "http://jimcoretailsite.azurewebsites.net",
    "https://jimcoretailsite.azurewebsites.net",
    "http://jimcoemployeeportal.azurewebsites.net",
    "https://jimcoemployeeportal.azurewebsites.net"
  ],
now the relevant sections of Program.cs:
C# code:
var origins = builder.Configuration.GetSection("CORSOrigins").Get<string[]>();
if (origins is null || !origins.Any())
{
  builder.Services.AddCors(options =>
  options.AddDefaultPolicy(builder =>
    builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod()));
}
else
{
  builder.Services.AddCors(options =>
    options.AddDefaultPolicy(builder =>
    builder.WithOrigins(origins)
      .AllowAnyHeader()
      .AllowAnyMethod()));
}

...

app.UseCors();
and the error message:
Access to fetch at 'https://jimcoapi.azurewebsites.net/api/v1/Product/Random/3' from origin 'https://jimcoretailsite.azurewebsites.net' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled..

The site origin listed in the error message is one of the ones in the origins list.

I am sorely confused, especially since this all used to work.

Ideas?

Use your browser tools to start looking at the request/response header info, try multiple browsers since they might say slightly different things that might lead you to the solution. I've had this nonsense happen, and IE11 of all things gave me a message (that no other browser did) that was the clue I needed.

Just-In-Timeberlake
Aug 18, 2003

worms butthole guy posted:

So I tried the above suggestions and I think I got closer to what I was trying to accomplish...I think. And i'm stuck again :v:. So I ended up with:

code:
List<ChartMap> Gems = new List<ChartMap>() { new ChartMap() {
            Beat = "00:00",
            Note = 2,
            loc = new List<int> {200, 400},
            PowerUp = false
        }, new ChartMap() {
            Beat = "00:05",
            Note = 1,
            loc = new List<int> {100, 400},
            PowerUp = false
        }, new ChartMap() {
            Beat = "00:08",
            Note = 2,
            loc = new List<int> {200, 200},
            PowerUp = false
        },
        new ChartMap() {
            Beat = "00:12",
            Note = 1,
            loc = new List<int> {200, 400},
            PowerUp = false
        }};
The issue i'm having now is trying to find something in this List using like:

code:
// beat = "00:05";
Debug.WriteLine(Gems.Contains(new ChartMap { Beat = beat }));
But I don't get any result for that except false. So hoping one of you kind goons can help me out again! :v

shouldn’t that be Beat == beat?

Just-In-Timeberlake
Aug 18, 2003

epswing posted:

Tell me about your favourite HTML -> PDF converter! I haven't had to do this in a while, notably since the shift from .NET Framework to .NET Core. Has the dotnetcore community gravitated towards a particularly good solution/library? Or is using a 3rd party service the way to go these days?

Edit: I should mention the environment here is an .NET 6 ASP.NET site running as a Web App in Azure. I'm familiar with tools like wkhtmltopdf.exe but I don't think that'd work in this case (there's no filesystem/OS to play with). The html will come from some url, and the resulting pdf will be stored in some cloud storage bucket.

We use https://www.api2pdf.com/, cheap, fast, and accurately renders the HTML => PDF, and the generated PDFs get stored in an S3 bucket.

They have SDKs for python, node, php, c# and java and several different rendering engines to choose from:

https://app.swaggerhub.com/apis-docs/api2pdf/api2pdf/2.0.0

Adbot
ADBOT LOVES YOU

Just-In-Timeberlake
Aug 18, 2003

Surprise T Rex posted:

What's the state of the art for creating PDFs in C# code now? Ideally one I can run from a serverless Azure Function or AWS Lambda. At work we do some of this using rendering Razor templates to HTML and feeding it to Puppeteer(?) to basically fake a print-to-PDF, but that requires us to run it as a docker container so we can bundle a headless Chrome with it and that seems like more effort than is necessary.

QuestPDF seems good but new and I'm not sure if I'm just being blinded by it looking semi-modern.

I recommended api2pdf a few posts up, I still recommend it. It costs next to nothing (we generated ~50k pdfs in December, cost ~$30), multiple converters and .pdf utilities to choose from, and I don't have to maintain poo poo.

https://app.swaggerhub.com/apis-docs/api2pdf/api2pdf/2.0.0

I found the Wkhtmltopdf converter to do the best job in accurately converting HTML to a .pdf

Just-In-Timeberlake fucked around with this message at 14:08 on Jan 9, 2024

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply