Skip to content

Instantly share code, notes, and snippets.

@specimen151
Created October 5, 2023 16:52
Show Gist options
  • Save specimen151/ea082cdabc529197a79b530e71db8d39 to your computer and use it in GitHub Desktop.
Save specimen151/ea082cdabc529197a79b530e71db8d39 to your computer and use it in GitHub Desktop.
FalsePropertyJson files
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# Custom
dist/
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
#**/Properties/launchSettings.json
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# TODO: Comment the next line if you want to checkin your web deploy settings
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Typescript v1 declaration files
typings/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# JetBrains Rider
.idea/
*.sln.iml
# CodeRush
.cr/
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": ".NET Core Launch (web)",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
"program": "${workspaceFolder}/FalsePropertyJson/bin/Debug/net6.0/FalsePropertyJson.dll",
"args": [],
"cwd": "${workspaceFolder}/FalsePropertyJson",
"stopAtEntry": false,
"serverReadyAction": {
"action": "openExternally",
"pattern": "\\bNow listening on:\\s+(https?://\\S+)"
},
"env": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"sourceFileMap": {
"/Views": "${workspaceFolder}/Views"
}
},
{
"name": ".NET Core Attach",
"type": "coreclr",
"request": "attach"
}
]
}
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "build",
"command": "dotnet build",
"type": "shell",
"group": "build",
"presentation": {
"reveal": "silent"
},
"problemMatcher": "$msCompile"
}
]
}

empty

.NET 6.0 Empty Web Single Project Template

Browse source code, view live demo web.web-templates.io and install with dotnet-new:

$ dotnet tool install -g x

$ x new empty ProjectName

Alternatively write new project files directly into an empty repository, using the Directory Name as the ProjectName:

$ git clone https://github.com/<User>/<ProjectName>.git
$ cd <ProjectName>
$ x new empty

Update Server TypeScript DTOs

Run the dtos package.json script to update your server dtos:

