I am working with TWILIO and Sharepoint 2016 to send text messages. I have created a Studio Dashboard to send the text messages and a Twilio function to send a response back to a Sharepoint list. My website is external facing with FBA accounts
All of this works if I paste the FEDAUTH code in my function. My question is how do I get the FEDAUTH code ? The pasted FEDAUTH seems to expire after awhile.
exports.handler = function(context, event, callback) {
var options = {
"method": "GET",
"hostname": "www.mysite.org",
"port": null,
"path": "/_layouts/15/Login.aspx",
"headers": {
"authorization": xxxx,
"content-type": "application/x-www-form-urlencoded",
"cache-control": "no-cache",
}
};
var req = http.request(options, function(res) {
var chunks = [];
res.on("data", function(chunk) {
chunks.push(chunk);
});
res.on("end", function() {
var body = Buffer.concat(chunks);
sendAPI();// passed FEDAUTH to /_api/contextinfo/
});
});
req.end();
};
Related
Edited
I have a problem with communication between ASP.NET web service and react-native. I try to use ajax request after reading this: Simplest SOAP example and finally get error message.
Error code bellow:
"DONE": 4, "HEADERS_RECEIVED": 2, "LOADING": 3, "OPENED": 1, "UNSENT": 0,
"_aborted": false, "_cachedResponse": undefined, "_hasError": true,
"_headers": {"content-type": "text/xml"},
"_incrementalEvents": false, "_lowerCaseResponseHeaders": {},
"_method": "POST", "_perfKey":
"network_XMLHttpRequest_http://localhost:44358/BikeWebService.asmx",
"_performanceLogger": {"_closed": false, "_extras": {},
"_pointExtras": {}, "_points": {"initializeCore_end": 11271328.84606,
"initializeCore_start": 11271264.66206}, "_timespans":
{"network_XMLHttpRequest_http://localhost:44358/BikeWebService.asmx":
[Object]}}, "_requestId": null, "_response": "Failed to connect to localhost/127.0.0.1:44358",
"_responseType": "", "_sent": true, "_subscriptions": [], "_timedOut": false,
"_trackingName": "unknown", "_url": "http://localhost:44358/BikeWebService.asmx",
"readyState": 4, "responseHeaders": undefined, "status": 0, "timeout": 0, "upload": {}, withCredentials": true
Ajax request in react native:
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('POST', 'http://localhost:44358/BikeWebService.asmx', true);
var sr ='<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">\
<s:Header>
<Action s:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">http://tempuri.org/LogIn</Action>
</s:Header>
<s:Body>\
<LogIn xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://tempuri.org/">\
<password>a</password>\
<login>1</login>\
</LogIn>\
</s:Body>\
</s:Envelope>';
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
console.log(xmlhttp.responseText);
}
}
console.log(xmlhttp);
}
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
xmlhttp.send(sr);
In ASP.NET, I have a web method like this:
[WebMethod]
public ResponseModel<User> LogIn(string password, string login)
{
return new User();
}
I tried for this answer using axios, but still getting network error. Make request to SOAP endpoint using axios
I also try add cors to web.config as shown in this answer: How to allow CORS for ASP.NET WebForms endpoint?
But it's still not working...
SSL is disabled in ASP.NET service. I try to disabled firewall and tls in windows but this is not a problem
I'm running on ASP.NET 4.8
Does anybody have any idea? Is XMl okey? I have it from WCF test client.
Starting web service on IIS and add address to hosts on windos fix this connection error.
SOAP request:
let body = '<?xml version="1.0" encoding="utf-8"?>\
<soap12:Envelope xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">\
<soap12:Body>\
<LogIn xmlns="http://tempuri.org/">\
<password>string</password>\
<login>string</login>\
</LogIn>\
</soap12:Body>\
</soap12:Envelope>';
let SOAPAction = 'http://tempuri.org/LogIn';
requestOptions = {
method: 'POST',
body: body,
headers: {
Accept: '*/*',
'SOAPAction': SOAPAction,
'Content-Type': 'text/xml; charset=utf-8'
},
};
await fetch('http://ip:port/BikeWebService.asmx', requestOptions)
.then((response) => console.log(response))
.catch((error) => {
console.log('er' + error)
});
I am trying to load a website in an I-frame. this is the first time I have to call the post method and pass a header and body.
This is my attempt with ajax.
$.ajax({
url: 'example.com',
type: 'post',
data: {
FirstName: "john doe"
},
headers: {
Token: "token"
},
dataType: 'json',
success: function (data) {
//console.info(data);
$("#output_iframe_id").attr('src', "/")
$("#output_iframe_id").contents().find('html').html(data);
}
});
I get a CORS error.
Access to XMLHttpRequest at 'https://localhost:44349/archive/statements' from origin 'https://localhost:44346' has been blocked by CORS policy: Request header field token is not allowed by Access-Control-Allow-Headers in preflight response.
Update:
I used HttpClient and was able to pass the needed header and body. the site loads in the i-frame. However, the site does not behave correctly. I loose session data on additional calls to the server.
string jsonString = GetJsonString(req);
string url = example.com;
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Token", "token");
var clientRequest = new HttpRequestMessage()
{
Method = HttpMethod.Post,
Content = new StringContent(jsonString, Encoding.UTF8, "application/json")
};
var Res = await client.PostAsync(url, clientRequest.Content);
ViewBag.Statements = await Res.Content.ReadAsStringAsync();
}
Usage:
<div>
<iframe srcdoc="#ViewBag.Statements"></iframe>
</div>
I was finally able to get the ajax call working. I ended up adding a test page within the application itself and below is the working ajax call.
$.ajax({
url: 'example.com',
type: 'post',
data: {
FirstName: "john doe"
},
headers: {
Token: "token"
},
dataType: 'html',
success: function (data) {
$("#output_iframe_id").contents().find('html').html(data);
}
});
AS for the HTTPClient call. I found a few articles stating that HTTPClient doesn't return all HTML so I ended up focusing on the ajax call.
I created an web application with submit button. When the user clicks on this button, there will be Ajax call invoked to communicate the BOT. I used following code for Ajax function
<script>
$(document).ready(function () {
$("#btnSend").click(function (e) {
$.ajax({
type: "POST",
url: "GroupChat.aspx/GetData",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("success!");
},
error: function (response) {
alert(response.d);
}
});
return false;
});
});
</script>
And I used following code to communicate BOT from the web method
[WebMethod]
public static async Task GetData()
{
Task<TokenResponse> response = GetTokenAsync();
response.Wait();
string token = response.Result.access_token;
List<BOTConstants> lstConstants = new List<BOTConstants>();
lstConstants.Add(new BOTConstants
{
text = "test message",
channelId = "webApp",
serviceUrl = "https://smba.trafficmanager.net/in/",
textFormat = "plain",
type = "message"
});
string json = (new JavaScriptSerializer()).Serialize(lstConstants);
var data = new StringContent(json, Encoding.UTF8, "application/json");
using (var client = new HttpClient())
{
//client.BaseAddress = new Uri("https://mybot.azurewebsites.net");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var result = await client.PostAsync("https://mybot.azurewebsites.net/api/messages", data).ConfigureAwait(false);
string resultContent = await result.Content.ReadAsStringAsync();
Console.WriteLine(resultContent);
}
}
But, var result = await client.PostAsync("https://mybot.azurewebsites.net/api/messages", data).ConfigureAwait(false); is always returns Bad request.
Can anybody help me on this to resolve this issue, Please correct me if any mistakes in the above code.
You should use the direct line API instead of posting directly to your "api/messages" endpoint.
Based on Microsoft documentation, below should be the steps. For the same end-user, you should cache the token and conversation id, so your conversation can continue properly in a multi-turn dialog.
Start a conversation.
POST https://directline.botframework.com/v3/directline/conversations
Authorization: Bearer SECRET
//Response
{
"conversationId": "abc123",
"token": "RCurR_XV9ZA.cwA.BKA.iaJrC8xpy8qbOF5xnR2vtCX7CZj0LdjAPGfiCpg4Fv0y8qbOF5xPGfiCpg4Fv0y8qqbOF5x8qbOF5xn",
"expires_in": 1800,
"streamUrl": "https://directline.botframework.com/v3/directline/conversations/abc123/stream?t=RCurR_XV9ZA.cwA..."
}
After you get the conversation id e.g. "abc123", you can start posting your message to this conversation.
POST https://directline.botframework.com/v3/directline/conversations/abc123/activities
Authorization: Bearer RCurR_XV9ZA.cwA.BKA.iaJrC8xpy8qbOF5xnR2vtCX7CZj0LdjAPGfiCpg4Fv0
Content-Type: application/json
[other headers]
//Request body
{
"locale": "en-EN",
"type": "message",
"from": {
"id": "user1"
},
"text": "hello"
}
I am a new to ASP.NET MVC. I want to call an API on a payment gateway. The API only tries to resolve Users Identity. I have written the CURL in C# but I seem to be stuck on how to proceed to get the API called and also return a JSON using AJAX.
Below is the Curl converted to C#.
[HttpPost]
public JsonResult ResolveBVN()
{
//string str = BVN;
var secretKey = "secretkey";
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {secretKey}");
var response = client.PostAsync("https://api.paystack.co/bvn/match", new StringContent("{ bvn: \"22146592120\",\n account_number: \"0689688306\",\n bank_code: \"044\",\n first_name: \"uthman\",\n last_name: \"jinadu\"\n }")).Result;
PaystackAPI paystackAPI = new PaystackAPI()
{
statuscode = response.IsSuccessStatusCode,
message = response.StatusCode
};
return Json(paystackAPI);
}
}
The AJAX call is below:
$("#btnGetBVN").click(function () {
if ($('#BVN').val() == '' || $('#BVN').val() == undefined) {
alert('Please Enter Customer BVN');
return false;
}
$('.spinner').css('display', 'block'); //if clicked ok spinner shown
$.ajax({
type: "POST",
url: "#Url.Action("ResolveBVN", "Transactions")",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.status);
$('#Firstname').val(response.data.first_name);
$('#Surname').val(response.data.last_name);
// $('#Phone_Number').val(response.data.mobile);
$('.spinner').css('display', 'none');
},
failure: function (response) {
alert('BVN Does Not Exist Or Error Processing Request');
$('.spinner').css('display', 'none');
},
error: function (response) {
alert('BVN Does Not Exist Or Error Processing Request');
$('.spinner').css('display', 'none');
}
});
});
The alert message response is UNDEFINED
EDIT
I have added the Class to return the JSon to the AJAX call. I can only use the statuscode of the response.
How can I access the other part of the response? The response sample is below:
{
"status": true,
"message": "BVN lookup successful",
"data": {
"bvn": "000000000000",
"is_blacklisted": false,
"account_number": true,
"first_name": true,
"last_name": true
},
"meta": {
"calls_this_month": 1,
"free_calls_left": 9
}
}
How do I access the other parts in the class like account_Number, message and the likes.
Please use below :-
var secretKey = string.Empty;
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {secretKey}");
var response = httpClient.PostAsync("https://api.paystack.co/bvn/match", new StringContent("{ bvn: \"12345678912\",\n account_number: \"0000000000\",\n bank_code: \"087\",\n first_name: \"bojack\",\n last_name: \"horseman\"\n }")).Result;
}
Please make sure to set the correct secret key.
you should be writing this code in the the method which is being called by the ajax.Response variable will contain the response returned by the paystack api
I have created a bot with MS Bot SDK. Then, I want to get the page URL where I'm hosting the bot. I just inject the script to a page to host the bot. But, does anyone who knows how to get the current page URL from C#?
I can see someone is trying to use Activity for getting the URL, but I can't find the right property from Activity.
I just inject the script to a page to host the bot. But, does anyone who knows how to get the current page URL from C#?
If you embed webchat in your web site and you want to get the URL of the web page where you embed the webchat, you can try the following approach to get the URL and pass it to your bot.
Pass the URL to bot:
<script>
var urlref = window.location.href;
BotChat.App({
directLine: { secret: "{directline_secret}" },
user: { id: 'You', pageurl: urlref},
bot: { id: '{bot_id}' },
resize: 'detect'
}, document.getElementById("bot"));
</script>
Retrieve the URL in bot application:
if (activity.From.Properties["pageurl"] != null)
{
var urlref= activity.From.Properties["pageurl"].ToString();
}
ChannelData was designed to enable sending custom information from client to bot, and back. Similar to Fei Han's answer, you can intercept outgoing messages and provide custom ChannelData for every activity sent.
<script>
var dl = new BotChat.DirectLine({
secret: 'yourdlsecret',
webSocket: false,
pollingInterval: 1000,
});
var urlref = window.location.href;
BotChat.App({
botConnection: {
...dl,
postActivity: activity => dl.postActivity({
...activity,
channelData: { pageurl: urlref }
})
},
user: { id: 'userid' },
bot: { id: 'botid' },
resize: 'detect'
}, document.getElementById("bot"));
</script>
Then, in the bot: