Is there a windows command to list the process IDs and Names of application holding a specific URL registration?
I am after the applications that has made registrations under the following URL namespace.
http://localhost:55987/
I am aware that URL Reservations can be listed using
netsh http show urlacl
The reservation states that
Reserved URL : http://localhost:55987/
User: \Everyone
Listen: Yes
Delegate: No
SDDL: D:(A;;GX;;;WD)
But how do I find the registrations made under the reserved URL namespace?
You can find the processId for the registered urls using the following command:
netsh http show servicestate view=requestq verbose=no
It's going to return a table like the following:
Request queue name: Request queue is unnamed.
Version: 2.0
State: Active
Request queue 503 verbosity level: Basic
Max requests: 1000
Number of active processes attached: 1
Process IDs:
3604
URL groups:
URL group ID: F100000040000003
State: Active
Request queue name: Request queue is unnamed.
Number of registered URLs: 1
Registered URLs:
HTTP://+:8022/
Server session ID: F200000020000007
Version: 2.0
State: Active
Request queue name: Request queue is unnamed.
Version: 2.0
State: Active
Request queue 503 verbosity level: Basic
Max requests: 1000
Number of active processes attached: 1
Process IDs:
3604
URL groups:
URL group ID: D400000040001E9C
State: Active
Request queue name: Request queue is unnamed.
Number of registered URLs: 1
Registered URLs:
HTTP://+:3799/API
Server session ID: D6000000200013C1
Version: 2.0
State: Active
I`ve also made a powershell function who parses this output to return an object list.
Result sample:
ProcessId ControllerProcessId RegisteredUrl
--------- ------------------- -------------
1860 HTTP://+:8022/
1020 HTTPS://+:5986/WSMAN/
function Parse-HttpSysReqQueue() {
[string[]]$rawHttpSysQueue = netsh http show servicestate view=requestq verbose=no
$urls = #()
$output = #()
$recordIsOpen = $false
$index = 0
$rawHttpSysQueue | ForEach-Object {
$line = $_
# Whether is the begining of a new request queue record.
$newRecordToken = "Request queue name"
if ($line.StartsWith($newRecordToken)) {
$recordIsOpen = $true
$index++; return
}
# We are iterating through a request-queue record.
if ($recordIsOpen) {
# Obtain Process ID
if ($line.Contains("Process IDs:")) {
$rawPid = $rawHttpSysQueue[$index+1]
if($rawPid.Trim() -match '^\d+$'){
$processId = $rawPid.Trim()
} else {
$processId = $null
}
$index++; return
}
# Obtain Controller Process ID (generally IIS)
if ($line.Contains("Controller process ID:")) {
$controllerProcessId = $line.Split(":")[1].Trim()
$index++; return
}
# Read all registered urls from current record.
if ($line.Contains("Registered URLs:")) {
$urlLineIndex = $index+1
while ($rawHttpSysQueue[$urlLineIndex].Trim().StartsWith("HTTP://") -or $rawHttpSysQueue[$urlLineIndex].Trim().StartsWith("HTTPS://")) {
$urls += $rawHttpSysQueue[$urlLineIndex].Trim()
$urlLineIndex++
}
# Add record to output list.
$urls | ForEach-Object {
$output += New-Object PSObject -Property #{
ProcessId = $processId
RegisteredUrl = $_
ControllerProcessId = $controllerProcessId
}
}
# Already read all the urls from this request-queue, consider the record closed.
$processId = $null
$controllerProcessId = $null
$urls = #()
$recordIsOpen = $false
}
}
$index++
}
return $output
}
Related
Is there a way to notify system`s users on real-time that the system is in deployment process(publish to production)?The purpose is to prevent them from starting to do atomic operations?
the system is an ASP.NET-based system and it already has SignalR Dlls, but I do not exactly know how to get to the "source" in the application from which I know that the system is deploying right now.
This is highly dependent on your deployment process, but I achieved something similar in the following way:
I created a method in one of my controllers called AnnounceUpdate:
[HttpPost("announce-update")]
public async Task<IActionResult> AnnounceUpdate([FromQuery] int secondsUntilUpdate, string updateToken)
{
await _tenantService.AnnounceUpdate(secondsUntilUpdate, updateToken);
return Ok();
}
The controller method takes in the amount of seconds till the update, as well as a secret token to ensure not just anyone can call this endpoint.
The idea is that we will call this controller just before we deploy, to announce the pending deployment. I make my deployments using Azure Dev Ops, and so I was able to create a release task that automatically runs the following PowerShell code to call my endpoint:
$domain = $env:LOCALURL;
$updateToken = $env:UPDATETOKEN;
$minutesTillUpdate = 5;
$secondsUntilUpdate = $minutesTillUpdate * 60;
$len = $secondsUntilUpdate / 10;
#notify users every 10 seconds about update
for($num =1; $num -le $len; $num++)
{
$url = "$domain/api/v1/Tenant/announce-update?secondsUntilUpdate=$secondsUntilUpdate&updateToken=$updateToken";
$r = Invoke-WebRequest $url -Method Post -UseBasicParsing;
$minsLeft = [math]::Floor($secondsUntilUpdate/60);
$secsLeft = $secondsUntilUpdate - $minsLeft * 60;
$timeLeft;
if($minsLeft -eq 0){
$timeLeft = "$secsLeft seconds";
}else{
if($secsLeft -eq 0){
$timeLeft = "$minsLeft minute(s)";
}else{
$timeLeft = "$minsLeft minute(s) $secsLeft seconds";
}
};
$code = $r.StatusCode;
Write-Output "";
Write-Output "Notified users $num/$len times.";
Write-Output "Response: $code.";
Write-Output "$timeLeft remaining."
Write-Output "_________________________________"
Start-Sleep -Seconds 10;
$secondsUntilUpdate = $secondsUntilUpdate - 10;
}
Write-Output "Allowing users to log out.";
Write-Output "";
Start-Sleep -Seconds 1;
Write-Output "Users notfied! Proceeding with update.";
As you can see, on the script I have set that the time till the update is 5 minutes. I then call my AnnounceUpdate endpoint every 10 seconds for the duration of the 5 minutes. I have done this because if I announce an update that will occur in 5 minutes, and then 2 minutes later someone connects, they will not see the update message. On the client side I set a variable called updatePending to true when the client receives the update notification, so that they do not keep on getting a message every 10 seconds. Only clients that have not yet seen the update message will get it.
In the tenant service I then have this code:
public async Task AnnounceUpdate(int secondsUntilUpdate, string updateToken)
{
if (updateToken != _apiSettings.UpdateToken) throw new ApiException("Invalid update token");
await _realTimeHubWrapper.AnnouncePendingUpdate(secondsUntilUpdate);
}
I simply check if the token is valid and then conitnue to call my HUB Wrapper.
The hub wrapper is an implementation of signalR's hub context, which allows to invoke signalR methods from within our code. More info can be read here
In the HUB wrapper, I have the following method:
public Task AnnouncePendingUpdate(int secondsUntilUpdate) =>
_hubContext.Clients.All.SendAsync("UpdatePending", secondsUntilUpdate);
On the client side I have set up this handler:
// When an update is on the way, clients will be notified every 10 seconds.
private listenForUpdateAnnouncements() {
this.hubConnection.on(
'PendingUpdate', (secondsUntilUpdate: number) => {
if (!this.updatePending) {
const updateTime = currentTimeString(true, secondsUntilUpdate);
const msToUpdate = secondsUntilUpdate * 1000;
const message =
secondsUntilUpdate < 60
? `The LMS will update in ${secondsUntilUpdate} seconds.
\n\nPlease save your work and close this page to avoid any loss of data.`
: `The LMS is ready for an update.
\n\nThe update will start at ${updateTime}.
\n\nPlease save your work and close this page to avoid any loss of data.`;
this.toastService.showWarning(message, msToUpdate);
this.updatePending = true;
setTimeout(() => {
this.authService.logout(true, null, true);
this.stopConnection();
}, msToUpdate);
}
}
);
}
I show a toast message to the client, notifying them of the update. I then set a timeout (using the value of secondsUntilUpdate) which will log the user out and stop the connection. This was specifically for my use case. You can do whatever you want at this point
To sum it up, the logical flow is:
PowerShell Script -> Controller -> Service -> Hub Wrapper -> Client
The main take away is that somehow we need to still trigger the call to the endpoint to announce the update. I am lucky enough to be able to have it run automatically during my release process. If you are manually publishing and copying the published code, perhaps you can just run the PowerShell script manually, and then deploy when it's done?
I am trying to upload JSON data + file (binary) to FastAPI 'POST' endpoint using requests.
This is the server code:
#app.post("/files/")
async def create_file(
file: bytes = File(...), fileb: UploadFile = File(...), timestamp: str = Form(...)
):
return {
"file_size": len(file),
"timestamp": timestamp,
"fileb_content_type": fileb.content_type,
}
This is the client code:
session = requests.Session()
adapter = requests.adapters.HTTPAdapter(max_retries=0)
session.mount('http://', adapter)
jpg_image = open(IMG_PATH, 'rb').read()
timestamp_str = datetime.datetime.now().isoformat()
files = {
'timestamp': (None, timestamp_str),
'file': ('image.jpg', jpg_image),
}
request = requests.Request('POST',
FILE_UPLOAD_ENDPOINT,
files=files)
prepared_request = request.prepare()
response = session.send(prepared_request)
The server fails with
"POST /files/ HTTP/1.1" 422 Unprocessable Entity
FastAPI endpoints usually respond 422 when the request body is missing a required field, or there are non-expected fields, etc.
It seems that you are missing the fileb from your request body.
If this field is optional, you must declare it as follows in the endpoint definition:
fileb: Optional[UploadFile] = File(None)
You will also need to make some checks inside your endpoint code...
If it is a required field then you need to add it to your request body.
When running the following program in elm-reactor (or using elm-make for that matter), the only webpage I have found that it actually GETs is httpbin. Otherwise, I see a Http.NetworkError, even on reliable sites such as "http://google.com" or "http://stackoverflow.com". I am utterly befuddled as to why this might be, can anyone point out my error?
module Main (..) where
import Http
import Html exposing (..)
import Effects
import Html.Events as Events
import StartApp
import Task
-- MODEL
type alias Model =
{ output : String }
type Action
= Response String
| Request String
| HTTPError Http.Error
-- UPDATE
update : Action -> Model -> ( Model, Effects.Effects Action )
update act mod =
case act of
Response str ->
( { mod | output = str }, Effects.none )
Request srv ->
let
effects =
srv
|> Http.getString
|> Task.map Response
|> flip Task.onError (Task.succeed << HTTPError)
|> Effects.task
in
( { mod | output = "GET: " ++ srv }, effects )
HTTPError err ->
( { mod
| output =
"Error: "
++ case err of
Http.Timeout ->
"Timeout"
Http.UnexpectedPayload str ->
"Unexpected payload: " ++ str
Http.BadResponse code str ->
"Bad response: " ++ toString code ++ ": " ++ str
Http.NetworkError ->
"Network error"
}
, Effects.none
)
-- VIEW
view : Signal.Address Action -> Model -> Html.Html
view address mod =
div
[]
[ div
[]
[ input
[ Events.on "input" Events.targetValue (Request >> Signal.message address) ]
[]
]
, div [] [ text mod.output ]
]
-- MAIN
app : StartApp.App Model
app =
StartApp.start
{ init = ( { output = "No requests made" }, Effects.none )
, update = update
, view = view
, inputs = []
}
main =
app.html
port tasks : Signal (Task.Task Effects.Never ())
port tasks =
app.tasks
You are most likely running into cross-origin browser restrictions. Take a look at your browser javascript console as you make requests that fail. Chrome logs an error like this:
XMLHttpRequest cannot load https://www.stackoverflow.com/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://elm-lang.org' is therefore not allowed access.
Your working httpbin example link includes the HTTP header Access-Control-Allow-Origin: *, which is the least restrictive setting.
You can read up more on these types of issues, and the way to get around them, by looking up information on CORS (which stands for Cross Origin Http Request).
Xively provisioning - how does an app request a device feed ID and key?
On the "Provisioning" page it says:
"8 An application prompts the user for the serial number of the device they have just activated, the application uses a Master Key and the device serial number to request the device Feed ID and key from Xively."
This seems to suggest there's an API to do this, but I can't find it!
Does anyone know where this is in the docs or how to do this?
To get a feed ID for the device one need to make a Read Device request.
Go to Account | Settings | Add a master key
with Read/Update all permissions.
2) Note down the master key. Now to read all the devices (instances) created for a product (template) use API and key from (1)
URL: https://api.xively.com/v2/products/product_id/devices
X-ApiKey: The key you created in (1)
This API will return all devices with feedId and device keys.
A working example with Curl
include ('sensorui.inc');
include(APP_CLASS_LOADER);
// script to list all devices for a product
$url = "https://api.xively.com/v2/products/XwYNEGj4epo7HXNM0DGK/devices" ;
// API KEY
// This is master key API (from Account | settings page)
// for some reason (bug?) READ only key does not work!
$xheaders = array("X-ApiKey" => "your_master_key");
$cookies = array();
$curl = new \com\yuktix\util\curl\Wrapper($url,$cookies,$xheaders) ;
$curl->setCookies($cookies);
$curl->setXHeaders($xheaders);
// $curl->setDebug();
$response = $curl->doGet();
print_r($response);
$code = ($response["code"] != 200) ? 1 : 0 ;
return $code ;
Returns
rjha#kubuntu13:~/code/bitbucket/sensorui/scripts/xively$ php list-product.php
Array
(
[code] => 200
[response] => {"totalResults":2,"itemsPerPage":30,"startIndex":1,"devices":[{"serial":"SVSN001","activation_code":"xxx","created_at":"2014-02-02T15:05:37Z","activated_at":"2014-02-02T15:12:41Z","feed_id":xxx,"api_key":"xxx"},{"serial":"SVSN002","activation_code":"xxxx","created_at":"2014-02-02T15:05:37Z","activated_at":null,"feed_id":xxxx}]}
All I want is to do a POST like this:
You can post a score or a user by issuing an HTTP POST request to /USER_ID/scores with the app access_token as long as you have the publish_actions permission.
Name Description Type Required
score numeric score with value > 0. integer yes
I am doing this:
try {
http.request( POST, URLENC ) {
uri.path = "/100000781309474/scores?" + user.accessToken
body = [score:10]
response.success = { resp ->
println "Tweet response status: ${resp.statusLine}"
assert resp.statusLine.statusCode == 200
}
response.failure = { resp ->
println "Unexpected error: ${resp.status} : ${resp.statusLine.reasonPhrase}"
}
}
} catch ( HttpResponseException ex ) {
// default failure handler throws an exception:
println "Unexpected response error: ${ex.statusCode}"
}
but it's returning this exception:
400: Bad request
It means that the POST isn't correct, yes?
Can someone tell me how to do the post with the user score?
Referring to https://developers.facebook.com/docs/score/
I first see you're passing in the user token
uri.path = "/100000781309474/scores?" + user.accessToken
It should be the app access token. The format is http://graph.facebook.com/{userId}/scores?access_token={AppAccessToken} with parameter name of score and value of {theirScore}. Be sure that access_token is an app access token. Also be sure your app is registered as an game app.