$ x scripts dtos
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26730.3
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FalsePropertyJson", "FalsePropertyJson\FalsePropertyJson.csproj", "{5F817400-1A3A-48DF-98A6-E7E5A3DC762F}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{5F817400-1A3A-48DF-98A6-E7E5A3DC762F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{5F817400-1A3A-48DF-98A6-E7E5A3DC762F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{5F817400-1A3A-48DF-98A6-E7E5A3DC762F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{5F817400-1A3A-48DF-98A6-E7E5A3DC762F}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {02854F2A-8EF4-468E-80A3-CD64BBAF5D15}
EndGlobalSection
EndGlobal
{
"DetailedErrors": true,
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
using Funq;
using ServiceStack;
using FalsePropertyJson.ServiceInterface;
using ServiceStack.Text;
[assembly: HostingStartup(typeof(FalsePropertyJson.AppHost))]
namespace FalsePropertyJson;
public class AppHost : AppHostBase, IHostingStartup
{
public void Configure(IWebHostBuilder builder) => builder
.ConfigureServices(services => {
// Configure ASP.NET Core IOC Dependencies
});
public AppHost() : base("FalsePropertyJson", typeof(MyServices).Assembly) {}
public override void Configure(Container container)
{
// enable server-side rendering, see: https://sharpscript.net/docs/sharp-pages
Plugins.Add(new SharpPagesFeature {
EnableSpaFallback = true
});
SetConfig(new HostConfig
{
AddRedirectParamsToQueryString = true,
});
JsConfig.Init(new ServiceStack.Text.Config
{
DateHandler = DateHandler.ISO8601,
AlwaysUseUtc = false,
TextCase = TextCase.CamelCase,
ExcludeDefaultValues = false, // e.g. IsStartupItem=false won't be emitted unless ==true
IncludeNullValues = false
});
}
}
/* Options:
Date: 2021-01-19 21:51:24
Version: 5.105
Tip: To override a DTO option, remove "//" prefix before updating
BaseUrl: https://localhost:5001
//GlobalNamespace:
//MakePropertiesOptional: False
//AddServiceStackTypes: True
//AddResponseStatus: False
//AddImplicitVersion:
//AddDescriptionAsComments: True
//IncludeTypes:
//ExcludeTypes:
//DefaultImports:
*/
export interface IReturn<T>
{
createResponse(): T;
}
export interface IReturnVoid
{
createResponse(): void;
}
export class HelloResponse
{
public result: string;
public constructor(init?: Partial<HelloResponse>) { (Object as any).assign(this, init); }
}
// @Route("/hello")
// @Route("/hello/{Name}")
export class Hello implements IReturn<HelloResponse>
{
public name: string;
public constructor(init?: Partial<Hello>) { (Object as any).assign(this, init); }
public createResponse() { return new HelloResponse(); }
public getTypeName() { return 'Hello'; }
}
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<Using Include="FalsePropertyJson" />
<Using Include="ServiceStack" />
</ItemGroup>
<ItemGroup>
<Folder Include="wwwroot\" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="ServiceStack" Version="6.*" />
</ItemGroup>
</Project>
{
"name": "FalsePropertyJson",
"lockfileVersion": 3,
"requires": true,
"packages": {}
}
{
"scripts": {
"dtos": "x mjs"
}
}
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
app.UseHttpsRedirection();
}
app.UseServiceStack(new AppHost());
app.Run();
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "https://localhost:5001/",
"sslPort": 0
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"FalsePropertyJson": {
"commandName": "Project",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"applicationUrl": "https://localhost:5001/"
}
}
}
using System;
using ServiceStack;
using FalsePropertyJson.ServiceModel;
namespace FalsePropertyJson.ServiceInterface
{
public class MyServices : Service
{
public object Any(Hello request)
{
if(string.IsNullOrEmpty(request.Name))
return new HelloResponse { Result = $"Hello, {request.Name}!" };
return new HelloResponse { CouldBeFalse=true, Result = $"Hello, {request.Name}!" };
}
}
}
using ServiceStack;
namespace FalsePropertyJson.ServiceModel
{
[Route("/hello")]
[Route("/hello/{Name}")]
public class Hello : IReturn<HelloResponse>
{
public string? Name { get; set; }
}
public class HelloResponse
{
public string? Result { get; set; }
public bool CouldBeFalse {get;set;}
}
}
<html>
<head>
<title>False Property Json</title>
<style>
body { padding: 1em 1em 5em 1em; }
body, input[type=text] { font: 20px/28px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif }
input { padding:.25em .5em; margin-right:.5em; }
a { color:#007bff; text-decoration:none }
a:hover { text-decoration:underline }
#result { display:inline-block; color:#28a745; font-size:28px }
pre { border-radius:10px; overflow:hidden }
h2, h3, strong { font-weight:500 }
</style>
<link rel="stylesheet" href="https://unpkg.com/@highlightjs/[email protected]/styles/atom-one-dark.min.css">
<script async src="https://ga.jspm.io/npm:[email protected]/dist/es-module-shims.js"></script><!--safari polyfill-->
<script type="importmap">
{
"imports": {
"@servicestack/client": "https://unpkg.com/@servicestack/client@2/dist/servicestack-client.min.mjs"
}
}
</script>
</head>
<body>
<h2><a href="/ui/Hello">Hello</a> API</h2>
<input type="text" id="txtName">
<div id="result"></div>
<script type="module">
import { JsonApiClient, $1, on } from '@servicestack/client'
import { Hello } from '/types/mjs'
const client = JsonApiClient.create()
on('#txtName', {
/** @param {Event} el */
async keyup(el) {
const api = await client.api(new Hello({ name:el.target.value }))
$1('#result').innerHTML = api.response.result
}
})
$1('#txtName').value = 'World'
$1('#txtName').dispatchEvent(new KeyboardEvent('keyup'))
</script>
<div id="content" style="max-width:105ch"></div>
<template id="docs">
## View in API Explorer
- [Call API](/ui/Hello)
- [View API Details](/ui/Hello?tab=details)
- [Browse API source code in different langauges](/ui/Hello?tab=code)
### Using JsonServiceClient in Web Pages
Easiest way to call APIs is to use [@servicestack/client](https://docs.servicestack.net/javascript-client) with
the built-in [/types/mjs](/types/mjs) which returns your APIs in annotated typed ES6 class DTOs where it can be
referenced directly from a [JavaScript Module](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules).
We recommend using an [importmap](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script/type/importmap)
to specify where to load **@servicestack/client** from, e.g:
```html
&lt;script type="importmap"&gt;
{
"imports": {
"@servicestack/client":"https://unpkg.com/@servicestack/client@2/dist/servicestack-client.mjs"
}
}
&lt;/script&gt;
```
This lets us reference the **@servicestack/client** package name in our source code instead of its physical location:
```html
&lt;input type="text" id="txtName"&gt;
&lt;div id="result"&gt;&lt;/div&gt;
```
```html
&lt;script type="module"&gt;
import { JsonApiClient, $1, on } from '@servicestack/client'
import { Hello } from '/types/mjs'
const client = JsonApiClient.create()
on('#txtName', {
async keyup(el) {
const api = await client.api(new Hello({ name:el.target.value }))
$1('#result').innerHTML = api.response.result
}
})
&lt;/script&gt;
```
### Enable static analysis and intelli-sense
For better IDE intelli-sense during development, save the annotated Typed DTOs to disk with the [x dotnet tool](https://docs.servicestack.net/dotnet-tool):
```bash
$ x mjs
```
Then reference it instead to enable IDE static analysis when calling Typed APIs from JavaScript:
```js
import { Hello } from '/js/dtos.mjs'
client.api(new Hello({ name }))
```
To also enable static analysis for **@servicestack/client**, install the dependency-free library as a dev dependency:
```bash
$ npm install -D @servicestack/client
```
Where only its TypeScript definitions are used by the IDE during development to enable its type-checking and intelli-sense.
</template>
<script src="https://unpkg.com/@highlightjs/[email protected]/highlight.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<script>
function decode(html) {
const txt = document.createElement("textarea")
txt.innerHTML = html
return txt.value
}
document.querySelector('#content').innerHTML = marked.parse(decode(document.querySelector('#docs').innerHTML))
hljs.highlightAll()
</script>
</div>
</body>
</html>
/* Options:
Date: 2023-02-09 11:00:41
Version: 6.60
Tip: To override a DTO option, remove "//" prefix before updating
BaseUrl: https://localhost:5001
//AddServiceStackTypes: True
//AddDocAnnotations: True
//AddDescriptionAsComments: True
//IncludeTypes:
//ExcludeTypes:
//DefaultImports:
*/
"use strict";
export class HelloResponse {
/** @param {{result?:string}} [init] */
constructor(init) { Object.assign(this, init) }
/** @type {string} */
result;
}
export class Hello {
/** @param {{name?:string}} [init] */
constructor(init) { Object.assign(this, init) }
/** @type {string} */
name;
getTypeName() { return 'Hello' }
getMethod() { return 'POST' }
createResponse() { return new HelloResponse() }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment