Instantly share code, notes, and snippets.

Embed
What would you like to do?
https://hajekj.net Code Samples

HAJEKJ.NET

The purpose of this Gist is to contain all code samples and snippets from my personal blog and to allow for easier embedding.

async function Test1(): Promise<string> {
// Calling Test2 here to show that we can use await within async functions
let test2 = await Test2();
console.log("Test1:", test2)
return new Promise<string>(async (resolve, reject) => {
setTimeout(function () {
resolve("Test1 finished");
}, 1000);
});
}
async function Test2(): Promise<string> {
return new Promise<string>(async (resolve, reject) => {
setTimeout(function () {
resolve("Test2 finished");
}, 1000);
});
}
async function RunTest() {
console.log("async operation started...");
let test1 = await Test1();
console.log("RunTest:", test1);
console.log("async operation finished...");
}
RunTest();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator.throw(value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments)).next());
});
};
function Test1() {
return __awaiter(this, void 0, void 0, function* () {
// Calling Test2 here to show that we can use await within async functions
let test2 = yield Test2();
console.log("Test1:", test2);
return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
setTimeout(function () {
resolve("Test1 finished");
}, 1000);
}));
});
}
function Test2() {
return __awaiter(this, void 0, void 0, function* () {
return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
setTimeout(function () {
resolve("Test2 finished");
}, 1000);
}));
});
}
function RunTest() {
return __awaiter(this, void 0, void 0, function* () {
console.log("async operation started...");
let test1 = yield Test1();
console.log("Test1", test1);
console.log("async operation finished...");
});
}
RunTest();
//# sourceMappingURL=HelloWorld.js.map
import * as sqlite3 from "sqlite3";
async functin Connect(): Promise < sqlite3.Database > {
return await new sqlite3.Database("db.sqlite");
}
async function Run() {
let database = await Connect();
}
# You can write your powershell scripts inline here.
# You can also pass predefined and custom variables to this scripts using arguments
composer install
phpunit
try {
    $XslPatht = New-Object System.Xml.Xsl.XslCompiledTransform
    $XslPatht.Load("Test/phpunit2junit.xsl")
    $XslPatht.Transform("Test/Logs/junit.xml", "Test/Logs/junit-fixed.xml")
}
catch {
    Write-Host $_.Exception -ForegroundColor Red
}
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/5.2/phpunit.xsd"
backupGlobals="false"
backupStaticAttributes="false"
beStrictAboutCoversAnnotation="true"
beStrictAboutOutputDuringTests="true"
beStrictAboutTestsThatDoNotTestAnything="true"
beStrictAboutTodoAnnotatedTests="true"
forceCoversAnnotation="true"
verbose="true">
<logging>
<log type="junit" target="Test/Logs/junit.xml"/>
</logging>
<testsuite name="Sample">
<directory suffix="Test.php">Test</directory>
</testsuite>
</phpunit>
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<xsl:element name="testsuites">
<xsl:for-each select="//testsuite[@file]">
<xsl:copy-of select="." />
</xsl:for-each>
</xsl:element>
</xsl:template>
</xsl:stylesheet>
; Example Settings
curl.cainfo="%ProgramFiles(x86)%\Git\bin\curl-ca-bundle.crt"
&& ln -s /home/site/wwwroot /var/www/html \
&& ln -s /home/LogFiles /var/log/apache2
; php options
pid = /var/run/hhvm/pid
; hhvm specific
hhvm.server.port = 80
hhvm.server.type = proxygen
hhvm.server.default_document = index.php
hhvm.server.error_document404 = index.php
hhvm.repo.central.path = /var/run/hhvm/hhvm.hhbc
hhvm.server.source_root = /home/site/wwwroot
; default log location is stdout/err, which is good for docker
hhvm.log.use_log_file = true
hhvm.log.file = /home/LogFiles/hhvm.log
docker login
docker build -t "hajekj/hhvm" .
docker push hajekj/hhvm
@if "%SCM_TRACE_LEVEL%" NEQ "4" @echo off
:: ----------------------
:: KUDU Deployment Script
:: Version: 1.0.12
:: ----------------------
:: Prerequisites
:: -------------
:: Verify node.js installed
where node 2>nul >nul
IF %ERRORLEVEL% NEQ 0 (
echo Missing node.js executable, please install node.js, if already installed make sure it can be reached from current environment.
goto error
)
:: Setup
:: -----
setlocal enabledelayedexpansion
SET ARTIFACTS=%~dp0%..\artifacts
IF NOT DEFINED DEPLOYMENT_SOURCE (
SET DEPLOYMENT_SOURCE=%~dp0%.
)
IF NOT DEFINED DEPLOYMENT_TARGET (
SET DEPLOYMENT_TARGET=%ARTIFACTS%\wwwroot
)
IF NOT DEFINED NEXT_MANIFEST_PATH (
SET NEXT_MANIFEST_PATH=%ARTIFACTS%\manifest
IF NOT DEFINED PREVIOUS_MANIFEST_PATH (
SET PREVIOUS_MANIFEST_PATH=%ARTIFACTS%\manifest
)
)
IF NOT DEFINED KUDU_SYNC_CMD (
:: Install kudu sync
echo Installing Kudu Sync
call npm install kudusync -g --silent
IF !ERRORLEVEL! NEQ 0 goto error
:: Locally just running "kuduSync" would also work
SET KUDU_SYNC_CMD=%appdata%\npm\kuduSync.cmd
)
IF NOT DEFINED DEPLOYMENT_TEMP (
SET DEPLOYMENT_TEMP=%temp%\___deployTemp%random%
SET CLEAN_LOCAL_DEPLOYMENT_TEMP=true
)
IF DEFINED CLEAN_LOCAL_DEPLOYMENT_TEMP (
IF EXIST "%DEPLOYMENT_TEMP%" rd /s /q "%DEPLOYMENT_TEMP%"
mkdir "%DEPLOYMENT_TEMP%"
)
IF DEFINED MSBUILD_PATH goto MsbuildPathDefined
SET MSBUILD_PATH=%ProgramFiles(x86)%\MSBuild\14.0\Bin\MSBuild.exe
:MsbuildPathDefined
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: Deployment
:: ----------
echo Handling ASP.NET Core Web Application deployment.
:: 1. Restore nuget packages
call :ExecuteCmd dotnet restore "Radius365.sln"
IF !ERRORLEVEL! NEQ 0 goto error
:: 2. Build and publish
call :ExecuteCmd dotnet publish "src\Radius365\Radius365.csproj" --output "%DEPLOYMENT_TEMP%" --configuration Release
IF !ERRORLEVEL! NEQ 0 goto error
:: 3. KuduSync
call :ExecuteCmd "%KUDU_SYNC_CMD%" -v 50 -f "%DEPLOYMENT_TEMP%" -t "%DEPLOYMENT_TARGET%" -n "%NEXT_MANIFEST_PATH%" -p "%PREVIOUS_MANIFEST_PATH%" -i ".git;.hg;.deployment;deploy.cmd"
IF !ERRORLEVEL! NEQ 0 goto error
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
goto end
:: Execute command routine that will echo out when error
:ExecuteCmd
setlocal
set _CMD_=%*
call %_CMD_%
if "%ERRORLEVEL%" NEQ "0" echo Failed exitCode=%ERRORLEVEL%, command=%_CMD_%
exit /b %ERRORLEVEL%
:error
endlocal
echo An error has occurred during web site deployment.
call :exitSetErrorLevel
call :exitFromFunction 2>nul
:exitSetErrorLevel
exit /b 1
:exitFromFunction
()
:end
endlocal
echo Finished successfully.
[config]
command = deploy.cmd
:: 2.1 Build and publish WebJobs
echo Building and deploying Radius365.WebJob
call :ExecuteCmd dotnet publish "src\Radius365.WebJob\Radius365.WebJob.csproj" -o "%DEPLOYMENT_TEMP%\App_Data\Jobs\Continuous\Radius365.WebJob" -c Release
IF !ERRORLEVEL! NEQ 0 goto error
await HttpContext.Authentication.SignOutAsync(OpenIdConnectDefaults.AuthenticationScheme);
await HttpContext.Authentication.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
await HttpContext.Authentication.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
function TryCompleteSignout() {
var signoutComplete = true;
if (signoutComplete) {
CompleteSignout();
}
}
function CompleteSignout() {
var statusSuccess = true;
CompleteSignoutRender(statusSuccess);
}
function CompleteSignoutRender(signoutSuccessful) {
signoutSuccessful = signoutSuccessful && true;
if (!signoutSuccessful) {
RenderSignoutFailure();
} else {
RenderSignoutSuccess();
setTimeout('InitiatorRedirect()', 1000);
}
}
function RenderSignoutSuccess() {
User.UpdateLogo('', "You signed out of your account");
var signoutStatusMessage = $('#SignOutStatusMessage');
signoutStatusMessage.text("It\u0027s a good idea to close all browser windows.");
signoutStatusMessage.show();
}
function RenderSignoutFailure() {
User.UpdateLogo('', 'Hmm... we\u0027re having trouble signing you out.');
var signoutStatusMessage = $('#SignOutStatusMessage');
signoutStatusMessage.text("You may still be signed in to some applications. Close your browser to finish signing out.");
signoutStatusMessage.show();
}
function WriteSignoutFailedCookie() {
document.cookie = "SOS" + "=1; path=/";
}
function InitiatorRedirect() { }
// ...
OnRedirectToIdentityProvider = context =>
{
if (context.ShouldReauthenticate())
{
context.ProtocolMessage.MaxAge = "0"; // <time since last authentication or 0>;
}
return Task.FromResult(0);
},
// ...
internal static bool ShouldReauthenticate(this RedirectContext context)
{
context.Properties.Items.TryGetValue("reauthenticate", out string reauthenticate);
bool shouldReauthenticate = false;
if (reauthenticate != null && !bool.TryParse(reauthenticate, out shouldReauthenticate))
{
throw new InvalidOperationException($"'{reauthenticate}' is an invalid boolean value");
}
return shouldReauthenticate;
}
var state = new Dictionary<string, string> { { "reauthenticate", "true" } };
await HttpContext.Authentication.ChallengeAsync(OpenIdConnectDefaults.AuthenticationScheme, new AuthenticationProperties(state)
{
RedirectUri = "/sensitivePage"
}, ChallengeBehavior.Unauthorized);
public class RequireReauthenticationAttribute : Attribute, IAsyncResourceFilter
{
private int _timeElapsedSinceLast;
public RequireReauthenticationAttribute(int timeElapsedSinceLast)
{
_timeElapsedSinceLast = timeElapsedSinceLast;
}
public async Task OnResourceExecutionAsync(ResourceExecutingContext context, ResourceExecutionDelegate next)
{
var foundAuthTime = int.TryParse(context.HttpContext.User.FindFirst(AppClaimTypes.AuthTime)?.Value, out int authTime);
if (foundAuthTime && DateTime.UtcNow.ToUnixTimestamp() - authTime < _timeElapsedSinceLast)
{
await next();
}
else
{
var state = new Dictionary<string, string> { { "reauthenticate", "true" } };
await context.HttpContext.Authentication.ChallengeAsync(OpenIdConnectDefaults.AuthenticationScheme, new AuthenticationProperties(state)
{
RedirectUri = context.HttpContext.Request.Path
}, ChallengeBehavior.Unauthorized);
}
}
}
context.ProtocolMessage.SetParameter("amr_values", "mfa");
public class AppInsightsInitializer : ITelemetryInitializer
{
private IHttpContextAccessor _httpContextAccessor;
public AppInsightsInitializer(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor ?? throw new ArgumentNullException("httpContextAccessor");
}
public void Initialize(ITelemetry telemetry)
{
var httpContext = _httpContextAccessor.HttpContext;
if (httpContext != null && httpContext.User.Identity.IsAuthenticated == true && httpContext.User.Identity.Name != null)
{
telemetry.Context.User.AuthenticatedUserId = httpContext.User.Identity.Name;
telemetry.Context.User.AccountId = httpContext.User.FindFirst(AppClaimTypes.TenantId).Value;
}
}
}
services.AddSingleton<ITelemetryInitializer, AppInsightsInitializer>();
:: 1. Composer.phar
IF EXIST "%DEPLOYMENT_SOURCE%\composer.json" (
cd %DEPLOYMENT_SOURCE%
IF NOT EXIST "%DEPLOYMENT_SOURCE%\composer.phar" (
echo Composer.phar not found. Downloading...
call curl -s https://getcomposer.org/installer | php
IF !ERRORLEVEL! NEQ 0 goto error
) ELSE (
echo Attempting to update composer.phar
php composer.phar self-update
)
call php composer.phar install --no-dev
IF !ERRORLEVEL! NEQ 0 goto error
)
cp -R /home/site/wwwroot/* /var/www/html/ # replace /var/www/html with your local folder
#!/bin/bash
mkdir /var/www
cp -R /home/site/wwwroot/* /var/www/
exec /bin/init_container.sh # or any other command that you overwrote from the Dockerfile with your custom script
[config]
command = deploy.sh
#!/bin/bash
# ----------------------
# KUDU Deployment Script
# Version: 1.0.13
# ----------------------
# Helpers
# -------
exitWithMessageOnError () {
if [ ! $? -eq 0 ]; then
echo "An error has occurred during web site deployment."
echo $1
exit 1
fi
}
# Prerequisites
# -------------
# Verify node.js installed
hash node 2>/dev/null
exitWithMessageOnError "Missing node.js executable, please install node.js, if already installed make sure it can be reached from current environment."
# Setup
# -----
SCRIPT_DIR="${BASH_SOURCE[0]%\\*}"
SCRIPT_DIR="${SCRIPT_DIR%/*}"
ARTIFACTS=$SCRIPT_DIR/../artifacts
KUDU_SYNC_CMD=${KUDU_SYNC_CMD//\"}
if [[ ! -n "$DEPLOYMENT_SOURCE" ]]; then
DEPLOYMENT_SOURCE=$SCRIPT_DIR
fi
if [[ ! -n "$NEXT_MANIFEST_PATH" ]]; then
NEXT_MANIFEST_PATH=$ARTIFACTS/manifest
if [[ ! -n "$PREVIOUS_MANIFEST_PATH" ]]; then
PREVIOUS_MANIFEST_PATH=$NEXT_MANIFEST_PATH
fi
fi
if [[ ! -n "$DEPLOYMENT_TARGET" ]]; then
DEPLOYMENT_TARGET=$ARTIFACTS/wwwroot
else
KUDU_SERVICE=true
fi
if [[ ! -n "$KUDU_SYNC_CMD" ]]; then
# Install kudu sync
echo Installing Kudu Sync
npm install kudusync -g --silent
exitWithMessageOnError "npm failed"
if [[ ! -n "$KUDU_SERVICE" ]]; then
# In case we are running locally this is the correct location of kuduSync
KUDU_SYNC_CMD=kuduSync
else
# In case we are running on kudu service this is the correct location of kuduSync
KUDU_SYNC_CMD=$APPDATA/npm/node_modules/kuduSync/bin/kuduSync
fi
fi
if [ "x$DEPLOYMENT_TEMP" = x ]; then
DEPLOYMENT_TEMP=/tmp/`date +%s`
CLEAN_LOCAL_DEPLOYMENT_TEMP=true
fi
if [ "x$CLEAN_LOCAL_DEPLOYMENT_TEMP" = xtrue ]; then
rm -rf "$DEPLOYMENT_TEMP"
mkdir "$DEPLOYMENT_TEMP"
fi
##################################################################################################################################
# Deployment
# ----------
echo Handling ASP.NET Core Web Application deployment.
# 1. Restore nuget packages
dotnet restore "WebApplication1/WebApplication1.csproj"
exitWithMessageOnError "dotnet restore failed"
# 2. Build and publish
dotnet publish "WebApplication1/WebApplication1.csproj" --output "$DEPLOYMENT_TEMP" --configuration Release
exitWithMessageOnError "dotnet publish failed"
# 3. KuduSync
"$KUDU_SYNC_CMD" -v 50 -f "$DEPLOYMENT_TEMP" -t "$DEPLOYMENT_TARGET" -n "$NEXT_MANIFEST_PATH" -p "$PREVIOUS_MANIFEST_PATH" -i ".git;.hg;.deployment;deploy.sh"
exitWithMessageOnError "Kudu Sync failed"
##################################################################################################################################
echo "Finished successfully."
{
"failure": false,
"tenants": [
{
"id": "67266d43-8de7-494d-9ed8-3d1bd3b3a764",
"domainName": "thenetw.org",
"displayName": "TheNetw.org s.r.o.",
"isSignedInTenant": false
},
{
"id": "40c29545-8bca-4f51-8689-48e6819200d2",
"domainName": "hajekj.net",
"displayName": "hajekj",
"isSignedInTenant": true
},
{
"id": "8026f5b9-c636-4dc9-9ad1-bb30a080c651",
"domainName": "b2c.hajekj.net",
"displayName": "hajekj-b2c",
"isSignedInTenant": false
}
]
}
public async Task TenantSelect(Guid id)
{
var state = new Dictionary<string, string> { { "tenantId", id.ToString() } };
await HttpContext.Authentication.ChallengeAsync(OpenIdConnectDefaults.AuthenticationScheme, new AuthenticationProperties(state)
{
RedirectUri = Url.Action("TenantSelection", "Home")
}, ChallengeBehavior.Unauthorized);
}
OnRedirectToIdentityProvider = (context) =>
{
string tenantId;
context.Properties.Items.TryGetValue("tenantId", out tenantId);
if(tenantId != null)
{
context.ProtocolMessage.IssuerAddress = context.ProtocolMessage.IssuerAddress.Replace("common", tenantId);
}
return Task.FromResult(0);
},
OnTokenValidated = (context) =>
{
string tenantId;
context.Properties.Items.TryGetValue("tenantId", out tenantId);
if(tenantId != null)
{
string userTenantId = context.Ticket.Principal.FindFirst(AzureAdClaimTypes.TenantId)?.Value;
if (userTenantId != tenantId)
{
throw new Exception($"You signed in with wrong tenant, expected: {tenantId} but got {userTenantId}");
}
}
// You would validate whether the organization exists in the system etc.
return Task.FromResult(0);
}
INSERT INTO table (ID, Value) VALUES (1, "VALUE");
USE database;
EXEC sys.sp_wait_for_database_copy_sync @target_server = 'server_hostname', @target_database = 'database';
.AddOpenIdConnect(options =>
{
...
options.ClaimActions.Remove("auth_time");
...
});
passport.use(new OIDCStrategy({
callbackURL: process.env.returnUrl,
clientID: process.env.clientId,
clientSecret: process.env.clientSecret,
validateIssuer: true,
identityMetadata: "https://login.microsoft.com/thenetw.org/.well-known/openid-configuration",
skipUserProfile: true,
responseType: "code id_token",
responseMode: "form_post",
passReqToCallback: true,
}, function verify(req, iss, sub, profile, jwtClaims, accessToken, refreshToken, params, done) {
if (!profile.id) {
return done(new Error("No valid user auth ID"), null);
}
profile.initialRefreshToken = refreshToken;
profile.oid = jwtClaims.oid;
done(null, profile);
}));
const authContext = new AuthenticationContext("https://login.microsoftonline.com/thenetw.org", null, new MemoryCache());
// I suggest offloading this code to a separate .js script since it won't work with @ts-check or in TypeScript
const TokenRequest = require('./node_modules/adal-node/lib/token-request');
function obtainToken(user, resource, callback) {
if (user.initialRefreshToken != undefined) {
// Token has not been obtained by ADAL for Node.js, try to obtain it
authContext.acquireTokenWithRefreshToken(
user.initialRefreshToken,
clientId,
clientSecret,
resource,
function (error, result) {
if (error) {
return callback(error);
}
else {
user.initialRefreshToken = null;
var tokenRequest = new TokenRequest(authContext._callContext, authContext, clientId, resource, null);
// Always refer to user by their objectId, this is useful when creating multi-tenant applications which support switching tenants
result.userId = user.oid;
return tokenRequest._addTokenIntoCache(result, callback);
}
});
} else {
// Token has been already obtained and is in memory cache, use it to obtain access token
authContext.acquireToken(resource, user.oid, clientId, function (error, result) {
if (error) {
return callback(error);
}
else {
return callback(null, result);
}
});
}
}
az extension add -–name webapp
az webapp remote-connection create --resource-group <group_name> -n <app_name> -p <port>
ssh root@127.0.0.1 -p <port>
ssh -R <remote_port>:localhost:<local_port> root@127.0.0.1 -p <port>
xdebug.remote_host = localhost
xdebug.remote_port = <remote_port>
<Target Name="DebugEnsureNodeEnv" BeforeTargets="Build">
<Message Importance="high" Text="Restoring dependencies using 'npm'. This may take several minutes..." />
<Exec WorkingDirectory="wwwroot\" Command="npm install --no-audit" />
<Message Importance="high" Text="Done restoring dependencies using 'npm'." />
</Target>
<Target Name="DebugEnsureNodeEnv" BeforeTargets="Build" Condition=" '$(Configuration)' == 'Debug' ">
<!-- Ensure Node.js is installed -->
<Message Importance="high" Text="Checking Node.js presence..." />
<Exec Command="node --version" ContinueOnError="true">
<Output TaskParameter="ExitCode" PropertyName="ErrorCode" />
</Exec>
<Error Condition="'$(ErrorCode)' != '0'" Text="Node.js is required to build and run this project. To continue, please install Node.js from https://nodejs.org/, and then restart your command prompt or IDE." />
<Message Importance="high" Text="Restoring dependencies using 'npm'. This may take several minutes..." />
<Exec WorkingDirectory="$(wwwroot)" Command="npm install --no-audit" />
<Message Importance="high" Text="Done restoring dependencies using 'npm'." />
</Target>
<Target Name="PublishRunWebpack" AfterTargets="ComputeFilesToPublish">
<!-- As part of publishing, ensure the JS resources are freshly built in production mode -->
<Exec WorkingDirectory="$(wwwroot)" Command="npm install --no-audit" />
<!-- Include the newly-built files in the publish output -->
<ItemGroup>
<DistFiles Include="$(wwwroot)node_modules\**" />
<ResolvedFileToPublish Include="@(DistFiles->'%(FullPath)')" Exclude="@(ResolvedFileToPublish)">
<RelativePath>%(DistFiles.Identity)</RelativePath>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
</ResolvedFileToPublish>
</ItemGroup>
</Target>
{
"version": "1.0",
"defaultProvider": "cdnjs",
"defaultDestination": "wwwroot/lib",
"libraries": [
{
"library": "jquery@3.2.1",
"destination": "wwwroot/lib/jquery"
},
{
"library": "twitter-bootstrap@3.3.7",
"destination": "wwwroot/lib/bootstrap"
},
{
"library": "jquery-validate@1.17.0",
"destination": "wwwroot/lib/jquery-validate"
},
{
"library": "jquery-validation-unobtrusive@3.2.10",
"destination": "wwwroot/lib/jquery-validation-unobtrusive"
}
]
}
HttpContext.ChallengeAsync(new AuthenticationProperties(
new Dictionary<string, string>() { { "Hello,", "I am state!" } },
new Dictionary<string, object>() { { "Hello", "I am part of query!" } })
{
RedirectUri = "/success"
});
var properties = new OpenIdConnectChallengeProperties();
properties.MaxAge = TimeSpan.FromMinutes(1); // Require the session to be no older than 60 seconds.
var result = await HttpContext.AuthenticateAsync(OpenIdConnectDefaults.AuthenticationScheme);
var value = result.Properties.Items["Hello,"];
services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
.AddAzureAD(options => Configuration.Bind("AzureAd", options))
.AddCookie(options => options.Cookie.SameSite = SameSiteMode.None);
app.UseCookiePolicy(new CookiePolicyOptions
{
MinimumSameSitePolicy = SameSiteMode.None
});
.AddOpenIdConnect("AzureAD", options => {
...
// Set response type to code and response type to query
// to avoid the default response_mode=form_post
// which causes issues with WebKit's handling of samesite=lax for the session cookie
options.ResponseType = OpenIdConnectResponseType.Code;
options.ResponseMode = OpenIdConnectResponseMode.Query;
};
services.AddHttpsRedirection(options => { options.HttpsPort = 443; });
[assembly: UserSecretsId("project-name")]
.ConfigureHostConfiguration(config =>
{
config.AddCommandLine(args);
config.AddEnvironmentVariables();
config.AddUserSecrets<Program>();
})
.ConfigureWebJobs(config =>
{
config.AddAzureStorageCoreServices();
config.AddTimers();
})
.ConfigureLogging((context, config) =>
{
if (context.HostingEnvironment.IsDevelopment())
{
config.SetMinimumLevel(LogLevel.Debug);
config.AddConsole();
}
})
.ConfigureServices((context, services) =>
{
services.AddMemoryCache();
services.AddSingleton(context.Configuration);
services.AddSingleton();
services.AddScoped<Functions, Functions>();
})
class JobActivator : IJobActivator
{
private readonly IServiceProvider _service;
public JobActivator(IServiceProvider service)
{
_service = service;
}
public T CreateInstance<T>()
{
return (T)_service.GetService(typeof(T));
}
}
npm install -g ngrok
ngrok authtoken 1234567890abcdefghijklmnopqrstuvwxyz
ngrok tcp 9000
ngrok by @inconshreveable
Tunnel Status online
Version 2.1.8
Region United States (us)
Web Interface http://127.0.0.1:4040
Forwarding tcp://0.tcp.ngrok.io:18396 -> localhost:9000
Connections ttl opn rt1 rt5 p50 p90
0 0 0.00 0.00 0.00 0.00
xdebug.remote_enable = 1
xdebug.remote_handler = dbgp
xdebug.remote_port = 18396 ; This is the port we got from ngrok
xdebug.remote_host = 173.255.197.142 ; The IP address behind 0.tcp.ngrok.io
zend_extension = "D:\devtools\xdebug\2.2.5\Php_5.6\php_xdebug-2.2.5-5.6-vc11-nts.dll"
{
"version": "0.2.0",
"configurations": [
{
"name": "Listen for XDebug",
"type": "php",
"request": "launch",
"port": 9000,
"localSourceRoot": "C:/Users/hajek/Documents/Source/Temp/hajekj-xdebug/",
"serverSourceRoot": "D:/home/site/wwwroot/"
}
]
}
<?php
xdebug_break();
phpinfo();
$array = [1,2,3,4,5,6,7,8,9];
foreach($array as $item) {
echo $item;
}
xdebug.remote_autostart = 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment