Retrieve ID created by Firebase Post - c#

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.

Related

DELETE request works from insomnia/postman but not from the frontend

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.

Throwing a custom C# .Net exception does not get recognized by Axios in React

This is how I throw the exception:
throw RestExceptionHandler.ThrowException(ErrorCode.WebServiceConnectorUnableToGetUser);
This is the ThrowException method:
public static RestServerException ThrowException(ErrorCode errorCode, object[] parameters = null, string property = null)
{
try
{
var value = ErrorCodes.errorList.First(code => code.errorCode == errorCode);
if (parameters?.Length > 0)
{
return new RestServerException(string.Format(value.description, parameters),
value.httpStatusCode, new ErrorDescription
{
property = property ?? value.property,
errorCode = value.errorCode
});
}
value.description = value.description.Replace("'{0}'", "");//removing placeholder {0} if there are no parameters given
return new RestServerException(value.description,
value.httpStatusCode, new ErrorDescription
{
property = property ?? value.property,
errorCode = value.errorCode
});
}
catch (Exception e)
{
Log.Error(e, "Error: {#Exception}", e);
throw;
}
}
This is the exception error body:
Now comes the React code, this is the post function in my service:
getUser(request: any) {
const res = axios
.post<any, AxiosResponse<any>>("https://localhost:5002/v/1/signumid_integrations/user", request)
.then((res) => {
console.log(res);
return res.data;
})
.catch(function (err) {
console.log(err);
});
return res;
}
And this is how I call the getUser method:
httpClient
.getUser(request)
.then((res2) => {
initiator.current =
res2.mail === null || res2.mail === undefined || res2.mail === "" ? res2.userPrincipalName : res2.mail;
});
And this is the Axios error that I get every time. It is a default empty network error every time.
What could be the problem here and how do I solve it?
This is what the getUser method looks in network:
It returns 500, even though i set it to 400.
This is the controller in minimal api code:
app.MapPost("v/1/signumid_integrations/user", async (ExchangeOBORequest request) =>
await IntegrationsService.GetUser(request));

Why does the code always go to the not false part upon returning the control to the request?

