WinRT | C++ - HTTP Post File - The certificate authority is invalid or incorrect - c++

Basically I have two concerns, however the focus is on how to get around the certification.
I am having a hard time understanding how to make an HTTP post request in WinRT|C++. I have an ASP.Net-6-Web-Api-Project, which I have already been able to communicate with via a Python project and a C++ project (via Curl). I also tested the api via Postman. Every time doing so I had to ignore the validation of certification and it worked fine.
But now I have a WinRT/C++ project and have thrown together the following code. I want to be able to upload a file. In my case it is a point cloud in a .ply syntax as a string.
My Concerns:
In WinRT I got the expected error for invalid/untrusted certification, so I looked up what to do and ended up using IgnorableServerCertificateErrors from HttpBaseProtocolFilter, like you can see at the end of my code. But that did not fix my error. What am I missing? I still get the errors:
WinRT originate error - 0x80072F0D : 'The certificate authority is invalid or incorrect'.
WinRT originate error - 0x80190190 : 'The response status code does not indicate success: 400 ().'.
From the point of view of a developer familiar with WinRT, is the implementation correct in terms of an HTTP post request? Especially the lines
binaryContent.Headers().Append(L"Content-Type", L"image/jpeg"); andHttpContentDispositionHeaderValue disposition{ L"form-data" }; And what are the follow lines for? Is this just about assigning arbitrary names?
disposition.Name(L"fileForUpload");
disposition.FileName(L"test.ply");
Code:
void HL2ResearchMode::SendPLY(std::wstring const& pointCloud)
{
OutputDebugString(L"--- SendPLY()\n");
if (pointCloud.size() == 0)
return;
init_apartment();
auto buffer{
winrt::Windows::Security::Cryptography::CryptographicBuffer::ConvertStringToBinary(
pointCloud,
winrt::Windows::Security::Cryptography::BinaryStringEncoding::Utf8
)
};
winrt::Windows::Web::Http::HttpBufferContent binaryContent{ buffer };
// binaryContent.Headers().Append(L"Content-Type", L"text/plain;charset=utf8");
binaryContent.Headers().Append(L"Content-Type", L"image/jpeg");
winrt::Windows::Web::Http::Headers::HttpContentDispositionHeaderValue disposition{ L"form-data" };
//winrt::Windows::Web::Http::Headers::HttpContentDispositionHeaderValue disposition{ L"multipart/form-data" };
binaryContent.Headers().ContentDisposition(disposition);
disposition.Name(L"fileForUpload");
disposition.FileName(L"test.ply");
winrt::Windows::Web::Http::HttpMultipartFormDataContent postContent;
postContent.Add(binaryContent);
winrt::Windows::Web::Http::HttpResponseMessage httpResponseMessage;
std::wstring httpResponseBody;
try
{
// Send the POST request.
winrt::Windows::Foundation::Uri requestUri{ L"https://192.168.178.41:5001/api/meshes/uploadPointCloud" };
winrt::Windows::Web::Http::Filters::HttpBaseProtocolFilter myFilter;
auto fu = myFilter.IgnorableServerCertificateErrors();
fu.Append(ChainValidationResult::Expired);
fu.Append(ChainValidationResult::Untrusted);
fu.Append(ChainValidationResult::InvalidName);
fu.Append(ChainValidationResult::InvalidSignature);
fu.Append(ChainValidationResult::InvalidCertificateAuthorityPolicy);
winrt::Windows::Web::Http::HttpClient httpClient(myFilter);
httpResponseMessage = httpClient.PostAsync(requestUri, postContent).get();
httpResponseMessage.EnsureSuccessStatusCode();
httpResponseBody = httpResponseMessage.Content().ReadAsStringAsync().get();
}
catch (winrt::hresult_error const& ex)
{
httpResponseBody = ex.message();
}
std::wcout << httpResponseBody;
}

Related

in the apollo-client how I may be able to log or intercept all the operations (queries and mutations)

