How do you add a "general info" section to an NSwag generated API document website? - asp.net-core

Our current method uses a manually maintained and formatted YML document. At the beginning is a lengthy introduction/instruction section that I would like to include in generated documentation. The swagger docs suggest that I can add a markdown compatible, multi-line description but that's not really something I want to do in my Startup.cs file. How can I add this sort of extended introduction?
An example of the what I'm looking to do is shown on docs.discourse.org which is generated using Redoc.

I would suggest placing your API introduction to a static file that is copied to build output, then configure open api document to read it.
The file can contain HTML markup or markdown. I tend to use markdown to get heading links appear in the sidebar in redoc, it is completely up to you.
services.AddOpenApiDocument(document =>
{
document.Description = File.ReadAllText("Docs/Description.html");
// other properties
document.AddSecurity("Bearer", Enumerable.Empty<string>(), new OpenApiSecurityScheme
{
Type = OpenApiSecuritySchemeType.ApiKey,
Name = "Authorization",
In = OpenApiSecurityApiKeyLocation.Header,
Description = File.ReadAllText("Docs/Authentication.html")
});
document.OperationProcessors.Add(new AspNetCoreOperationSecurityScopeProcessor("Bearer"));
});

Related

In Docusaurus, is there can I preserve capitalization in anchors created from headings in docs?

I'm using Docusaurus to publish documentation for an open source library's API. The headings of my source markdown files correspond to the names of methods and properties for classes in the library. This all works fine.
However, the anchors that are created in the HTML are all lowercase. I want them to respect the capitalization used in the markdown file.
For example, this markdown header:
###.doSomething()
Generates the following HTML:
<h3>
<a aria-hidden="true" tabindex="-1" class="..." id="dosomething"></a>.
<code>.doSomething()</code>
<a class="..." href="#dosomething" title="...">#</a>
</h3>
As you can see, camelCase is transformed to lowercase. I would like to keep capitalization intact. Is it possible?
P.S. The markdown files are automatically generated from jsdoc comments. In jsdoc, links to a method or properties include capitalization.
TL;DR
Inside your project, navigate to the directory node_modules > github-slugger;
Open the index.js file;
Remove the line if (!maintainCase) string = string.toLowerCase()
The function will become something like this:
function slugger (string, maintainCase) {
if (typeof string !== 'string') return ''
// if (!maintainCase) string = string.toLowerCase() <-- remove this!
return string.trim()
.replace(specials, '')
.replace(emoji(), '')
.replace(whitespace, '-')
}
IMPORTANT!
If you update the docusaurus, you may need to apply this change again;
It may be necessary to edit the doc to see the changes, because of cache. Here I edited the doc file and it worked;
You must restart the docusaurus service after you make this change. And probably needs to clear the cache with npm cache clear --force;
Also, I think you should delete the folder .docusaurus to force the rebuild of all documents.
RESULT
The .md file:
---
id: intro
---
# Random title
### WriNTinG with CaSeS
test 1
### .doAnotherThink()
test 3
### .doCamelCaseWithSeveralLETTERS()
test 3
ROADMAP
I must say that this one was hard. First I tried to track down the anchor tags, then the description. Eventually I found about the github-slugger, and looked like that was the way.
But once I made the changes, nothing had happened to the document! So after hours trying, I gave up… Then, just for curiosity, I decide to see what the slug function did to the document, by adding a second header with the same name. And — luck! — it kept the original case.
It turns out that you can simply use explicit IDs to solve this issue: https://docusaurus.io/docs/next/markdown-features/headings#explicit-ids

Google Search Image "no longer available: 403" [duplicate]

