Mvvmcross 6.2.3 strange behavior of viewmodel navigation - mvvmcross

I'm playing with MVVMCROSS 6.2.3 and I have an issue with nested navigation in my XForms UWP app.
Here is a description:
VM1 navigate to VM2 and VM1 is waiting for a result of VM2!
VM2 navigate to VM3, VM2 does not need a result of VM3.
After navigation from VM2 to VM3 and VM1 is unexpectedly getting a null result.
public class MainViewModel : MvxViewModel
{
public IMvxAsyncCommand GoToSecondPageCommand =>
new MvxAsyncCommand(async () =>
{
var param = new Dictionary<string, string> { { "ButtonText", ButtonText } };
var result = await navigationService.Navigate<SecondViewModel, Dictionary<string, string>, SecondViewModelResult>(param);
var breakpoint = 1;
//HERE IS THE ISSUE, result IS NULL because it fires immediately after Navigate<ThirdViewModel>()
});
public IMvxAsyncCommand BackCommand => new MvxAsyncCommand(async () =>
{
await navigationService.Close(this, new SecondViewModelResult { Result = "Back button clicked" });
});
}
public class SecondViewModel : MvxViewModel<Dictionary<string, string>, SecondViewModelResult>
{
public IMvxAsyncCommand GoToThirdPageCommand =>
new MvxAsyncCommand(async () =>
{
var t = await navigationService.Navigate<ThirdViewModel>();
var breakpoint = 2;
});
}
public class ThirdViewModel : MvxViewModel
{
}
You could run it by yourself from my GitHub https://github.com/JTOne123/XamFormsMvxTemplate
This behavior was good in version 5.7 and VM1 is waiting until VM2 return the result.
What am I doing wrong?

Related

Swagger not working (rather exception is thrown) after migrating project from .net core 2.2 to 3.0 preview-7

I have just migrated my project from .net core 2.2 to 3.0 preview 7. I am using Swashbuckle.AspNetCore (v4.0.1) in it. This is my startup class.
public class Startup
{
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration["ConnectionStrings:ConnectionStringAzureSQL"]));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
services.AddApplicationInsightsTelemetry();
services.AddLocalization(options => options.ResourcesPath = #"Resources");
services.AddMemoryCache();
services.Configure<RequestLocalizationOptions>(options =>
{
var supportedCultures = new List<CultureInfo>
{
new CultureInfo("en-US")
};
options.DefaultRequestCulture = new RequestCulture("en-US");
options.SupportedCultures = supportedCultures;
options.SupportedUICultures = supportedCultures;
});
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info { Title = "GetAJobToday", Description = "GetAJobTodayAPIs" });
var xmlPath = AppDomain.CurrentDomain.BaseDirectory + #"PlatformAPI.xml";
c.IncludeXmlComments(xmlPath);
c.AddSecurityDefinition("Bearer",
new ApiKeyScheme
{
In = "header",
Description = "Please enter token into the field",
Name = "Authorization",
Type = "apiKey"
});
c.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>>
{
{"Bearer", new string[] { }},
});
});
services.AddSingleton<ITelemetryInitializer, HttpContextItemsTelemetryInitializer>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseRouting();
app.UseMiddleware<ApiLoggingMiddleware>();
app.UseHttpsRedirection();
app.UseRequestLocalization(app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>().Value);
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapControllerRoute("default", "{controller=Auth}/{action=RequestVerificationCode}/{id?}");
});
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "GetAJobToday");
});
}
}
But it is throwing this exception when I run it:
AggregateException: Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Swashbuckle.AspNetCore.Swagger.ISwaggerProvider Lifetime: Transient ImplementationType: Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenerator': Failed to compare two elements in the array.) (Error while validating the service descriptor 'ServiceType: Swashbuckle.AspNetCore.SwaggerGen.ISchemaRegistryFactory Lifetime: Transient ImplementationType: Swashbuckle.AspNetCore.SwaggerGen.SchemaRegistryFactory': Failed to compare two elements in the array.)
Upgrading Swashbuckle.AspNetCore and Swashbuckle.AspNetCore.Filters to v 5.0.0-rc2 solved the problem.
Upgrading Swashbuckle.AspNetCore to the latest version v 5.0.0-rc4 solved the problem.

How to fix DOMException error in google chrome?

