I'm using Angular 6: I have a service httppost with return type Observable<IResourceInfo>.
searchResourceSuggestion(param: ISearchResourceParam): Observable<IResourceInfo[]>{
return this.httpClient.post<IResourceInfo[]>(url, param); }
And in my component file:
I call it in event :
this.searchResourceService.searchResourceSuggestion(param).pipe(takeUntil(this.destroy)).subscribe(data => {
this.data= data;});
But this.data is ReplaySubject<IResourceInfo[]> = new ReplaySubject<IResourceInfo[]>(1);
and it show error missing the following properties from type ReplaySubject.
Can anyone help me?
Related
As a sample of what I'm trying to accomplish, here in MapPost I'm manually parsing the body of the HTTP request.
// Program.cs
using System.Text.Json;
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
Type[] types = new[] { typeof(SampleDto1), typeof(SampleDto2), <other unknown types> };
foreach (var type in types)
{
app.MapPost(type.Name, async (HttpContext httpContext) =>
{
var request = await JsonSerializer.DeserializeAsync(
httpContext.Request.Body,
type,
new JsonSerializerOptions(JsonSerializerDefaults.Web),
httpContext.RequestAborted);
return Results.Ok(request);
});
}
app.Run();
internal record SampleDto1(string Input) { }
internal record SampleDto2(string Input) { }
This works, yay! However, ... ASP.NET Core's MVC has all these sophisticated ModelBinding functionality and I really would like to use that. Because that opens up possibilities for binding to querystring parameters and other sources instead of only the request body.
Basically I want to replace the call to JsonSerializer with a call to framework code.
I've been browsing the ASP.NET Core source code and at first the DefaultModelBindingContext looked promising. However, I soon stumbled on some internal classes which I couldn't access from my code.
Long story short, .. is it at all possible to plug-in to MVC's model binding from application code?
Update: Although it doesn't show from the initial question, the solution should work dynamically with any request type. Not only SampleDto1 and SampleDto2. That's why explicit parameter binding from Minimal API won't do the trick.
You could try the codes :
using Microsoft.AspNetCore.Mvc;
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
builder.Services.AddSingleton<Service>();
app.MapPost("/{id}", ([FromRoute] int id,
[FromQuery(Name = "p")] int page,
[FromBody]SampleDto1 sample1,
[FromBody] SampleDto2 sample2,
[FromServices] Service service,
[FromHeader(Name = "Content-Type")] string contentType)
=> { });
app.Run();
internal record SampleDto1(string Input) { }
internal record SampleDto2(string Input) { }
You could read the official document for more details:
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/minimal-apis?view=aspnetcore-6.0#explicit-parameter-binding
I was able to receive push notifications some months ago, a day ago i started to work again on the app now the issue is it's not able to receive push notification. It does provide FCM token but onMessageReceived never gets called also if i try with Postman it gives an error of Mismatchsender ID, but the scenario here is a bit confusing. If i change the package name (after creating new project on console and added new goole-service.json file) it doesn't let me register for FCM token. i've stuck in this situation from last day. can anybody please help? what i'm doing wrong.
Here is implementaion of FCMToken
[Service]
[IntentFilter(new[] { "com.google.firebase.INSTANCE_ID_EVENT" })]
public class MyFirebaseIIDService : FirebaseInstanceIdService
{
const string TAG = "MyFirebaseIIDService";
public override void OnTokenRefresh()
{
var refreshedToken = FirebaseInstanceId.Instance.Token;
Log.Debug(TAG, "Refreshed token: " + refreshedToken);
SendRegistrationToServer(refreshedToken);
}
void SendRegistrationToServer(string token)
{
// Add custom implementation, as needed.
}
}
Here it gives me error if i change my package name to any other,
Error: Java.Lang.IllegalStateException: Default FirebaseApp is not
initialized in this process
try
{
var refreshedToken = FirebaseInstanceId.Instance.Token;
// PushNotificationManager.Initialize(this, false);
} catch(Exception ee)
{
}
I've solved my issue with with customization of FirebaseInitialize after creating new project on Firebase here is my code. But one bad thing is here that when new token gets initialized it never gets called on FirebaseInstanceIdReceiver.
var options = new FirebaseOptions.Builder()
.SetApplicationId("<AppID>")
.SetApiKey("<ApiKey>")
.SetDatabaseUrl("<DBURl>")
.SetStorageBucket("<StorageBucket>")
.SetGcmSenderId("<SenderID>").Build();
var fapp = FirebaseApp.InitializeApp(this, options);
I have a xamarin form apps and I need it to consume an asmx web service. I encounter error when creating class in Android platform to implement the interface.
I have following this tutorial (https://www.c-sharpcorner.com/article/consuming-asmx-services-in-xamarin-forms/) to consume the asmx web service. I have this web method called "GetAllProjects" which will return List. I keep encounter error for the line of code:
"return new List(result);" (refer to the codes below).
Error message: Error CS1503 Argument 1: cannot convert from 'IMSr2.Droid.IMSWS.Project[]' to 'int'. How should I return the result from the web service?
public async Task<List<IProject>> GetAllProjects(string criteria = null)
{
return await Task.Run(() =>
{
var result = service.GetAllProjects();
return new List<IProject>(result);
/* How should I return the result from the web service?*/
});
}
/* This hello world is working*/
public Task<string> HelloWorld()
{
return Task.Run(() =>
{
return service.HelloWorld();
});
}
I am expecting the same result as the tutorial: https://www.c-sharpcorner.com/article/consuming-asmx-services-in-xamarin-forms/
I need to return the result from the webservice call ("GetAllProjects") and display in the listview.
Appreciate for help.
If you check the error statement correctly it says IMSr2.Droid.IMSWS.Project[]' to 'int' which clearly means that the method of your Service object by the name of getallprojects returns int
i.e.
service.GetAllProjects();
Is returning int when it should be returning Project[].
Check return type for GetAllProjects
I have custom middleware that provides global error handling. If an exception is caught it should log the details with a reference number. I then want to redirect the user to an error page and only show the reference number. My research shows that TempData should be ideal for this but it only seems to be accessible from within a controller context. I tried adding the reference number to HttpContext.Items["ReferenceNumber"] = Guid.NewGuid();
But this value is lost through the redirect.
How can middleware pass information through a redirect? Do I just have to put the number in a querystring?
Inside the middleware class you need to add a reference to get access to the required interfaces. I have this middleware in a separate project and needed to add this NuGet package.
using Microsoft.AspNetCore.Mvc.ViewFeatures;
This then allows you to request the correct services within the middleware.
//get TempData handle
ITempDataDictionaryFactory factory = httpContext.RequestServices.GetService(typeof(ITempDataDictionaryFactory)) as ITempDataDictionaryFactory;
ITempDataDictionary tempData = factory.GetTempData(httpContext);
After you have ITempDataDictionary you can use it like you would use TempData within a controller.
//pass reference number to error controller
Guid ReferenceNum = Guid.NewGuid();
tempData["ReferenceNumber"] = ReferenceNum.ToString();
//log error details
logger.LogError(eventID, exception, ReferenceNum.ToString() + " - " + exception.Message);
Now when I get the the controller after a redirect I have no issues pulling out the reference number and using it in my view.
//read value in controller
string refNum = TempData["ReferenceNumber"] as string;
if (!string.IsNullOrEmpty(refNum))
ViewBag.ReferenceNumber = refNum;
#*display reference number if one was provided*#
#if (ViewBag.ReferenceNumber != null){<p>Reference Number: #ViewBag.ReferenceNumber</p>}
Once you put this all together, you give users a reference number that they can give you to help troubleshoot the problem. But, you are not passing back potentially sensitive error information which could be misused.
You can register an ITempDataProvider yourself and use it in your middleware. Here is a small sample I got working between two simple paths. If you are already using MVC the ITempDataProvider is probably already registered. The issue I faced was the path of the cookie that was written. It was /page1 so /page2 did not have access to the cookie. So I had to override the options as you can see in code below.
I hope this will help you :)
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IDataProtectionProvider>(s => DataProtectionProvider.Create("WebApplication2"));
services.Configure<CookieTempDataProviderOptions>(options =>
{
options.Path = "/";
});
services.AddSingleton<ITempDataProvider, CookieTempDataProvider>();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ITempDataProvider tempDataProvider)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.Map("/page1", (app1) =>
{
app1.Run(async context =>
{
tempDataProvider.SaveTempData(context, new Dictionary<string, object> { ["Message"] = "Hello from page1 middleware" });
await context.Response.WriteAsync("Hello World! I'm page1");
});
});
app.Map("/page2", (app1) =>
{
app1.Run(async context =>
{
var loadTempData = tempDataProvider.LoadTempData(context);
await context.Response.WriteAsync("Hello World! I'm page2: Message from page1: " + loadTempData["Message"]);
});
});
}
This led me in the right direction: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/app-state#cookie-based-tempdata-provider
Happy coding! :)
My Scenario is I created a Web API that returns an Active Directory Object.
I have this WEB API function create Active Directory User and creates a user that returns Active Directory Object that contains First Name , Last Name, Email, UserName, Etc... What If it got an error how would I handle this?
I'm using Kendo Grid InLine Edit http://demos.kendoui.com/web/grid/editing-inline.html
I want to show the error message as a pop up window
How would I do that???
Options
try catch the error and put in the Active Directory Object as
Exception???
How can I capture this is Kendo UI?
Throw the response and get the error message and show it in the Kendo Grid
//HttpResponseMessage msg = new HttpResponseMessage(HttpStatusCode.OK)
//{
// Content = new StringContent(string.Format("No User with ID = {0}.{1}", businessObject.UserName, ex.InnerException.ToString() )),
// ReasonPhrase = "CustomerID Not Found in Database!"
//};
//throw new HttpResponseException(msg);
OR
//var message = string.Format("Error Message: {0}", taskCreateADUser.ADExceptionDescription);
//throw new HttpResponseException(
// Request.CreateErrorResponse(HttpStatusCode.OK, message));
Thanks,
MarcLevin
Whenever KendoUI binds via Ajax it relies on serialized version of ModelState sent in json response. Essentially if ModelState is not valid, the json response returned to the widget (grid in this case) will contain something like this:
{
"Errors":{
"PropA":{
"errors":[
"Error1",
"Error2"
]
},
"PropB":{
"errors":[
"FUBAR"
]
}
}
}
Essentially your WebAPI will need to return similar data structure if you want the grid to respond to it.
This is regarding your Option 2. You would need to apply the following correctly to your specific scenario. This is just a sample of a really simple parse of the response and displaying an alert if an error is detected. This sample expects a JSON object containing an array of Items. You could definitely apply more advanced handling once you have the basic idea down.
$("#grid").kendoGrid({
dataSource: {
schema: {
data: function(data) {
if (data.Items[0].substring(0,37) == "allmyerrormessagesstartwiththisphrase"){
alert(data.Items[0];
} else {
return data.Items;
}
}
},
transport: {
read: "http://myurl.com/something/"
}
}
}
);