Unable to inject javascript into Swagger documentation - c#

So I've seen this question posed before, but I feel like I have a specific context that warrants posing the question. I could be risking getting a good ol' stack overflow scolding, but here goes. In either case, I feel like it's going to likely be a one-line fix, so I'm prepared to be humbled. Quick profile of the system:
AspNetCore: 2.2.0
Swashbuckle: 4.0.1
Filename: ./SwaggerExtensions/test.js (only trying to get a console log verification at this point)
Inside Configure Method
app.UseSwaggerUI(o =>
{
o.SwaggerEndpoint($"/docs/swagger.json", $"{ApplicationName} {_applicationVersion}");
o.InjectJavascript("identity.SwaggerExtensions.test.js");
});
Additionally, I have invoked the UseStaticFiles middleware at the top of the Configure method. I have seen other implementations that require the use of the specific assembly (e.g. SwaggerConfig), but the version I'm using only calls for the 'logical name' of the file path (appName.directory.filename.type), but the InjectJavascript method for the version I'm using has no parameter for the assembly, only the file and an optional parameter for the type (e.g., text/javascript):
I feel like I've followed other posts about this pretty closely and I can't seem to make any headway on what appears to be a pretty straightforward implementation.
Additionally, the js file is being appended to the head of the html, but I imagine the format should be converted to a regular path. I have also set the Build Action to Embedded Resource. I feel like I've been chasing my tail for the last day or so trying to get this working so I can move on to implementing an auth flow.

Related

How to trigger HTTP requests based on OpenAPI .json files?

I'm looking for a way to interpret an OpenAPI .json definition. This is my workflow:
The user provides the .json file during runtime.
I would like to show all existing endpoints, their HTTP methods, parameters and expected bodies like e.g. Postman or Swagger are doing it.
The user can choose one endpoint and an HTTP method, then provide all needed parameters and send a request. As soon as I retrieve the response I will show it as plain text to the user.
The user can choose an endpoint and HTTP method and I will serialize the information needed to do step 3. later again without reading the whole .json file again.
I googled and tested a few libraries but did not find one or multiple which do exactly what I'm looking for.
I think OpenAPI.NET might do the reading job necessary for step 2.
Regarding the part that's able to trigger the HTTP request I only found fully-fledged "Client Creators" which take an OpenAPI .json and create C# code which can then be compiled to get a full client library. Many of these "Client Creators" are also build up on other tech stacks (e.g. Java) and make it difficult to use from a .Net application.
I had a deeper look into NSwag which is written in C# and can be installed as a NuGet but again this one creates C# code that needs to be compiled and it also seems it creates way more then I need (deserialization and handling of Non-OK status codes etc.)
I would just need a way to create something like a System.Net.Http.HttpRequestMessage or RestSharp.RestRequest. I could have a look into what it needs to create them by my own but I fear to reinvent the wheel and miss some more specific parts of the OpenAPI specification.
Do you know any libraries that would help me achieving my workflow but especially step 3 and step 4 of it?

How to pass experimental_allow_proto3_optional for C# <proto/> definitions to enable optional in proto3?

I've looked everywhere for this. The C# grpc people don't know how to do it, and point to the grpc/grpc people for the tooling but you're not allowed to ask questions there. I guess I could phrase this as a feature but that feels like cheating. (please add documentation too show how...)
How does one pass the parameter for this to C# grpc in the <proto> definition so that we can use the optional keyword?
Thanks!
As for January 2021, the only - yet hacky - way around this is to make your proto filename (or a directory name) contain the string test_proto3_optional, as pointed out by protobuf documentation:
If you try to run protoc on a file with proto3 optional fields, you will get an error because the feature is still experimental. [...] There are two options for getting around this error:
Pass --experimental_allow_proto3_optional to protoc.
Make your filename (or a directory name) contain the string test_proto3_optional. This indicates that the proto file is specifically for testing proto3 optional support, so the check is suppressed.
For more information see #977 (grpc-dotnet), #19164 (AspNetCore.Docs) and #23686 (grpc) issues.

Is there a way to produce executables from an existing Antlr4 grammar within expressions from the user?

