DELETE request give 204 response code from Insomnia/Postman, But from the frontend it gives error for Delete request.
Please find my Service code below :
public bool Dissociate(string envCode, string serialNumber, string gatewayType)
{
envCode.ThrowIfNull();
serialNumber.ThrowIfNull();
gatewayType.ThrowIfNull();
if (!IsAssociated(envCode, serialNumber, gatewayType))
{
_logService.Warn($"DspService - Dissociate - {gatewayType} {serialNumber} not associated to DSP tenant on environment {envCode}");
return false;
}
EnvironmentSettings dspEnvSettings = GetEnvironmentSettings(envCode);
string baseUri = DspHelper.GetBaseUriByAction(dspEnvSettings, DspActionType.Dissociate);
string dspDeviceId = DspHelper.BuildDeviceId(serialNumber, gatewayType, true);
string uri = $"{baseUri}/registry/devices/{dspDeviceId}/claim";
var body = new
{
Claimable = true
};
try
{
var authToken = GetAuthorizationHeader(dspEnvSettings, DspActionType.Dissociate);
RunDspCommand<bool>(dspEnvSettings, uri, authToken, body, HttpMethod.Put, DspActionType.Dissociate);
return true;
}
catch (Exception e)
{
_logService.ErrorException(e, $"DspService - Dissociate - Error dissociating {gatewayType} {serialNumber} on environment {envCode}. {uri}");
throw;
}
}
Please find my insomnia response:
CONTROLLER :
[AcceptVerbs("DELETE")]
[Route("dissociate")]
public bool Dissociate([FromUri] string gatewayType, [FromUri] string gatewaySerial)
{
if (string.IsNullOrEmpty(gatewaySerial) || string.IsNullOrEmpty(gatewayType))
{
this.BadRequestResponse();
}
var connectedUser = this.permissionService.GetConnectedUser();
this.permissionService.CheckRolePermission(connectedUser.Role, PermissionConstant.DissociateComX);
bool hasSucceeded = this.dspService.Dissociate(connectedUser.CurrentEnvironment, gatewaySerial, gatewayType);
if (hasSucceeded)
{
this.applicationDataAccess.LogAction(connectedUser.CurrentEnvironment, connectedUser.Email, LogActionConstants.Action.DissociateComX, string.Format(LogActionConstants.Message.DissociateComX, gatewayType, gatewaySerial));
}
else
{
this.BadRequestResponse("cannot deprovioned comx");
}
return hasSucceeded;
}
It gives the exception in the Service Code
RunDspCommand<bool>(dspEnvSettings, uri, authToken, body, HttpMethod.Put, DspActionType.Dissociate);
Below is my front end code.
controller.ts
dissociateGateway() {
if (!this.isDspGateway || this.isLoadingDspState || this.isDissociating
|| this.gateway.FirmwareUpgradeWorkflow || this.gateway.DeleteGatewayWorkflow
|| !this.isAssociated()) {
return;
}
this.modalService.confirm(
`The ${this.gateway.Type} ${this.gateway.SerialNumber} will be dissociated from its DSP tenant ${this
.dspGatewayState.Tenant}.`,
'Are you sure you want to dissociate the gateway from DSP tenant?')
.then(() => {
this.isDissociating = true;
this.dspService.dissociate(this.gateway.Type, this.getDeviceId())
.then(() => this.getDspGatewayState())
.catch((e) => {
if (e) {
this.modalService.error('Error dissociating the gateway. Please retry later');
}
})
.finally(() => this.isDissociating = false);
});
}
service.ts
dissociate(gatewayType: string, gatewaySerial: string): ng.IPromise<boolean> {
var uri = this.ROUTES.dissociate
.replace('{:gatewayType}', gatewayType.toString())
.replace('{:gatewaySerial}', gatewaySerial);
return this.restService
.delete(uri, null)
.then((response: any) => {
return response;
})
.catch((response: any) => {
return this.$q.reject(response);
});
}
Path :
dissociate: '/dsp/dissociate?gatewaytype={:gatewayType}&gatewaySerial={:gatewaySerial}',
If you need more information please comment below.
Please help me. Thanks in Advance.
Related
I am using Firebase API for Unity and I am pushing some data to the realtime database using the Post request
Right after using that Post request I need the created ID for the new node to do something else but I am not sure how to retrieve that ID.
Firebase.Instance.Post(uri, new Dictionary<string, string>() { { "name", name } },
delegate { Debug.Log("Name has been added successfully!"); //here is where i need the new ID to do something else },
delegate { Debug.Log("Something Wrong! .. Please try again later"); });
The post function:
public void Post<T, K>(URI uri, T body, System.Action<K> onSuccess, System.Action<string> onFail)
{
RequestHelper currentRequest = new RequestHelper
{
Uri = uri.Path,
BodyString = JsonConvert.SerializeObject(body),
IgnoreHttpException = true
};
Debug.Log("BODY_post: " + currentRequest.BodyString);
RestClient.Post(currentRequest, (exception, res) => ResolveResponse(exception, res, onSuccess, onFail));
}
void ResolveResponse<T>(RequestException exception, ResponseHelper res, System.Action<T> onSuccess, System.Action<string> onFail)
{
string returnedText = res.Text;
AuthError authError = null;
try
{
authError = JsonConvert.DeserializeObject<AuthError>(returnedText);
}
catch (System.Exception ex)
{
Debug.Log(ex);
}
finally
{
if (authError != null && authError.error != null && authError.error.message != null)
{
onFail(BeautifyMessage(authError.error.message));
}
else if (exception != null && (exception.IsHttpError || exception.IsNetworkError))
{
onFail(BeautifyMessage(exception.Message));
}
else if (typeof(T) == typeof(string))
{
onSuccess((T)(object)returnedText);
}
else
{
onSuccess(JsonConvert.DeserializeObject<T>(returnedText));
}
}
}
And it calls to the rest api's library post function.
You are wrapping the Firebase REST API, where calling POST returns the key in the response:
A successful request is indicated by a 200 OK HTTP status code. The response contains the child name of the new data specified in the POST request.
{ "name": "-INOQPH-aV_psbk3ZXEX" }
So your response handler will need to parse that result, and return the "-IN...." key back to the caller.
I'm getting an error saying AuthDataResult does not contain ProfileChangeRequest() when i try to change the name of the user. I've to research online and read the firebase docs as well but no luck.
public static async Task Register(UIViewController thisView,
string inpName,
string inpEmail,
string inpPassword)
{
bool done = false;
AppDataClass.auth.CreateUser(inpEmail, inpPassword, (user, error) =>
{
if (error != null)
{
AlertShow.Alert(thisView, "Error",
"This went wrong: " + error.UserInfo.Description);
return;
}
UserProfileChangeRequest changeReq = user.ProfileChangeRequest;
changeReq.DisplayName = inpName;
changeReq.CommitChanges((profileError) =>
{
if (profileError != null)
{
AlertShow.Alert(thisView, "Error",
"Profile Error: " + profileError);
return;
}
done = true;
});
});
while (!done)
{
await Task.Delay(50);
}
}
If you read the document about method -signInWithEmail:password:completion:, the call back it retures is a FIRAuthDataResultCallback , the first parameter here is FIRAuthDataResult.
So the user should be:
user.user.ProfileChangeRequest
To make it clear:
public static async Task Register(UIViewController thisView,
string inpName,
string inpEmail,
string inpPassword)
{
bool done = false;
AppDataClass.auth.CreateUser(inpEmail, inpPassword, (authDataResult, error) =>
{
if (error != null)
{
AlertShow.Alert(thisView, "Error",
"This went wrong: " + error.UserInfo.Description);
return;
}
UserProfileChangeRequest changeReq = authDataResult.user.ProfileChangeRequest;
changeReq.DisplayName = inpName;
});
while (!done)
{
await Task.Delay(50);
}
}
Refer: ERROR is value of type 'AuthDataResult' has no member 'uid'
ScreenCast Video Screen Capture: https://www.screencast.com/t/iwbNw1qwzGa
When you see the screen capture. It will show the first part where I demonstrate the calling of API using the Angular UI and the second part is where I use Swagger UI to call the API. You can see there that the first part displays calls the API and returns 0 records on the response when executing the GetAll() function of the default method of the ASP.Net Zero. But in the second part where it executes the API via swagger it returns the expected value from the DB. Please help on this issue. Thanks in advance.
See details of my code:
Component
ngOnInit(): void {
this.loadGroupHeaderCombo();
}
loadGroupHeaderCombo()
{
this._groupHeadersService.getAllGroupHeaderCombo()
.pipe(finalize(() => this.primengTableHelper.hideLoadingIndicator()))
.subscribe(result =>{
this.groupHeaderNamesSelectItems = _.map(result.groupHeaderNames, function(groupHeader) {
return {
label: groupHeader.displayText, value: groupHeader.value
};
});
return result;
});
}
Service-proxies
getAllGroupHeaderCombo(): Observable<GetGroupHeaderOutput> {
let url_ = this.baseUrl + "/api/services/app/GroupHeaders/GetAllGroupHeaderCombo";
url_ = url_.replace(/[?&]$/, "");
let options_ : any = {
observe: "response",
responseType: "blob",
headers: new HttpHeaders({
"Accept": "application/json"
})
};
return this.http.request("get", url_, options_).pipe(_observableMergeMap((response_ : any) => {
return this.processGetAllGroupHeaderCombo(response_);
})).pipe(_observableCatch((response_: any) => {
if (response_ instanceof HttpResponseBase) {
try {
return this.processGetAllGroupHeaderCombo(<any>response_);
} catch (e) {
return <Observable<GetGroupHeaderOutput>><any>_observableThrow(e);
}
} else
return <Observable<GetGroupHeaderOutput>><any>_observableThrow(response_);
}));
}
protected processGetAllGroupHeaderCombo(response: HttpResponseBase): Observable<GetGroupHeaderOutput> {
const status = response.status;
const responseBlob =
response instanceof HttpResponse ? response.body :
(<any>response).error instanceof Blob ? (<any>response).error : undefined;
let _headers: any = {}; if (response.headers) { for (let key of response.headers.keys()) { _headers[key] = response.headers.get(key); }};
if (status === 200) {
return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => {
let result200: any = null;
let resultData200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver);
result200 = GetGroupHeaderOutput.fromJS(resultData200);
return _observableOf(result200);
}));
} else if (status !== 200 && status !== 204) {
return blobToText(responseBlob).pipe(_observableMergeMap(_responseText => {
return throwException("An unexpected server error occurred.", status, _responseText, _headers);
}));
}
return _observableOf<GetGroupHeaderOutput>(<any>null);
}
API Function
public async Task<GetGroupHeaderOutput> GetAllGroupHeaderCombo()
{
var output = new GetGroupHeaderOutput();
//Issue is ocurring here
var x = _groupHeaderRepository.GetAll();
//GroupHeader
output.GroupHeaderNames = _groupHeaderRepository
.GetAll()
.Select(s => new ComboboxItemDto
{
DisplayText = s.GroupTitle,
IsSelected = false
})
.ToList();
}
what i notice are 1.from your API your change list async
2.clean your service.proxy file and run 'refresh.bat' in your nswag file to generate new proxies.
I am using an token based authorization using .net as backend and angular 6 in front end and I have successfully able to receive the token from the server, but after authenticate method is called from the UI the token is reached to UI.
I am using an token based authorization using .net as backend and angular 6 in front end and I have successfully able to receive the token from the server, but after authenticate method is called from the UI I get an error;
TypeError: Cannot read property 'headers' of null.
C# webapi code for authenticate method is
[a.Route("api/authenticate/")]
[a.HttpPost]
public c.Http.HttpResponseMessage Authenticate([FromBody]User usr)
{
if (string.IsNullOrEmpty(usr.UserName) && string.IsNullOrEmpty(usr.Password))
{
var message = new c.Http.HttpResponseMessage(c.HttpStatusCode.NotAcceptable);
message.Content = new c.Http.StringContent("Not Valid Request");
return message;
}
else
{
if (auth.ValidateKeys(usr.UserName, usr.Password))
{
//var pass1 = EncryptionLibrary.DecryptText(ClientKeys.Password);
var pass = EncryptionLibrary.EncryptText(usr.Password);
var clientkeys = auth.GetClientKeysDetailsbyCLientIDandClientSecert(usr.UserName, pass);
if (clientkeys == null)
{
var message = new c.Http.HttpResponseMessage(c.HttpStatusCode.NotAcceptable);
message.Content = new c.Http.StringContent("Not Valid Request");
return message;
}
else
{
if (auth.IsTokenAlreadyExists(clientkeys.UserId))
{
auth.DeleteGenerateToken(clientkeys.UserId);
var response= GenerateandSaveToken(clientkeys);
return response;
}
else
{
var response= GenerateandSaveToken(clientkeys);
return response;
}
}
}
else
{
var message = new c.Http.HttpResponseMessage(c.HttpStatusCode.NotFound);
message.Content = new c.Http.StringContent("InValid Keys");
return new c.Http.HttpResponseMessage { StatusCode = c.HttpStatusCode.NotAcceptable };
//return new HttpResponseMessage { StatusCode = HttpStatusCode.NotAcceptable };
}
}
}
GenerateandSaveToken method is as follows:
private c.Http.HttpResponseMessage GenerateandSaveToken(User clientkeys)
{
var IssuedOn = DateTime.Now;
var newToken = auth.GenerateToken(clientkeys, IssuedOn);
TokensManager token = new TokensManager();
//token.TokenId = 0;
token.TokenKey = newToken;
token.UserID = clientkeys.UserId;
token.IssuedOn = IssuedOn;
token.ExpiresOn = DateTime.Now.AddMinutes(Convert.ToInt32(ConfigurationManager.AppSettings["TokenExpiry"]));
token.CreatedOn = DateTime.Now;
var result = auth.InsertToken(token);
if (result == 1)
{
c.Http.HttpResponseMessage response = new c.Http.HttpResponseMessage();
//response = Content(c.HttpStatusCode.Found, "Authorized");
response.Headers.Add("Token", newToken);
response.Headers.Add("TokenExpiry", ConfigurationManager.AppSettings["TokenExpiry"]);
response.Headers.Add("Access-Control-Expose-Headers", "Token,TokenExpiry");
return response;
}
else
{
var message = new c.Http.HttpResponseMessage(c.HttpStatusCode.NotAcceptable);
message.Content = new c.Http.StringContent("Error in Creating Token");
return message;
}
}
In angular code is as follows:
AuthenticationService
export class AuthenticationService {
private currentUserSubject: BehaviorSubject<User>;
public currentUser: Observable<User>;
private baseUrl: string = environment.apiUrl;
constructor(private http: HttpClient) {
this.currentUserSubject = new BehaviorSubject<User>(JSON.parse(localStorage.getItem('currentUser')));
this.currentUser = this.currentUserSubject.asObservable();
}
public get currentUserValue(): User {
return this.currentUserSubject.value;
}
login(User) {
console.log("User values check"+User)
const headers = new HttpHeaders()
//headers.append('Content-Type', 'application/json');
.set('Content-Type', 'application/x-www-form-urlencoded');
return this.http.post<any>(this.baseUrl+'api/authenticate/',User, {headers,responseType: "json"})
.pipe(map((user => {
// login successful if there's a jwt token in the response
console.log("user values"+user.headers.get('Token'))
if (user && user.headers.get('Token')) {
console.log("Reached tokens!!!")
// store user details and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('currentUser', JSON.stringify(user));
this.currentUserSubject.next(user);
}
/* this.http.put(apiURL, JSON.stringify(json),
{observe:'response'}).subscribe((res:Response) =>
console.log(res));*/
return user;
})));
}
logout() {
// remove user from local storage to log user out
localStorage.removeItem('currentUser');
this.currentUserSubject.next(null);
}
}
Calling the above login method from LoginComponent as follows:
export class LoginComponent implements OnInit {
response:{}
loginForm: FormGroup;
loading = false;
submitted = false;
returnUrl: string;
usr:User[];
constructor(
private formBuilder: FormBuilder,
private route: ActivatedRoute,
private router: Router,
private authenticationService: AuthenticationService,
private alertService: AlertService,
) {
// redirect to home if already logged in
if (this.authenticationService.currentUserValue) {
this.router.navigate(['/']);
}
}
ngOnInit() {
this.loginForm = this.formBuilder.group({
username: ['', Validators.required],
password: ['', Validators.required]
});
// get return url from route parameters or default to '/'
this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/';
}
// convenience getter for easy access to form fields
get f() { return this.loginForm.controls; }
onSubmit() {
this.submitted = true;
let frm= JSON.stringify(this.loginForm.value);
console.log("printing form values"+this.loginForm.value)
console.log("frm values"+frm)
// stop here if form is invalid
if (this.loginForm.invalid) {
return;
}
/* .subscribe( t =>
this.CatalogForm.patchValue
({Category:t,SubCategory:t,Description:t,ItemName:t,IAP_Number:t})
, err =>
console.log("Error messgae:",this.errorMessage)
);*/
this.loading = true;
this.authenticationService.login(frm)
.pipe(map((data:Response)=>data.json()))
.subscribe(
data => {
this.response = data,
console.log('Response'+this.response);
//this.loginForm.patchValue({User:data});
this.router.navigate([this.returnUrl]);
},
error => {
console.log("Reached Login error!!!")
this.alertService.error(error);
this.loading = false;
});
}
}
alertService as below:
#Injectable({ providedIn: 'root' })
export class AlertService {
private subject = new Subject<any>();
private keepAfterNavigationChange = false;
constructor(private router: Router) {
// clear alert message on route change
console.log("inside alert service!!!!")
router.events.subscribe(event => {
if (event instanceof NavigationStart) {
console.log("event:"+event)
if (this.keepAfterNavigationChange) {
// only keep for a single location change
console.log("inside Navigation Start!!!!")
this.keepAfterNavigationChange = false;
} else {
// clear alert
console.log("inside Navigation Start else method!!!!")
this.subject.next();
}
}
});
}
success(message: string, keepAfterNavigationChange = false) {
this.keepAfterNavigationChange = keepAfterNavigationChange;
console.log("inside Success Start!!!!")
this.subject.next({ type: 'success', text: message });
}
error(message: string, keepAfterNavigationChange = false) {
this.keepAfterNavigationChange = keepAfterNavigationChange;
console.log("Navigation value"+this.keepAfterNavigationChange);
console.log("inside Navigation error!!!!")
console.log("message"+message)
this.subject.next({ type: 'error', text: message });
}
getMessage(): Observable<any> {
return this.subject.asObservable();
}
}
Please note I am able to receive token from the server and the token is exposed as well from server side using below code
config.EnableCors(new EnableCorsAttribute(origins: "*", headers: "*", methods: "*", exposedHeaders: "TestHeaderToExpose") { SupportsCredentials = true });
config.MapHttpAttributeRoutes();
config.EnableCors();
I should be successfully able to receive the token from the server and ui should display an success message as in below html
<div *ngIf="message"
[ngClass]="{ 'alert': message, 'alert-success': message.type === 'success', 'alert-danger': message.type === 'error' }">
{{message.text}}</div>
In your AuthenticationService's login method, use this, you'll have to pass observe: 'response' as well to the HttpOptions argument, in order to get the complete response. Something like this:
export class AuthenticationService {
private currentUserSubject: BehaviorSubject < User > ;
public currentUser: Observable < User > ;
private baseUrl: string = environment.apiUrl;
constructor(private http: HttpClient) {
this.currentUserSubject = new BehaviorSubject < User > (JSON.parse(localStorage.getItem('currentUser')));
this.currentUser = this.currentUserSubject.asObservable();
}
public get currentUserValue(): User {
return this.currentUserSubject.value;
}
login(User) {
console.log("User values check" + User)
const headers = new HttpHeaders({
'Content-Type', 'application/x-www-form-urlencoded'
});
return this.http.post < any > (this.baseUrl + 'api/authenticate/', User, {
headers,
responseType: "json",
observe: 'response'
})
.pipe(map((user => {
// login successful if there's a jwt token in the response
console.log("user values" + user.headers.get('Token'))
if (user && user.headers.get('Token')) {
console.log("Reached tokens!!!")
// store user details and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('currentUser', JSON.stringify(user));
this.currentUserSubject.next(user);
}
/* this.http.put(apiURL, JSON.stringify(json),
{observe:'response'}).subscribe((res:Response) =>
console.log(res));*/
return user;
})));
}
logout() {
// remove user from local storage to log user out
localStorage.removeItem('currentUser');
this.currentUserSubject.next(null);
}
}
I have been given this API which is based in PHP but I need to convert it into C#. This is only the first method and this is my result.
I seem to be missing a lot. Will this c# method function as the PHP ones does
PHP:
// Call SVP Service
function callSVPService($service, $arg, $raw_data = false) {
global $entry_point;
$count_attempts = 3;
$token_error_codes = array(2004, 2005, 2006);
$counter = 0;
// Make a attempts to call a SVP API service.
// With this we can automatically generate a new token if the token is empty,
// the token is not valid or the validation period of the token is expired.
while(true) {
$counter++;
$token_response = getToken();
// If token error occurs - exit calling service.
if($token_response['error_code']) {
return array('error_code' => $token_response['error_code'], 'response' => '');
}
$token = $token_response['token'];
$arg['token'] = $token;
$response = callSVP_API_Service($service, $arg);
$result = getTextBetweenTags($response, 'result', true);
if(!$result) {
if(!$raw_data) {
return array('error_code' => -1, 'response' => $response);
}
else if(!$response) {
return array('error_code' => -1, 'response' => 'Empty server response');
}
else {
$error_code = 0;
}
}
else if($result == 'ERROR') {
$error_code = getTextBetweenTags($response, 'code', true);
}
else if($result == 'OK') {
$error_code = 0;
}
if(!$error_code) {
return array('error_code' => 0, 'response' => $response);
}
else if(in_array($error_code, $token_error_codes)) {
// The service response contains a token error. Try to generate a new token.
saveToken(0);
}
if($counter >= $count_attempts) {
return array('error_code' => $error_code, 'response' => $response);
}
}
}
C#
public dynamic callSVPService(dynamic service, dynamic arg, dynamic raw_data)
{
var countAttempt = 3;
int[] tokenErrorCodes;
tokenErrorCodes = new int[2004];
tokenErrorCodes = new int[2005];
tokenErrorCodes = new int[2006];
var counter = 0;
while (true)
{
counter++;
var tokenResponse = getToken();
var token = tokenResponse["token"];
var response = callSVPAPIService(service, arg);
var result = getTextBetweenTags(response, "result", true);
return result;
}
}