For analytic purposes I'd like to keep track on the client side of all the graphql operations (including ie #client ones). I was unable to find appropriate options in the API and wonder if this may be doable on the apollo-client level or may I need to introduce some proxy to intercept the calls by my own?
A custom Apollo link is a way to go.
You can use apollo-link-logger in particular to log all operations to console.
Usage (from docs):
import apolloLogger from 'apollo-link-logger';
// ...
ApolloLink.from([
apolloLogger,
// ...
]);
Note: Place apolloLogger before other links.
Output example:
As the answer from Yuriy was exactly what I was looking for I marked is as accepted answer - Thanks!
Still for the record here is the code doing a job for me - I believe someone may find it useful, also it is worth to show it's simplicity.
It's worth noting that Apollo links are chainable - thus the argument to a link function are operation: Operation and forward: NextLink which is supposed to be called from our link implementation.
let analytics: Analytics; // this is Fabric.io Analytics to be provided by DI
const analyticsLink = new ApolloLink((
operation: Operation,
forward?: NextLink
) => {
const operationType = operation.query.definitions[0].operation;
return forward(operation)
.map((result: FetchResult) => {
try {
analytics.sendCustomEvent(`${operationType}.${operation.operationName}`);
} catch (e) {
console.error('analytics error', e);
}
return result;
});
});
as a bonus we can also catch errors (i.e. to leverage fabric.io crashlytics) by using apollo-link-error (handling of errors in Apollo is a bit more complex);
const analyticsErrorLink = onError((error: ErrorResponse) => {
try {
// it's worth to rethink what we wanna log here
const message = error.graphQLErrors ? error.graphQLErrors[0].message :
(error.networkError.name + ': ' + error.networkError.message);
analytics.sendNonFatalCrash('GraphQL error: ' + message);
} catch(e) {
console.error('cannot report error to analytics', e);
}
});
Finally to compose the links we should put our intercepting implementations at the beginning so we will be able to catch all the GraphQL operations including those marked with #client which are not reaching network link - in my case full link looks like:
ApolloLink.from([
analyticsErrorLink,
analyticsLink,
stateLink,
auth,
http])

facebookclient.post() or .posttaskasync() with .net sdk returns invalid parameter when trying to post a link