I've already an existing application, in which I use Antlr4 in order to declare a customized grammar, compile the .g4 files into our c# base parser and lexer and also I've implemented the visitors for expression parsing.
The question is about finding a way to change the behavior from interpretation to compilation.
The way the app works today, we receive an expression from our users (in the customized grammar format), pass it through Antlr4 implementations in order to get our visitors running and executing the expression. This is a very repetitive process, considering the same expression gets evaluated over and over with just different arguments, the implemented logic is just the same.
I'd like to ask about if I could compile the provided expression of my users, save the compiled artifact so I can load it up and call it instead of parsing their expressions every time.
This is similar I do with C# programming, considering that I produce a DLL file that will get loaded up and executed later, without needing to get interpreted every time (not considering JIT at this context ;).
Hope I made my self clear enough about that.
It's not a problem to change architecture for this implementation, so we do need a "facelift" on the project, because of performance issues. Our customers use to produce very large expressions, which take lots of memory to be parsed and are causing some issues at runtime.
Thanks a lot.
After some extra time analysing the implementation and also the usage we have of AntLr, I could see that even though I could find a way to compile expressions analysis, the output results wouldn't be executable for our scenario, because of many usages of local libraries.
The path I choose to run on was to create, dynamicaly, C# code while visiting AntLr expression navigation, through visit methods overrides and, later, compile this C# code into a memory assembly, so I can locate the execution class, create instance and invoke it's execute method. Also I'm using Rosyln to achieve this approach.

Exclude other methods, variables and classes that are not needed for your method to work