I am using google image search API. Till yesterday it was working, but today morning it says "This API is no longer available"
Is it officially closed, Or any error at my side
Request
https://ajax.googleapis.com/ajax/services/search/images?v=1.0&rsz=8&q=cute+kittens
Response
{"responseData": null, "responseDetails": "This API is no longer available.", "responseStatus": 403}
The answer I found was using Google's Custom Search Engine (CSE) API. Note that this is limited to 100 free requests per day.
Creating cx and modifying it to search for images
Create custom search engine at https://cse.google.com/cse/create/new based on your search criteria.
Choose sites to search (leave this blank if you want to search the entire web, otherwise you can enter a site to search in one particular site)
Enter a name and a language for your search engine.
Click "create." You can now find cx in your browser URL.
Under "Modify your search engine," click the "Control Panel" button. In the "edit" section you will find an "Image Search" label with an ON/OFF button, change it to ON. Click "update" to save your changes.
Conducting a search with the API
The API endpoint url is https://www.googleapis.com/customsearch/v1
The following JSON parameters are used for this API:
q: specifies search text
num: specifies number of results. Requires an integer value between 1 and 10 (inclusive)
start: the "offset" for the results, which result the search should start at. Requires an integer value between 1 and 101.
imgSize: the size of the image. I used "medium"
searchType: must be set to "image"
filetype: specifies the file type for the image. I used `"jpg", but you can leave this out if file extension doesn't matter to you.
key: an API key, obtained from https://console.developers.google.com/
cx: the custom search engine ID from the previous section
Simply make a GET request by passing above parameters as JSON to the API endpoint (also listed above).
Note: If you set a list of referrers in the search engine settings, visiting the URL via your browser will likely not work. You will need to make an AJAX call (or the equivalent from another language) from a server specified in this list. It will work for only the referrers which were specified in the configuration settings.
Reference:
https://developers.google.com/custom-search/json-api/v1/reference/cse/list
Now You can search images with Custom image search API.
You can do this with two steps:
Get CUSTOM_SEARCH_ID
Go to - https://cse.google.ru/cse/all
Here you must create new Search Engine. Do this and enable Image Search at there.
Screen(i am Russian... sorry)
then get this search engine ID. To do this press at Get Code button:
And there find line with cx = "here will be your CUSTOM_SEARCH_ID":
Ok. It's done, now second step:
Get SERVER_KEY
Go to google Console - https://console.developers.google.com/project
Press to Create project button, enter the name and other required information.
Pick this project and go to Enable Apis
Now find Custom Search Engine.
And Enable it.
Now we must go to Credentials and create new Server Key:
Ok. Now we can use Image Search.
Query:
https://www.googleapis.com/customsearch/v1?key=SERVER_KEY&cx=CUSTOM_SEARCH_ID&q=flower&searchType=image&fileType=jpg&imgSize=xlarge&alt=json
Replace the SERVER_KEY and CUSTOM_SEARCH_ID and call this request.
Limit: for free you can search only 100 images per day.
If this is just for your own purposes (not for production) and you're not planning to abuse Google Image Search, you can simply extract first image URL from Google search results using JSOUP.
For example:
Code to retrieve image URL of the first thumbnail:
public static String FindImage(String question, String ua) {
String finRes = "";
try {
String googleUrl = "https://www.google.com/search?tbm=isch&q=" + question.replace(",", "");
Document doc1 = Jsoup.connect(googleUrl).userAgent(ua).timeout(10 * 1000).get();
Element media = doc1.select("[data-src]").first();
String finUrl = media.attr("abs:data-src");
finRes= "<img src=\"" + finUrl.replace("&quot", "") + "\" border=1/>";
} catch (Exception e) {
System.out.println(e);
}
return finRes;
}
Guide:
question - image search term
ua - user agent of the browser
After I read several responses I compiled a response with images:
Access the website: https://developers.google.com/custom-search/v1/introduction, on the page you will find this part, so click in the button Get a Key:
Create or select a project, and then NEXT:
Copy the API KEY:
Access the website to create your CX: https://cse.google.com/cse/create/new, write some random domain like “www.anypage.com”, (after we will delete), select a language, and define some name for your search engine. Click on the Button CREATE.
Will see this page, then click in Control Panel:
Copy the Search engine ID for later (this is your CX). After you can set to search in all websites (active Search the entire web, select on the random website www.anypage.com then click on the button Delete) and you can active Image search. So will see like this:
And Using REST you can get the results, using this example code (searching for flower):
<html lang="pt">
<head>
<title>JSON Custom Search API Example</title>
</head>
<body>
<div id="content"></div>
<script>
function hndlr(response) {
console.log(response);
for (var i = 0; i < response.items.length; i++) {
var item = response.items[i];
// in production code, item.htmlTitle should have the HTML entities escaped.
document.getElementById("content").innerHTML += "<br>" + item.htmlTitle;
}
}
</script>
<script src="https://www.googleapis.com/customsearch/v1?key=API_KEY&cx=SEARCH_ENGINE_KEY&q=flower&searchType=image&callback=hndlr"></script>
</body>
</html>
The base code is found here: https://developers.google.com/custom-search/v1/using_rest
After setting your API_KEY (key) and your SEARCH ENGINE KEY (cx), the result will see like this:
Thanks to #Vijay Shegokar, #aftamat4ik and #Alladinian
This is the full URL template to be used
We can eliminate unnecessary parameters.
https://www.googleapis.com/customsearch/v1?q={searchTerms}&num={count?}&start={startIndex?}&lr={language?}&safe={safe?}&cx={cx?}&cref={cref?}&sort={sort?}&filter={filter?}&gl={gl?}&cr={cr?}&googlehost={googleHost?}&c2coff={disableCnTwTranslation?}&hq={hq?}&hl={hl?}&siteSearch={siteSearch?}&siteSearchFilter={siteSearchFilter?}&exactTerms={exactTerms?}&excludeTerms={excludeTerms?}&linkSite={linkSite?}&orTerms={orTerms?}&relatedSite={relatedSite?}&dateRestrict={dateRestrict?}&lowRange={lowRange?}&highRange={highRange?}&searchType={searchType}&fileType={fileType?}&rights={rights?}&imgSize={imgSize?}&imgType={imgType?}&imgColorType={imgColorType?}&imgDominantColor={imgDominantColor?}&alt=json
I am using
https://www.googleapis.com/customsearch/v1?key=ap_key&cx=cx&q=hello&searchType=image&imgSize=xlarge&alt=json&num=10&start=1
Change the API url to
Google Custom Image search
Provide the same parameters along with with API KEY and CX.
More Info and Explorer
The Yahoo Boss API is a reasonable substitute, although it's not free and the results are not quite as good.
UPDATE: YAHOO BOSS JSON Search API will discontinue on March 31, 2016
SerpAPI enables to search through Google Images and returns a clean json. it integrates with most of the programming languages: python, php, java, golang, nodejs...
https://serpapi.com/images-results
Google limit the number of search per day.
but this service provides unlimited searches...
looks like we need to implement google custom search API
https://developers.google.com/custom-search/
says so on top of the page you provided yourself

sphinx remove chapter title in my pdf with latexpdf?

I generate a documentation from rst to pdf with latexpdf and sphinx.
How can I remove chapter title before every chapter?
-----------
CHAPTER ONE
-----------
As noted in the sphinx documentation you can change the latex_documents documentclass to a howto documentclass, which will get rid of the "Chaper" before your section. However, this will also change formatting slightly for the whole build.
documentclass: Normally, one of 'manual' or 'howto' (provided by Sphinx). Other document classes can be given, but they must include the “sphinx” package in order to define Sphinx’ custom LaTeX commands. “howto” documents will not get appendices. Also, howtos will have a simpler title page.
Just edit your conf.py and change manual to howto.
latex_documents = [
('index', 'foo.tex', u'foo Documentation',
u'bar', 'howto'),
]
As for the Chapter titles, from the Sphinx documentation and LaTeX customization:
Inclusion of the “fncychap” package (which makes fancy chapter
titles), default '\usepackage[Bjarne]{fncychap}' for English
documentation, '\usepackage[Sonny]{fncychap}' for internationalized
docs (because the “Bjarne” style uses numbers spelled out in English).
Other “fncychap” styles you can try include “Lenny”, “Glenn”, “Conny”
and “Rejne”. You can also set this to '' to disable fncychap.
latex_elements = {
'fncychap': '\\usepackage[Conny]{fncychap}',
# ...
}
Also, I was trying to search for how to remove the Title page, and a search brought me here, so I thought I'd add my answer here.
To remove the title page, just set the following options:
latex_elements = {
'maketitle': '', # No Title Page
# ...
}

How to grab the url or path of generated docs created in phpdocx

We have a project in which we are using phpdocx in generating word document. We would like to grab the url or path of the generated docs and send it to email. How can we grab the url? Thanks!
When you generate docs, you pass $path parameter to the method createdocx() like this:
<?php
$docx = new CreateDocx();
$docx->addText('This is just a dummy text');
$docx->createDocx($path);
?>
This generate the document at $path. So you always have the path of the generated docs

Read Velocity Tokens/Tag from .vm file

I have an application where in I am trying to create a velocity template repository which will help me centralise all my email templates and will allow me to create a communication hub. All templates will be called at runtime and populates with data via services.
My problem is that I need to provide users with optional and compulsory params list when they define the template inputs for the velocity template.
Is there a way to read the tokens/tags from the velocity template file and extract them??
Like I want a list of tokens $name.address.streetName to be available to me from .vm file.
I do not want to go for Regex .
I do not have to cache or reuse them , its just going to be a one time read and store the default,compulsory & optional params in the database.
I am following these patterns : http://kickjava.com/src/org/apache/velocity/test/view/TemplateNodeView.java.htm
How to use String as Velocity Template?
Please advice.
I got it working like this
RuntimeServices runtimeServices = RuntimeSingleton.getRuntimeServices();
StringReader reader = new StringReader(String velocityTemplateBodu);
SimpleNode node = runtimeServices.parse(reader, "dummyOne.vm");
for(int i=0; i<node.jjtGetNumChildren();i++){
if(node.jjtGetChild(i) instanceof org.apache.velocity.runtime.parser.node.ASTReference ){
System.out.println("Node -----------------"+i +"---"+node.jjtGetChild(i).literal());
}
}
Using SimpleNode class you get all the nodes on the .vm file.
The Nodes are read using javaCC as ASTReference and ASTText (both extend SimpleNode). To get the tokens you need to get the ASTReference and to get HTML text use the ASTText.