how to add soap header to react-native? - c#

I use soap header in c# like this :
MeyerWebService.WebServiceEmployees tasnifWS = new MeyerWebService.WebServiceEmployees();
tasnifWS.UserDetailsValue = new UserDetails()
{
userName = "**",
password = "**"
};
But I dont know how to do this in react-native

You can use a simple module for making SOAP requests with WSSecurity
npm install react-native-soap-request --save
Example
const soapRequest = new SoapRequest({
security: {
username: 'username',
password: 'password'
},
targetNamespace: 'http://soap.acme.com/2.0/soap-access-services',
commonTypes: 'http://soap.acme.com/2.0/soap-common-types',
requestURL: soapWebserviceURL
});
const xmlRequest = soapRequest.createRequest({
'soap:ProductRegistrationRequest': {
attributes: {
'xmlns:soap': 'http://soap.acme.com/2.0/soap-access-services',
'xmlns:cmn': 'http://soap.acme.com/2.0/soap-common-types'
},
'soap:productId': {
'cmn:internalId': {
'cmn:id': productId
}
},
'soap:userId': {
'cmn:internalId': {
'cmn:id': userId
}
}
}
});
const response = await soapRequest.sendRequest();

Related

Stripe payment intents examples for server side submit

I am looking at Stripe payment gateway with Payment intent API. All examples on the official page consist of example with jquery submit with function - payWithCard (function name).
Do we have any example where we could submit on server and do some validation before sending for payment?
With Charge API, we could post data on server and then we could send for payment.
Is it possible with Payment Intent API or I need to go with Jquery ?
You can go through Stripe documentation for details. When implementing Stripe we actually use both Server Side and Javascript. I am providing here sample working code.
Download Stripe package, I am using PHP here from the Github repository.
Then in the html page use the below javascript
function handleStripe() {
var stripe = Stripe("STRIPE PUBLISHABLE KEY");
var data = {
"sess": "Some valuable data",
"rcom": "Some valuable data"
};
fetch("stripe-intent-book.php", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
})
.then(function(result) {
return result.json();
})
.then(function(data) {
var elements = stripe.elements({
fonts: [
{
cssSrc: 'https://fonts.googleapis.com/css?family=Quicksand',
},
],
locale: window.__exampleLocale,
});
var elementStyles = {
base: {
color: '#32325D',
fontWeight: 500,
fontFamily: 'Source Code Pro, Consolas, Menlo, monospace',
fontSize: '16px',
fontSmoothing: 'antialiased',
'::placeholder': {
color: '#CFD7DF',
},
':-webkit-autofill': {
color: '#e39f48',
},
},
invalid: {
color: '#E25950',
'::placeholder': {
color: '#FFCCA5',
},
},
};
var elementClasses = {
focus: 'focused',
empty: 'empty',
invalid: 'invalid',
};
var cardNumber = elements.create('cardNumber', {
style: elementStyles,
classes: elementClasses,
});
cardNumber.mount('#card-number');
var cardExpiry = elements.create('cardExpiry', {
style: elementStyles,
classes: elementClasses,
});
cardExpiry.mount('#card-expiry');
var cardCvc = elements.create('cardCvc', {
style: elementStyles,
classes: elementClasses,
});
cardCvc.mount('#card-cvc');
var inputs = document.querySelectorAll('.stripeCC .input');
Array.prototype.forEach.call(inputs, function(input) {
input.addEventListener('focus', function() {
input.classList.add('focused');
});
input.addEventListener('blur', function() {
input.classList.remove('focused');
});
input.addEventListener('keyup', function() {
if (input.value.length === 0) {
input.classList.add('empty');
} else {
input.classList.remove('empty');
}
});
});
cardNumber.on("change", function (event) {
document.querySelector("button").disabled = event.empty;
document.querySelector("#card-error").textContent = event.error ? event.error.message : "";
});
$('#submit').click(function() {
payWithCard(stripe, cardNumber, data.clientSecret);
});
});
}
And the server side PHP code below
<?php
\Stripe\Stripe::setApiKey("Stripe Secret key");
header('Content-Type: application/json');
try {
$json_str = file_get_contents('php://input');
$json_obj = json_decode($json_str);
$sess = $json_obj->sess;
$rcom = $json_obj->rcom;
$amt = 10; /* Specify the amount to be charged here */
$amt = $amt * 100;
$paymentIntent = \Stripe\PaymentIntent::create([
'amount' => $amt,
'currency' => 'gbp'
]);
$output = [
'clientSecret' => $paymentIntent->client_secret,
];
echo json_encode($output);
} catch (Error $e) {
http_response_code(500);
echo json_encode(['error' => $e->getMessage()]);
}
?>
From the Stripe API reference below is the .Net code, requesting you to go through the Stripe API doc please
// Set your secret key. Remember to switch to your live secret key in production.
// See your keys here: https://dashboard.stripe.com/apikeys
StripeConfiguration.ApiKey = "sk_test_tR3PYbcVNZZ796tH88S4VQ2u";
var options = new PaymentIntentCreateOptions
{
Amount = 1099,
Currency = "usd",
PaymentMethodTypes = new List<string> {
"card",
},
};
var service = new PaymentIntentService();
var intent = service.Create(options);