I have this call which calls a action in the controller and expects a true or false in the object named data.
$("#btnReview").click(function () {
var data = {
'id': '1',
'recordID': selectedInspectionId, 'RoleRemarks': $("#CNGInspectionReport_RoleRemarks").val()
};
$.post('/CNGInspectionReport/ChangeStatus', data, function (data) {
if (data == false) {
alert('Something went wrong');
}
else {
alert('Record reviewed successfully. Kindly review the further records, if any.');
}
});
});
and
public ActionResult ChangeStatus(int id, int recordID, string RoleRemarks, string Role = "") // Later, this should be converted to an object instead of parameters
{
try
{
using (UnitOfWork uwork = new UnitOfWork())
{
CNGInspectionReportDAL = new CNGInspectionReportDAL();
User user = (User)Session["User"];
CNGInspectionReport CNGInspectionReport = uwork.CNGInspectionReportRepository.GetByID(recordID);
CNGInspectionReport.CNGInspectionReportID = recordID;
bool statusCrossOffice = false;
if (id == 1) //Reviewed
{
if(user.Office.Trim() != CNGInspectionReport.StationName.Trim())
{
return Json(new { data = statusCrossOffice, message = "Sorry, this record belongs to another office/station and can only be reviewed by the user of the same station/office" });
}
CNGInspectionReport.RoleRemarks = RoleRemarks;
CNGInspectionReport.CheckedBy = user.UserID;
CNGInspectionReport.CheckedByName = user.UserName;
CNGInspectionReport.Status = (byte)id;
CNGInspectionReport.ReviewDate = DateTime.Now;
}
return Json(new { data = status, message = "Success" });
}
}
catch (Exception ex)
{
ViewBag.Error = ex.Message;
return Json(new { data = false, message = ex.Message });
}
}
but the problem is that it still goes to the else block when returns to the Ajax call. Why? I have clearly returned Fase in data but still it goes to the else part which is NOT FALSE.
You should evaluate your data property of the returned object
if (data.data == false) {
alert('Something went wrong');
}
This is because the data returned value is an object and not a boolean. You can check the value yourself line this:
$.post('/CNGInspectionReport/ChangeStatus', data, function (data) {
alert(JSON.stringify(data));
// etc

In ASP.Net Zero, Why I am not getting records when I try to execute an API using Angular UI but when I use swagger It returns the expected value?

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.

MVC 3 Uploadify HTTP 302 error

I have configuration problems with uploadify (v.2.1.4) and my MVC 3 project. Here's the code which returns the HTTP 302 code.
#{string auth = #Request.Cookies[FormsAuthentication.FormsCookieName] == null ? string.Empty : Request.Cookies[FormsAuthentication.FormsCookieName].Value;}
$("#fileuploader").uploadify({
uploader: '#Url.Content("~/Scripts/uploadify.swf")',
script: '#Url.Action("Upload", "Control")',
scriptData: { token: "#auth" },
fileDataName: 'file',
buttonText: 'Upload file',
multi: false,
sizeLimit: 22222222222,
simUploadLimit: 1,
cancelImg: '#Url.Content("~/Images/uploadify-cancel.png")',
auto: true,
onError: function(event, queueID, fileObj, errorObj) {
alert("Error!!! Type: [" + errorObj.type + "] Info [" + errorObj.info + "]");
},
onComplete: function (event, queueId, fileObj, response, data) {
alert(response);
}
});
public class ControlController : Controller
{
[HttpPost]
public ActionResult Upload(string token, HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
var appData = Server.MapPath("~/app_data");
var filename = Path.Combine(appData, Path.GetFileName(file.FileName));
file.SaveAs(filename);
}
return Json(true);
}
}
1) The controller's action is not being fired
2) I've found that topic Getting Uploadify to work with asp.net-mvc, but if I use that attribute to my controller, I see that "AuthenticationToken" is null (I'm logged in)
3) If I set the uploadify option 'method' to 'post' I get the #2032 error
EDIT
The controller is the Admininistration controller, so I use that Attribute to it:
protected override bool AuthorizeCore(HttpContextBase httpContext) {
if (!HttpContext.Current.User.Identity.IsAuthenticated)
return false;
if (admin && !um.IsAdmin(HttpContext.Current.User.Identity.Name))
return false;
return true;
}
which returns true. I've noticed, if I remove this attribute, the uploads started working. But I need that Attribute
it's help you.
var auth = "#(Request.Cookies[FormsAuthentication.FormsCookieName]==null ? string.Empty : Request.Cookies[FormsAuthentication.FormsCookieName].Value)";
var ASPSESSID = "#(Session.SessionID)";
$("#uploadifyLogo").uploadify({
...
'scriptData': { 'ASPSESSID': ASPSESSID, 'AUTHID': auth }
});
In Global.asax :
protected void Application_BeginRequest(object sender, EventArgs e)
{
/* we guess at this point session is not already retrieved by application so we recreate cookie with the session id... */
try
{
string session_param_name = "ASPSESSID";
string session_cookie_name = "ASP.NET_SessionId";
if (HttpContext.Current.Request.Form[session_param_name] != null)
{
UpdateCookie(session_cookie_name, HttpContext.Current.Request.Form[session_param_name]);
}
else if (HttpContext.Current.Request.QueryString[session_param_name] != null)
{
UpdateCookie(session_cookie_name, HttpContext.Current.Request.QueryString[session_param_name]);
}
}
catch
{
}
try
{
string auth_param_name = "AUTHID";
string auth_cookie_name = FormsAuthentication.FormsCookieName;
if (HttpContext.Current.Request.Form[auth_param_name] != null)
{
UpdateCookie(auth_cookie_name, HttpContext.Current.Request.Form[auth_param_name]);
}
else if (HttpContext.Current.Request.QueryString[auth_param_name] != null)
{
UpdateCookie(auth_cookie_name, HttpContext.Current.Request.QueryString[auth_param_name]);
}
}
catch
{
}
}
private void UpdateCookie(string cookie_name, string cookie_value)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies.Get(cookie_name);
if (null == cookie)
{
cookie = new HttpCookie(cookie_name);
}
cookie.Value = cookie_value;
HttpContext.Current.Request.Cookies.Set(cookie);
}

Categories

Resources