I work with sounds in a browser game. I wrote sound manager. everything works fine, but not in Google chrome. I handled the error "uncaught (in promise) domexception", after the sounds were played in 50 percent of cases, in other cases it returns the error DOMException. What could be the problem?
export class AudioFile{
private audio: HTMLAudioElement;
private fileMP3: string;
private fileOGG: string;
private volume = 1;
private loop = false;
constructor(MP3:string, OGG:string) {
this.audio = new Audio();
this.fileMP3 = MP3;
this.fileOGG = OGG;
this.audio.canPlayType('audio/mpeg') ? this.audio.src = this.fileMP3 : this.audio.src = this.fileOGG;
this.audio.load();
this.audio.volume = this.volume;
this.audio.loop = this.loop;
}
public play() {
this.audio.currentTime = 0;
const playPromise = this.audio.play();
if (playPromise !== undefined) {
playPromise.then(_ => {
})
.catch(error => {
console.log(error);
});
}
}
public stop() {
this.audio.pause();
}
}
``````````````sound manager`````````````
export class SoundManager {
private sounds = new Map();
private static _soundManager: SoundManager;
constructor(){
if (SoundManager._soundManager) {
throw new Error("Instantiation failed: "+
"use Singleton.getInstance() instead of new.");
}
SoundManager._soundManager = this;
}
public static get instance(): SoundManager {
if (this._soundManager)
return this._soundManager;
else
return this._soundManager = new SoundManager();
}
preload() {
const pathMP3 = SoundConfig.PATHMP3;
const pathOGG = SoundConfig.PATHOGG;
for (const item in SoundConfig.SOUNDS) {
const name = SoundConfig.SOUNDS[item].NAME;
this.sounds.set(name, new AudioFile(pathMP3 + name + '.mp3', pathOGG + name + '.ogg'));
}
}
getSound(id: string): AudioFile {
return this.sounds.get(id);
}
}
Thank you spendr.
error: DOMException
code: 0
message: "play() failed because the user didn't interact with the document first.
Game runs through the iframe and I was needed to add a feature policy for autoplay.
<iframe src="..." allow="autoplay">
The article that helped me in solving the problem

Angular 2 periodically pull real time data

I have developed an app which basically has admin and client portal running in separate ports and when an order is placed from client side, the admin dashboard should be able to get the new order shown.
Basically the view has to be refreshed to keep an updated UI.
For which i have referred the below link:
http://beyondscheme.com/2016/angular2-discussion-portal
Below is what i have tried.
order-issue.component.ts
ngOnInit() {
const user_id = {
user_ids: this.user_id
};
// To display the Pending Orders into the table
this.orderService.getAllOrders("Pending").subscribe(data => {
if (data.success && data.Allorders.length != 0) {
for (let i = 0; i < data.Allorders.length; i++) {
this.orderService
.getOrderItemsByNo(data.Allorders[i].orderNo)
.subscribe(subData => {
data.Allorders[i].orderItems = subData;
});
}
this.source = data.Allorders; //To display the data into smart table
this.refreshData(); //For real time refresh
} else {
this.flashMessage.show("No Pending Orders", {
cssClass: "alert-success",
timeout: 300000
});
}
});
private refreshData(): void {
this.commentsSubscription = this.orderService.getAllOrders("Pending").subscribe(data => {
this.data = data;
console.log(data); //able to see the new orders
this.subscribeToData();
});
private subscribeToData(): void {
this.timerSubscription = Observable.timer(5000).first().subscribe(() => this.refreshData());
}
My service(orderService) will get all the orders:
getAllOrders(status) {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http.post(`${BASE_URL}/orders/getAllOrdersWithItems`, { status: status }, { headers: headers })
.map(res => res.json());
}
Ok i am able to fix it with below change.
//Function which refreshes the data in real time without page refresh
private refreshData(): void {
this.commentsSubscription = this.orderService.getAllOrders("Pending").subscribe(data => {
this.source = data.Allorders; //Updated here! and it worked
console.log(this.source);
this.subscribeToData(); //On success we call subscribeToData()
});
}

Pushing complete data from Spring Boot server through Web Socket to Client

I have a spring boot server and i am able to generate a streaming table on client side by sending json one after the another. The problem is if a user logs in say after 10 minutes, he is only able to access data starting from 10th minute i.e he is not able to access data from 0 to 10th minute. What i want is to push the data from 0th to 10th minute first and at the same time continue the streaming process. How can this be done? I am using jquery datatable to generate the table.
I am attaching the controller and client side html for reference
1) Controller
#Controller
public class ScheduledUpdatesOnTopic {
#Autowired
private SimpMessagingTemplate template;
int count=0;
#Scheduled(fixedDelay=500)
public void trigger() {
DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
String str[] = {"name"+count,""+Math.round(Math.random()*100),"India"+Math.round(Math.random()*100),df.format(date)};
this.template.convertAndSend("/topic/message",str);
++count;
}
}
2) Client HTML
var _self = this;
$(document).ready(function() {
var message ;
$('#tbl').DataTable( {
data: message,
"aLengthMenu" : [[25,50,75,-1],[25,50,75,"All"]],
"pageLength" :25,
columns: [
{ title: "Name" },
{ title: "Age" },
{ title: "Country" },
{ title: "Date"}
]
});
subscribeSocket();
});
function addRow(message){
var table = $('#tbl').DataTable();
if(table && message ){
table.row.add(message).draw();
}
}
function subscribeSocket(){
var socket = new SockJS('/gs-guide-websocket');
var stompClient = Stomp.over(socket);
stompClient.connect({ }, function(frame) {
stompClient.subscribe("/topic/message", function(data) {
message = JSON.parse(data.body);
_self.addRow(message);
});
});
};
If you don't save previous sent datas, you can't send them back to new customers.
On the front side, you have to subscribe to an "history" resource and make a call to get it.
Front:
function subscribeSocket() {
var socket = new SockJS('/gs-guide-websocket');
stompClient = Stomp.over(socket);
var firstCounterReceived = null;
stompClient.connect({}, function (frame) {
setConnected(true);
stompClient.subscribe('/topic/history', function (response) {
console.log(JSON.parse(response.body));
});
stompClient.subscribe('/topic/message', function (response) {
var message = JSON.parse(response.body);
if (firstCounterReceived == null) {
firstCounterReceived = message[0];
console.log(`Calling history endpoint with ${firstCounterReceived}`);
stompClient.send("/app/topic/history", {}, message[0]);
}
console.log(message);
});
});
}
Back:
#Controller
#EnableScheduling
public class ScheduledUpdatesOnTopic {
Map<Integer, String[]> history = new LinkedHashMap<>();
#Autowired
private SimpMessagingTemplate template;
private Integer count = 0;
#MessageMapping("/topic/history")
#SendTo("/topic/history")
public List<String[]> history(Integer to) {
return history.keySet()
.stream()
.filter(counter -> counter < to)
.map(counter -> history.get(counter))
.collect(Collectors.toList());
}
#Scheduled(fixedRate = 500)
public void sendMessage() {
DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
String[] str = {count.toString(), "name"+count,""+Math.round(Math.random()*100),"India"+Math.round(Math.random()*100),df.format(date)};
history.put(count, str);
this.template.convertAndSend("/topic/message",str);
++count;
}
}
In this sample, saved datas are stored in a map, be aware that it will consume some memory at some point.

need signalR polling for asp.net mvc

Any kind soul can guide me how to use signalR on an existing mvc project to poll data in real time i'd be greatly appreciate.
example code:
[controller]
private ApplicationDbContext db = new ApplicationDbContext();
public PartialViewResult Chat(string people) // <---need to send real time data to partial
{
var model = new MessageVM()
{
sender = User.Identity.Name;,
messageList = db.messages.Where(x => x.receiver == people).ToList().Take(30)
};
return PartialView("_chat", model);
}
[view]
#Ajax.ActionLink(item.name, "Chat", new { people = item.name }, new AjaxOptions()
{ HttpMethod = "GET", UpdateTargetId = "divChat", InsertionMode = InsertionMode.Replace })
<div id="divChat"></div> // <---this area need real-time messages data from controller.
First create your signalr connection in js in client side. something like:
function signalrconnection() {
$.connection.hub.url = "http://localhost:54321/signalr";
chat = $.connection.myHub;
if (chat != undefined) {
$.connection.hub.start()
.done(function () {
chat.server.send("client", "Status\tasking for status");
chat = $.connection.myHub;
})
.fail(function () { NoLTConnectionAlert(); });
}
else {
///do something.
}
}
return chat;
}
Then add signalr call to your $(document).ready(function ()) in your js something like:
$(document).ready(function () {
chat = signalrconnection();
intervalstatus = setInterval(checkstatus, 1000);
// Create a function that the hub can call to broadcast messages.
chat.client.addMessage = function (name, message) {}
}
In your controller you should have a class for hub and method inside like:
public class MyHub : Hub
{
public void Send(string name, string message)
{
Clients.Caller.addMessage("parameter", reply);
}
}
Then again you should handle Clients.Caller.addMessage in you js to update <div id="divChat"></div>