sample power-shell script to read values from REST API - c#

I need a sample powershell script to read values/single value from a given RESTFul API. Here is the URL of sample restful URL
http://dummy.restapiexample.com/
Below is the one I tried.But instead of count I wanted to get some employees data.
<!-- begin snippet: js hide: false console: true babel: false -->
$response = Invoke-RestMethod 'http://dummy.restapiexample.com/api/v1/employees'
$employees = $response.items.Count;
Write-Host "employees=$employees";
Output:
employees= 272

$response = Invoke-RestMethod 'http://dummy.restapiexample.com/api/v1/employees'
foreach($item in $response){
Write-Host "$item"
}
this will display each record..
Invoke-RestMethod 'http://dummy.restapiexample.com/api/v1/employees'
foreach($item in $response){
Write-Host $item.employee_name
}
this will display only names.

Related

How to pass array from kendo preflight to MVC list parameter?

I have a web endpoint
public JsonResult GetCompanyPersonnelMany(string text, IEnumerable<int> includeIds)
{
I want to pass some data from a kendo multiselect. The multi select uses server side filtering; it uses a remote datasource; and it needs to process the data pre-flight.
My problem is that the text parameter will be set, but includeIds is always empty.
The pre-flight method looks like
var employeeComboDataPreFlight_loading = true;
function employeeComboDataPreFlight() {
var data = multiSelectPreFlightCommon(getMultiSelectByName('personnel'));
if (employeeComboDataPreFlight_loading) { data.includeIds = [568,572,585] || []; }
return data;
}
The multiselect is defined in the view as
#(Html.Kendo().MultiSelect()
.Name("personnel")
.Filter(FilterType.Contains)
.Placeholder("Select an option...")
.DataTextField(nameof(PersonnelEmployerViewModel.DisplayName))
.DataValueField(nameof(PersonnelEmployerViewModel.PersonnelId))
.MinLength(2)
.Value(Model.Select(x => x.PersonnelId))
.DataSource(source =>
{
source.Read(read =>
{
read.Action(nameof(PersonnelController.GetCompanyPersonnelMany),
ControllerName.Personnel
)
.Data("employeeComboDataPreFlight")
;
})
.ServerFiltering(true);
})
)
Evaluating the pre-flight method (in chrome console) shows the following:
> employeeComboDataPreFlight()
<- {text: "", includeIds: Array(3)}
includeIds: Array(3)
0: 568
1: 572
2: 585
> JSON.stringify(employeeComboDataPreFlight())
<- "{"text":"","includeIds":[568,572,585]}"
Opening the chrome network tab, it shows Query String Parameters:
text:
includeIds[]: 568
includeIds[]: 572
includeIds[]: 585
And my request URL:
Request URL: https://localhost:44363/Personnel/GetCompanyPersonnelMany?text=&includeIds%5B%5D=568&includeIds%5B%5D=572&includeIds%5B%5D=585
So it looks like there is an array of data for a variable named includeIds being sent to the server.
My problem is that the controller isn't getting the the includeIds parameter (the text parameter works correctly), the List is always empty (non-null, length: 0). How do I get the kendo multiselect to pass my javascript array into a format the controller will accept?
Well, the problem is the same as seen here or here.
As pointed out in the documentation the read transport is a wrapper to jquery ajax method, so (some of) the same configuration parameters can be passed through. The fix is to pass traditional: true to the read transport configuration. This is not possible using the MVC wrappers, so you have to define the kendo widget in javascript.
I tried setting the option after the widget was initialized like in this post but couldn't get this to work:
multiselect.dataSource.transport.options.read.traditional = true; // doesn't do anything
I also tried to use JSON.stringify instead of traditional but couldn't ever get a working request. In the end, I had to (1) change from MVC to javascript definition of the widget and (2) add traditional: true to transport options. The view now looks like
<div id="personnelWrapper" name="personnel"></div>
<script>
$("#personnelWrapper").kendoMultiSelect({
"filter": "contains",
"placeholder": "Select an option...",
"dataTextField": "#nameof(PersonnelEmployerViewModel.DisplayName)",
"dataValueField": "#nameof(PersonnelEmployerViewModel.PersonnelId)",
"minLength": 2,
"value": [#(string.Join(",", Model.Select(x => x.PersonnelId)))],
"dataSource": {
"transport": {
"read": {
"url": "#(Url.Action(nameof(PersonnelController.GetCompanyPersonnelMany),
ControllerName.Personnel) )",
"dataType": "json",
"data":employeeComboDataPreFlight,
"traditional": true, // <- this is the solution
},
"prefix":""
},
"serverFiltering":true,
"filter":[],
"schema":{
"errors":"Errors"
}
}
});
</script>

How to get Persistent menu and Get started button on messenger with Botframework v4?