I've had this working in a previous version of my application and I tried using the old code, but I think the new sdk has something different going on. I'm simply trying to post a link (that includes an image) to my wall and receiving an "Invalid Parameter" response.
Here is the relevant code (I've also tried PostTaskAsync()...same result):
var client = new FacebookClient(accessToken);
var postParams = new
{
name = "the name",
caption = "the caption",
description = "the description",
link = "http://www.example.com/",
picture = "http://www.example.com/uploadedimages/myimage.jpg"
};
client.Post("me/feed", postParams);
I've tried substituting the object with a Dictionary with the same result. I've tried substituting object with dynamic parameters = new ExpandoObject(); with the same result.
If I post the object with just { message = "this is a test message" } it posts fine so I know that I have permissions to post on my wall. Something just isn't jiving when I try to post the link with the image. I also tried urlencoding the link and the image url and received a different error indicating that the "link/picture URL is not properly formatted".
I stripped out all of the parameters thinking one of them was no longer supported, but still no dice.
Here is the exact exception being thrown:
Facebook.FacebookApiException: (FacebookApiException - #100) Invalid
parameter at Facebook.FacebookClient.ProcessResponse(HttpHelper
httpHelper, String responseString, Type resultType, Boolean
containsEtag, IList`1 batchEtags) at
Facebook.FacebookClient.Api(HttpMethod httpMethod, String path, Object
parameters, Type resultType) at Facebook.FacebookClient.Post(String
path, Object parameters)
I got this sorted out. It turns out the link and the image url have to be in the same domain as the app you're using to post.
EDIT: just to clarify. The domain has to be included in your app's config section (on Facebook) in the "App domains" section at the top.

SBL-ODU-01007 The HTTP request did not contain a valid SOAPAction header

I am hoping someone can help get me in the right direction...
I am using Powerbuilder 12 Classic and trying to consume a Oracle CRM OnDemand web service.
Using Msxml2.XMLHTTP.4.0 commands, I have been able to connect using https and retrieve the session id, which I need to send back when I invoke the method.
When I run the code below, I get the SBL-ODU-01007 The HTTP request did not contain a valid SOAPAction header error message. I am not sure what I am missing??
OleObject loo_xmlhttp
ls_get_url = "https://secure-ausomxxxx.crmondemand.com/Services/Integration?command=login"
try
loo_xmlhttp = CREATE oleobject
loo_xmlhttp.ConnectToNewObject("Msxml2.XMLHTTP.4.0")
loo_xmlhttp.open ("GET",ls_get_url, false)
loo_xmlhttp.setRequestHeader("UserName", "xxxxxxx")
loo_xmlhttp.setRequestHeader("Password", "xxxxxxx")
loo_xmlhttp.send()
cookie = loo_xmlhttp.getResponseHeader("Set-Cookie")
sesId = mid(cookie, pos(cookie,"=", 1)+1, pos(cookie,";", 1)-(pos(cookie,"=", 1)+1))
ls_post_url = "https://secure-ausomxxxx.crmondemand.com/Services/Integration/Activity;"
ls_response_text = "jsessionid=" + sesId + ";"
ls_post_url = ls_post_url + ls_response_text
loo_xmlhttp.open ("POST",ls_post_url, false)
loo_xmlhttp.setRequestHeader("COOKIE", left(cookie,pos(cookie,";",1)-1) )
loo_xmlhttp.setRequestHeader("COOKIE", left(cookie,pos(cookie,";",1)-1) )
ls_post_url2 = "document/urn:crmondemand/ws/activity/10/2004:Activity_QueryPage"
loo_xmlhttp.setRequestHeader("SOAPAction", ls_post_url2)
loo_xmlhttp.send()
ls_get_url = "https://secure-ausomxxxx.crmondemand.com/Services/Integration?command=logoff"
loo_xmlhttp.open ("POST",ls_get_url, false)
loo_xmlhttp.send()
catch (RuntimeError rte)
MessageBox("Error", "RuntimeError - " + rte.getMessage())
end try
I believe you are using incorrect URL for Login and Logoff;
Here is the sample:
https://secure-ausomxxxx.crmondemand.com/Services/Integration?command=login
https://secure-ausomxxxx.crmondemand.com/Services/Integration?command=logoff
Rest of the code looks OK to me.
I have run into similar issues in PB with msxml through ole. Adding this may help:
loo_xmlhttp.setRequestHeader("Content-Type", "text/xml")
you need to make sure that the your value for ls_post_url2 is one of the values that is found in the wsdl file. Just search for "soap:operation soapAction" in the wsdl file to see the valid values for SOAPAction.

Abort user request with Node.js/formidable

I'm using formidable to receive a file upload with node.js. I send some fields together with a file in a multipart request.
As soon as certain fields arrived, I'm able to validate the authenticity of the request for instance, and I would like to abort the whole request if this is not correct to avoid waisting resources.
I have not found a right way to abort the incoming request. I tried to use req.connection.destroy(); as follow:
form
.on('field', function(field, value) {
fields[field] = value;
if (!fields['token'] || !fields['id'] || !fields['timestamp']) {
return;
}
if (!validateToken(fields['token'], fields['id'], fields['timestamp'])) {
res.writeHead(401, {'Content-Type' : 'text/plain' });
res.end('Unauthorized');
req.connection.destroy();
}
})
However, this triggers the following error:
events.js:45
throw arguments[1]; // Unhandled 'error' event
^
Error: Cannot resume() closed Socket.
at Socket.resume (net.js:764:11)
at IncomingMessage.resume (http.js:254:15)
at IncomingForm.resume (node_modules/formidable/lib/incoming_form.js:52:11)
at node_modules/formidable/lib/incoming_form.js:181:12
at node_modules/formidable/lib/file.js:51:5
at fs.js:1048:7
at wrapper (fs.js:295:17)
I also tried req.connection.end() but the file keeps uploading.
Any thoughts? Thanks in advance!
The problem is that formidable didn't understand that you want it to stop. Try this:
req.connection.destroy();
req.connection.resume = function(){};
Of course, this is a somewhat ugly workaround, I'd open an issue on github.

ArrayOfAnyType issues when calling the method:GetRangeA1 excel web services in the silverlight 4.0

I create a simple silverlight 4.0 application used to read the excel file data in the share point 2010 server. I try to use the "Excel Web Services" but I get an error here when calling the GetRangeA1 method:
An unhandled exception of type 'System.ServiceModel.Dispatcher.NetDispatcherFaultException' occurred in mscorlib.dll
Additional information: The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter http://schemas.microsoft.com/office/excel/server/webservices:GetRangeA1Response. The InnerException message was 'Error in line 1 position 361. Element 'http://schemas.microsoft.com/office/excel/server/webservices:anyType' contains data from a type that maps to the name 'http://schemas.microsoft.com/office/excel/server/webservices:ArrayOfAnyType'. The deserializer has no knowledge of any type that maps to this name. Consider using a DataContractResolver or add the type corresponding to 'ArrayOfAnyType' to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding it to the list of known types passed to DataContractSerializer.'. Please see InnerException for more details.
the source code is like:
namespace SampleApplication
{
class Program
{
static void Main(string[] args)
{
ExcelServiceSoapClient xlservice = new ExcelServiceSoapClient();
xlservice.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
Status[] outStatus;
string targetWorkbookPath = "http://phc/Shared%20Documents/sample.xlsx";
try
{
// Call open workbook, and point to the trusted location of the workbook to open.
string sessionId = xlservice.OpenWorkbook(targetWorkbookPath, "en-US", "en-US", out outStatus);
Console.WriteLine("sessionID : {0}", sessionId);
//1. works fines.
object res = xlservice.GetCellA1(sessionId, "CER by Feature", "B1", true, out outStatus);
//2. exception
xlservice.GetRangeA1(sessionId, "CER by Feature", "H19:H21", true, out outStatus);
// Close workbook. This also closes session.
xlservice.CloseWorkbook(sessionId);
}
catch (SoapException e)
{
Console.WriteLine("SOAP Exception Message: {0}", e.Message);
}
}
}
}
I am totally new to the silverlight and sharepoint developping, I search around but didn't get any luck, just found another post here, any one could help me?
This appears to be an oustanding issue, but two workarounds I found so far:
1) Requiring a change in App.config.
http://social.technet.microsoft.com/Forums/en-US/sharepoint2010programming/thread/ab2a08d5-2e91-4dc1-bd80-6fc29b5f14eb
2) Indicating to rebuild service reference with svcutil instead of using Add Service Reference:
http://social.msdn.microsoft.com/Forums/en-GB/sharepointexcel/thread/2fd36e6b-5fa7-47a4-9d79-b11493d18107