You load a foreign code example with libraries attached to it in Visual Studio. Now there is a method that you want to reuse in your code. Is there a function in VS that lets you strip the code from all unnecessary code to only have code left that is necessary for your current method to run?
It is not about the library. Loading a .sln or .csproj and having classes over classes when you just want one method out of it is a waste of performance, ram and space. It is about code you can easily omit or references(what I call libraries) you can easily omit. A part-question of this is: Which "using" statement do you need that is only necessary for your current method and the methods that pass paramaters to it? In short, showing relevant code only. Code that is tied to each other.
Let's use an example: You go to github and download source code in c#. Let's call the solution S. You open S in Visual Studio. You don't disassemble, you just load the source code of S, that is there in plain text. Then you find a method M - in plain text - that you want to use. M contains some objects whose classes were defined somewhere in the project. The goal is to recreate the surrounding only for this method to copy & paste it into my own solution without having red underlined words in almost every line within the method
after reading the question and the comments, I think I have a vague idea what you are referring to.
In case we ignore the context of the method you are referring, you can extract any code piece from a "library" by using a .NET decompiler and assembly browser.
There are many of them for free, such as:
dotPeek,
ILSpy
...
This will allow you to see the method's code. From there on, you can proceed as you like. In case your copy the method to your code base, you might still have to change it a bit in order to adapt it to work with your objects and context. If you don't, this will give you insight on how the method works and might help you to understand the logic, so you can write your own.
Disclaimer: With this post, I am pointing out that it is possible to extract code from an assembly. I am not discussing the ethics or legal perspective behind such actions.
Hope this helps,
Happy Coding!
If it`s just one method, look at the source code and copy it to your libarary. Make sure you make a comment where you obtained the code and who has the copyright! Don't forget to include the licence, which you should have done with a libary reference anyway.
That said it is currently not (official) possible to automaticly remove unused public declared code from a library (assembly). This process is called Treeshaking by the way. Exception: .NET Native.
But .NET Native is only available for Windows Store Apps. You can read more about it here.
That said, we have the JIT (Just in Time)-Compiler which is realy smart. I wouldn't worry about a few KB library code. Spend your time optimizing your SQL Queries and other bottlenecks. The classes are only loaded, when you actualy use them.
Using some unstable solutions or maintaining a fork of a library, where you use more then one method (with no documentation and no expertise, since it is your own fork) isn't worth the headache, you will have!
If you realy want to go the route of removing everything you do not want, you can open the solution, declare everything as internal (search and replace is your friend) and restore the parts to public, which are giving you are Buildtime error / Runtime error (Reflection). Then remove everything which is internal. There are several DesignTime tools like Resharper, which can remove Dead Code.
But as I said, it's not worth it!
For .NET Core users, in 6-8 weeks, we have the .NET IL Linker as spender has commented, it looks promising. What does this mean? The .NET framework evolves from time to time. Let it envolve and look at your productivity in the meantime.

Looking for a Command Line Argument Parser for .NET [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
I'm looking for a command line argument parser, such as "Command line parser" from http://www.sellsbrothers.com/tools/Genghis/ .
Features I'm looking for:
Auto-generation of usage
Should able to check required and optional parameters
Parameters should support IEnumerable with separator support
Should support flag parameters
Would be nice to support combining parameters such as "/fx" == "/f /x"
Would be nice to not force for a space after a parameter such as "/ftest.txt" == "/f test.txt"
P.S :
"Command line parser" is quite good, I really like the design of it but there is no documentation, no new updates and I couldn't figure out to do certain stuff such as how to check for required parameters.
My personal favourite 3rd party commandline parsing library is Command Line Parser and I assume this is the one you are referring to. The most recent release was less than 2 months ago and there are regular commits. If you want a more mature offering you could check out the console library in the mono project (sorry I can't seem to find a direct link to the namespace at the moment, but its a part of the mono framework)
Have a look at ndesk.options.
It is called Mono.Options now.
A popular and pretty comprehensive C command-line parser is GNU getopt. This has been ported (or cloned) for C#/.Net several times. Some of these include:
getopt# on freshmeat.net
C# getopt at PHPGuru
XGetoptCS on CodeProject
GetOpt for .NET on CodeProject
Getopt C#.NET on Codeplex
Take your pick! There are several others, and google can tell you about those,
Sadly there's no built in support for handling that in a standard manner. Have you looked into PowerShell? I bet there's a class in that shell which does exactly what you want or something similar.
Edit: as fatcat1111 points out, this feature did not ship with the final version of .net 4.0.
C# 4.0 has a pretty good one. Probably not very helpful yet, but you might want to consider looking at something that will make the jump to the built in one easy when it comes out. Bart De Smet talked about it on his
B# blog
I suggest NDesk.Options
look here:
Best way to parse command line arguments in C#?
Consider that once you start using this parser, you'll either have to maintain it yourself, or else depend on someone else to maintain it for you. You may be better off writing your own, starting from your most critical, immediate, requirements. I've found that it doesn't take too much work to produce some fairly complicated command-line parsing for most console-based applications I've worked on.
I've also found that when the parsing gets too complicated, it may be time to stop using the command line.
I'm betting this is not quite what you're looking for, but:
Somebody here had that problem, and his first thought was "hey, ocaml has a pretty good one!", and quickly ported it to F#.
I'm using the parser out of the C# 3.0 cookbook.
All the examples from this book can be downloaded here:
http://examples.oreilly.com/9780596516109/
Search for 'Arguments' and you'll find it. You have to do some little code changes to get it out of the whole thing into your own class, but this is no big problem.
It supports all your points except the last two ones (parameter combining & missing space).
The BizArk library contains a command-line parser.
Basically you just create a class that inherits from CmdLineObject, add properties that you want populated from the command-line, add a CmdLineArgAttribute to the properties, then call Initialize in your program. It supports ClickOnce URL arguments too!
Features (from the site)...
Automatic initialization: Class properties are automatically set based on the command-line arguments.
Default properties: Send in a value without specifying the property name.
Value conversion: Uses the powerful ConvertEx class also included in BizArk to convert values to the proper type.
Boolean flags. Flags can be specified by simply using the argument (ex, /b for true and /b- for false) or by adding the value true/false, yes/no, etc.
Argument arrays. Simply add multiple values after the command-line name to set a property that is defined as an array. Ex, /x 1 2 3 will populate x with the array { 1, 2, 3 } (assuming x is defined as an array of integers).
Command-line aliases: A property can support multiple command-line aliases for it. For example, Help uses the alias ?.
Partial name recognition. You don’t need to spell out the full name or alias, just spell enough for the parser to disambiguate the property/alias from the others.
Supports ClickOnce: Can initialize properties even when they are specified as the query string in a URL for ClickOnce deployed applications. The command-line initialization method will detect if it is running as ClickOnce or not so your code doesn’t need to change when using it.
Automatically creates /? help: This includes nice formatting that takes into account the width of the console.
Load/Save command-line arguments to a file: This is especially useful if you have multiple large, complex sets of command-line arguments that you want to run multiple times.
I'm a fan of the C# port to OptParse, a built in library in Python. It's rather simple to use compared to most of the other suggestions here and contains a number of useful features in addition to just auto parsing.
You may like my one Rug.Cmd
Easy to use and expandable command line argument parser. Handles: Bool, Plus / Minus, String, String List, CSV, Enumeration.
Built in '/?' help mode.
Built in '/??' and '/?D' document generator modes.
static void Main(string[] args)
{
// create the argument parser
ArgumentParser parser = new ArgumentParser("ArgumentExample", "Example of argument parsing");
// create the argument for a string
StringArgument StringArg = new StringArgument("String", "Example string argument", "This argument demonstrates string arguments");
// add the argument to the parser
parser.Add("/", "String", StringArg);
// parse arguemnts
parser.Parse(args);
// did the parser detect a /? argument
if (parser.HelpMode == false)
{
// was the string argument defined
if (StringArg.Defined == true)
{
// write its value
RC.WriteLine("String argument was defined");
RC.WriteLine(StringArg.Value);
}
}
}
Edit: This is my project and as such this answer should not be seen as an endorsement from a third party. That said I do use it for every command line based program I write, it is open source and it is my hope that others may benefit from it.

Categories