Hello guys i am a beginner developer and i want the Messenger UI to have the get started button and persistent menu. I can't get anything from this doc.
I tried googling and other searches all i can see are json and curl code i don't know where to start and put them.
Can anyone guide me?
I am using C# and BotFramework V4. Thank you
Update: I got it now for future reference or others here are the codes.
for Get Started button:
$ curl -X POST -H "Content-Type: application/json" -d '{
> "setting_type":"call_to_actions",
> "thread_state":"new_thread",
> "call_to_actions":[
> {
> "payload":"Get Started"
> }
> ]
> }' "https://graph.facebook.com/v2.6/me/thread_settings?access_token=<Page access token>"
and for the Persistent Menu its the answer below.
You just need to send a HTTP POST request to this end point :
You can do this using Postman or from a command line.
You should replace <PAGE_ACCESS_TOKEN> by your Facebook page access token, so FB identifies your page to add the persistent menu.
https://graph.facebook.com/v2.6/me/messenger_profile?access_token=<PAGE_ACCESS_TOKEN>
Also, you have to attach the data for your persistent menu in the body of your HTTP request.
Finally, add 'Content-Type: application/json' as HTTP Headers.
Example :
curl -X POST -H "Content-Type: application/json" -d '{
"persistent_menu":[
{
"locale":"default",
"composer_input_disabled": true,
"call_to_actions":[
{
"title":"My Account",
"type":"nested",
"call_to_actions":[
{
"title":"Pay Bill",
"type":"postback",
"payload":"PAYBILL_PAYLOAD"
},
{
"title":"History",
"type":"postback",
"payload":"HISTORY_PAYLOAD"
},
{
"title":"Contact Info",
"type":"postback",
"payload":"CONTACT_INFO_PAYLOAD"
}
]
},
{
"type":"web_url",
"title":"Latest News",
"url":"http://www.messenger.com/",
"webview_height_ratio":"full"
}
]
},
{
"locale":"zh_CN",
"composer_input_disabled":false,
"call_to_actions":[
{
"title":"Pay Bill",
"type":"postback",
"payload":"PAYBILL_PAYLOAD"
}
]
}
]
}' "https://graph.facebook.com/v2.6/me/messenger_profile?access_token=<PAGE_ACCESS_TOKEN>"

Powershell via Ajax returning string (or nothing) in .NET MVC project

I am working on dashboard that shows live details about a set of machines.
I have the below for my Powershell
param([string] $server)
$services = Get-WmiObject win32_service -ComputerName $server | Select -Property Name, ExitCode, State, Status
$disk = get-WmiObject win32_logicaldisk -Computername $server | Select-Object -Property DeviceID, #{n="Size";e={[math]::Round($_.Size/1GB,2)}},#{n="FreeSpace";e={[math]::Round($_.FreeSpace/1GB,2)}}
$cpu = Get-WmiObject win32_processor -ComputerName $server | Measure-Object -property LoadPercentage -Average | Select Average
$server_summary = #{
services = $services
disk = $disk
cpu = $cpu
}
$json = $server_summary | ConvertTo-Json
return $json
I have the below for my c# function
public JsonResult test (string server)
{
string script = ControllerContext.HttpContext.Server.MapPath("~/Content/Powershell/Get-Server-Summary.ps1");
string cmd = script + " -server '" + server + "'";
using (var ps = PowerShell.Create())
{
ps.AddScript(cmd);
var results = ps.Invoke();
return Json(results);
}
}
In the script section of my HMTL I have
function test(server) {
$.ajax({
type: "POST",
url: '#Url.Action("test")',
dataType: "json",
data: "{'server':" + "'" + server + "'}",
contentType: "application/json; charset=utf-8",
success: function (data) {
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Error getting stats for ' + server + '.');
},
complete: function () {
}
});
}
$(document).ready(function(){
test('server_name');
});
Even though I have converted the result to JSON before returning to the results to the application, I receive and empty string.
Am I missing something? I was able to get results with a slightly different function, but it returns incorrect results.
I will post that in the comments because I have too much code to post my question...
The results on the server side look like the below.
You can see that I am getting one result, which is a string containing all the json.
It was hard to get the screenshot in time. But you can see the value is there, It is just REALLY buried... Do I really need to parse through all of this? There isn't a function for this already?
Your PowerShell script already returns a JSON string, due to use of ConvertTo-Json.
As you state, the next step, in your C# code, is to extract that string from the System.Collections.ObjectModel.Collection<System.Management.Automation.PSObject instance that PowerShell.Invoke() returns:
string json = ps.Invoke()[0].ToString();
The final step is to use that string as-is as your method's result data, via the Content() method - there is no need to deserialize the string first only to re-serialize it with the Json() method:
return Content(json, "application/json");
Note that you'll have to change your method's return type from JsonResult to ContentResult.
This approach comes courtesy of this answer.

Postman - Web service - IIS 7.5 Detailed Error - 404.0 - Not Found

Im running a C# workflow application.
I've added an aspx page UserUpdate.aspx
Also added a web api controller SynchronisePersonnelXmlFromAwsServiceController.cs
Using postman on a POST call if I enter
http://localhost/Workflow/RefreshPersonnel.aspx
I get the correct response the page is displayed in html.
However If I try to call the function TestCall() in the SynchronisePersonnelXmlFromAwsServiceController.cs page with the following call
http://localhost/Workflow/SynchronisePersonnelXmlFromAwsServiceController/TestCall
I get a 404 not found -
<legend>Error Summary</legend>
<h2>HTTP Error 404.0 - Not Found</h2>
<h3>The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.</h3>
<legend>Most likely causes:</legend>
<ul>
<li>The directory or file specified does not exist on the Web server.</li>
<li>The URL contains a typographical error.</li>
<li>A custom filter or module, such as URLScan, restricts access to the file.</li>
</ul>
</fieldset>
</div>
<div class="content-container">
<fieldset>
<legend>Things you can try:</legend>
<ul>
<li>Create the content on the Web server.</li>
<li>Review the browser URL.</li>
<li>Create a tracing rule to track failed requests for this HTTP status code and see which module is calling SetStatus. For more information about creating a tracing rule for failed requests, click
code is as follows:
namespace Workflow
{
public class SynchroniseFromAwsServiceController: ApiController
{
//// POST api/<controller>
[HttpPost]
public string TestCall()
{
string xmlFile = "Test XML Test";
string responseMsg = "Failed Import User";
if (!IsNewestVersionOfXMLFile(xmlFile))
{
responseMsg = "Not latest version of file, update not performed";
}
else
{
Business.PersonnelReplicate personnelReplicate = BusinessLogic.SynchronisePersonnel.BuildFromDataContractXml<Business.PersonnelReplicate>(xmlFile);
bool result = Service.Personnel.SynchroniseCache(personnelReplicate);
if (result)
{
responseMsg = "Success Import Sap Cache User";
}
}
return "{\"response\" : \" " + responseMsg + " \" , \"isNewActiveDirectoryUser\" : \" false \"}";
}
}
}
http://localhost/Workflow/SynchronisePersonnelXmlFromAwsService/TestCall
Please remove Controller of SynchronisePersonnelXmlFromAwsServiceController like above.
Just make sure you have installed the following feature in IIS and then try again.

Use rails controllers in C#

I have a Rails app where I can do all the CRUD in a web page, but I need to make a console application in C# to access the controllers of the rails app and use it.
Anyone can help me, here is my code for the rails app.
class UsuariosController < ApplicationController
# GET /usuarios
# GET /usuarios.json
def index
#usuarios = Usuario.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: #usuarios }
end
end
# GET /usuarios/1
# GET /usuarios/1.json
def show
#usuario = Usuario.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: #usuario }
end
end
# GET /usuarios/new
# GET /usuarios/new.json
def new
#usuario = Usuario.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: #usuario }
end
end
# GET /usuarios/1/edit
def edit
#usuario = Usuario.find(params[:id])
end
# POST /usuarios
# POST /usuarios.json
def create
#usuario = Usuario.new(params[:usuario])
respond_to do |format|
if #usuario.save
format.html { redirect_to #usuario, notice: 'El usuario fue creado con exito.' }
format.json { render json: #usuario, status: :created, location: #usuario }
else
format.html { render action: "new" }
format.json { render json: #usuario.errors, status: :unprocessable_entity }
end
end
end
# PUT /usuarios/1
# PUT /usuarios/1.json
def update
#usuario = Usuario.find(params[:id])
respond_to do |format|
if #usuario.update_attributes(params[:usuario])
format.html { redirect_to #usuario, notice: 'El usuario fue actualizado con exito.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: #usuario.errors, status: :unprocessable_entity }
end
end
end
# DELETE /usuarios/1
# DELETE /usuarios/1.json
def destroy
#usuario = Usuario.find(params[:id])
#usuario.destroy
respond_to do |format|
format.html { redirect_to usuarios_url }
format.json { head :no_content }
end
end
end
IronRuby* might help!
*"an open source implementation of the Ruby programming language for .NET and Silverlight, heavily relying on Microsoft's Dynamic Language Runtime"
If you want to make a GET request to a rails controller like UsuariosController you can do :
public static string HttpGet(string URI)
{
System.Net.WebRequest req = System.Net.WebRequest.Create(URI);
req.Proxy = new System.Net.WebProxy(ProxyString, true);
System.Net.WebResponse resp = req.GetResponse();
System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
return sr.ReadToEnd().Trim();
}
For example, if you want to access www.yourpage.com/Usuarios and get the users, that's the uri you have to call. (This will call index action, that is the default routing actionin your controllers i suppose). Or if you want to use another action.. /Usuarios/id/SomeMethodReturningSomething

Categories