Autodesk Forge Create Activity

I am using Autodesk Forge DesignAutomatin V3 in C# and am getting an error when creating an Activity.
this is the error i receive: System.IO.InvalidDataException: 'CommandLine is a required property for Activity and cannot be null'
Here is how i am setting up the activity.
var activity = new Activity()
{
CommandLine = new List<string>() { $"$(engine.path)\\accoreconsole.exe /i $(args[InputModel].path) /al $(appbundles[{_bundleId}].path) /s $(settings[script].path)" },
Parameters = new Dictionary<string, ModelParameter>()
{
{ "HostDwg", new ModelParameter() { Verb = ModelParameter.VerbEnum.Get, LocalName = "$(HostDwg)", Required = true } },
{ "InputModel", new ModelParameter() { Verb = ModelParameter.VerbEnum.Get, LocalName = "3DBuild.dxf", Required = true, } },
{ "Result", new ModelParameter() { Verb = ModelParameter.VerbEnum.Put, Zip = true, LocalName = _outPutFileName, Required = true } }
},
Engine = _engineVersion,
Appbundles = new List<string>() { myApp },
Settings = new Dictionary<string, dynamic>()
{
{ "script", new StringSetting() { Value = string.Format("DXFIN\n\"3DBuild.dxf\"\nExplodeModel\n-view sw\nDXFOUT\n{0}\n16\n", _outPutFileName) } }
},
Description = "DXF processor",
Version = 1,
Id = _activityName
};
Please use exclusive Design Automation .NET core SDK for v3, it appears that you are referring Design Automation namespace from autodesk.forge.
When you add new SDK, make sure you remove this - using Autodesk.Forge.Model.DesignAutomation.v3; from your code.
var activity = new Activity() {
CommandLine = new List < string > () {
$ "$(engine.path)\\accoreconsole.exe /i $(args[InputModel].path) /al $(appbundles[{PackageName}].path) /s $(settings[script].path)"
}, Parameters = new Dictionary < string, Parameter > () {
{
"HostDwg",
new Parameter() {
Verb = Verb.Get, LocalName = "$(HostDwg)", Required = true
}
}, {
"InputModel",
new Parameter() {
Verb = Verb.Get, LocalName = "3DBuild.dxf", Required = true,
}
}, {
"Result",
new Parameter() {
Verb = Verb.Put, Zip = true, LocalName = outputFile, Required = true
}
}
}, Engine = TargetEngine, Appbundles = new List < string > () {
myApp
}, Settings = new Dictionary < string, ISetting > () {
{
"script",
new StringSetting() {
Value = string.Format("DXFIN\n\"3DBuild.dxf\"\nExplodeModel\n-view sw\nDXFOUT\n{0}\n16\n", outputFile)
}
}
}, Description = "DXF processor", Version = 1, Id = ActivityName
};

I have 265,467 rows and 500 columns of data .User should be able to download this data in the excel format using angular and c#

Below is my angular component code, I am calling exportAsXLSX() multiple times so that I don't get exceptions from webapi
exportAsXLSX(): void {
this.providerService.getALLDataExcel(this.skipForExcel,
this.takeForExcel).subscribe(
(response) =>
this.getSearchProviderExcelDataSucces(response),
(error) => this.getSearchProviderExcelDataFailure(error));
}
I am making 20 requests for now to test. For 250,000 records I may have to make 200 requests,
i: number = 0;
getSearchProviderExcelDataSucces(response) {
if (this.i != 20) {
this.providerExcel = this.providerExcel.concat(response)
this.skipForExcel = this.skipForExcel + 1000;
this.exportAsXLSX();
this.i = this.i + 1;
}
else {
this.excelService.exportAsExcelFile(this.providerExcel,
'test');
}
below is my service , I am trying to get 1000 records at once from web
api,
httpOptions = {
headers: new HttpHeaders({
'Access-Control-Allow-Origin':'*',
'Content-Type': 'application/json',
})
}
getALLDataExcel(skip: number, take: number): Observable<any>
{
const options = new RequestOptions({
responseType: ResponseContentType.Blob,
});
let Searchparams = new HttpParams();
Searchparams = Searchparams.append('skip', skip.toString());
Searchparams = Searchparams.append('take', take.toString());
return this.http.get<any>(this.Url +
'providers/GetSearchData/GetALLDataDataForExcel',
{
params: Searchparams,headers: this.httpOptions.headers},)
.pipe(map(this.extractData));
}
Excel service to download the data in excel format
const EXCEL_TYPE = 'application/vnd.openxmlformats-
officedocument.spreadsheetml.sheet;charset=UTF-8';
const EXCEL_EXTENSION = '.xlsx';
#Injectable({
providedIn: 'root'
})
export class ExcelService {
constructor() {}
public exportAsExcelFile(json: any[], excelFileName: string):
void
{
const worksheet: XLSX.WorkSheet =
XLSX.utils.json_to_sheet(json);
console.log('worksheet',worksheet);
const workbook: XLSX.WorkBook = { Sheets: { 'data': worksheet
},
SheetNames: ['data'] };
const excelBuffer: any = XLSX.write(workbook, { bookType:
'xlsx',
type:
'array'
});
this.saveAsExcelFile(excelBuffer, excelFileName);
}
private saveAsExcelFile(buffer: any, fileName: string): void {
const data: Blob = new Blob([buffer], {
type: EXCEL_TYPE
});
var date=new Date().toISOString().substr(0, 19).replace('T', '
').replace(/\-/g,'');
FileSaver.saveAs(data, fileName +'_'+ date.slice(0,date.indexOf('
'))
+ EXCEL_EXTENSION);
}
}

Identityserver implicit flow unauthorized_client

I cannot seem to understand why do I get unauthorized_client from identityserver. I use oidc-client with Angular 4 ui and asp.net core of web APIs. I cannot connect to identity server as every time it is returning my client is unauthorized_client.
This is the registered client:
new Client
{
ClientId = "EStudent",
ClientName = "EStudent",
AllowedGrantTypes = GrantTypes.Implicit,
RequireClientSecret = false,
AllowAccessTokensViaBrowser = true,
AllowedCorsOrigins = { "http://localhost:63150" },
LogoutSessionRequired = false,
RequireConsent = false,
AllowedScopes = new List<string>
{
IdentityServerConstants.StandardScopes.OpenId,
IdentityServerConstants.StandardScopes.Profile,
"UsersAPI",
},
AlwaysIncludeUserClaimsInIdToken = true,
RedirectUris = {
"http://localhost:63150/oauth.html"
},
PostLogoutRedirectUris = {
"http://localhost:63150/",
$"{this._baseAddress}/index.html"
},
AllowOfflineAccess = true,
}
This is the auth service in Angular:
import { Injectable, EventEmitter } from '#angular/core';
import { Http, Headers, RequestOptions, Response } from '#angular/http';
import { Observable } from 'rxjs/Rx';
import { UserManager, User } from 'oidc-client';
import { environment } from '../../../environments/environment';
const settings: any = {
authority: 'http://localhost:8200/oauth',
client_id: 'EStudent',
redirect_uri: 'http://localhost:63150/auth.html',
post_logout_redirect_uri: 'http://localhost:63150/index.html',
response_type: 'id_token token',
scope: 'openid profile UsersAPI',
silent_redirect_uri: 'http://localhost:63150/silent-renew.html',
automaticSilentRenew: true,
accessTokenExpiringNotificationTime: 4,
// silentRequestTimeout:10000,
filterProtocolClaims: true,
loadUserInfo: true
};
#Injectable()
export class AuthService {
mgr: UserManager = new UserManager(settings);
userLoadededEvent: EventEmitter<User> = new EventEmitter<User>();
currentUser: User;
loggedIn = false;
authHeaders: Headers;
constructor(private http: Http) {
this.mgr.getUser().then((user) => {
if (user) {
this.loggedIn = true;
this.currentUser = user;
this.userLoadededEvent.emit(user);
} else {
this.loggedIn = false;
}
}).catch((err) => {
this.loggedIn = false;
});
this.mgr.events.addUserLoaded((user) => {
this.currentUser = user;
this.loggedIn = !(user === undefined);
if (!environment.production) {
console.log('authService addUserLoaded', user);
}
});
this.mgr.events.addUserUnloaded((e) => {
if (!environment.production) {
console.log('user unloaded');
}
this.loggedIn = false;
});
}
}
And finally I make the call to identityserver like this:
constructor(public oidcSecurityService: AuthService) { }
ngOnInit() {
this.oidcSecurityService.mgr.signinRedirect();
}
The request which is sent looks like this:
http://localhost:8200/oauth/connect/authorize?client_id=EStudent&redirect_uri=http%3A%2F%2Flocalhost%3A63150%2Fauth.html&response_type=id_token%20token&scope=openid%20profile%20UsersAPI&state=91ea5de6886a49a997704bbdb4beda0c&nonce=295e6bf737274ea18ee2f575c93d150b
Your IdentityServer Client has a redirectUri that doesn't match that being used in the request:
http://localhost:63150/oauth.html
In the request, you use the following, which is missing the o in oauth:
http://localhost:63150/auth.html

How to create additional parameters for IdentityServer3 grant_type:password

I have IdentityServer3 spun up and working with AspNetIdentity and IdentityManager. I've created a JS client based on the samples for resource owner flow. My AspNetIdentity implementation is customized in a way as such the userstore has a foreign key to an organization table. The Organization table acts as a Tenant table because our IdentityServer and WebApi will be multi-tenant. When the user logs in, I need to pass into the request additional parameters that specify the user's tenant id. Once I get the tenant id I'll override the AuthenticateLocalAsync to look up the tenant information for the user.
I'm stuck on passing the additional tenant id or other parameters on the grant_type:password. I've tried to pass in the act_values array but I'm not sure I'm doing all this the correct way.
And any additional information on a good explanation of scopes, claims, roles, etc would be a big help because its all still fuzzy.
Here is the client on idsvr
new Client
{
ClientId = "tleweb",
ClientName = "TLE Web Client",
ClientSecrets = new List<Secret>
{
new Secret("secret".Sha256())
},
Enabled = true,
Flow = Flows.ResourceOwner,
RequireConsent = false,
AllowRememberConsent = true,
RedirectUris = new List<string>(){ "https://localhost:13048/account/signInCallback"},
PostLogoutRedirectUris = new List<string>(){ "https://localhost:13048/"},
AllowedScopes = new List<string>()
{
Constants.StandardScopes.OpenId,
Constants.StandardScopes.Profile,
Constants.StandardScopes.Email,
"read",
"write",
"tenant_id"
},
AllowedCorsOrigins = new List<string>
{
"http://localhost:13048"
},
AccessTokenType=AccessTokenType.Jwt,
AccessTokenLifetime = 3600,
AbsoluteRefreshTokenLifetime = 86400,
SlidingRefreshTokenLifetime = 43200,
RefreshTokenUsage = TokenUsage.OneTimeOnly,
RefreshTokenExpiration = TokenExpiration.Sliding
}
Here is the js client code
function getToken() {
var uid = document.getElementById("username").value;
var pwd = document.getElementById("password").value;
var xhr = new XMLHttpRequest();
xhr.onload = function (e) {
console.log(xhr.status);
console.log(xhr.response);
var response_data = JSON.parse(xhr.response);
if (xhr.status === 200 && response_data.access_token) {
token = response_data.access_token;
}
showToken(response_data);
}
xhr.open("POST", tokenUrl);
var data = {
username: uid,
password: pwd,
acr_values: ["1"],
grant_type: "password",
scope: "openid profile read write tenant_id"
};
var body = "";
for (var key in data) {
if (body.length) {
body += "&";
}
body += key + "=";
body += encodeURIComponent(data[key]);
}
xhr.setRequestHeader("Authorization", "Basic " + btoa(client_id + ":" + client_secret));
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(body);
}
Found it! Use the acr_values parameter on the request
https://identityserver.github.io/Documentation/docsv2/endpoints/authorization.html

Categories

Resources