SignalR .NET Client throw error during connection start - signalr.client

I face the next problem. I try to connect to SignalR server. I create HubConnection instance and the start connection. That is successfully. But when I create proxy hub for that connection I get exception.
SignalR version 2.2.0
Code example:
hubConnection = new HubConnection(inputDataContract.rootUrl + inputDataContract.defaultServicePath);
hubConnection.TraceLevel = TraceLevels.All;
hubConnection.TraceWriter = Console.Out;
hubConnection.Start().ContinueWith(task => {
if (task.IsFaulted)
{
Console.WriteLine("There was an error opening the connection:{0}",
task.Exception.GetBaseException());
}
else
{
Console.WriteLine("Connected");
}
}).Wait();
hubConnection.Stop();
That above code is executed successfully.
Log of connection
But next piece of code leads to error
hubConnection = new HubConnection(inputDataContract.rootUrl + inputDataContract.defaultServicePath);
hubConnection.TraceLevel = TraceLevels.All;
hubConnection.TraceWriter = Console.Out;
hubProxy = hubConnection.CreateHubProxy("Configurator");
hubProxy.On<EventArgs>("valueChanged", res => onValueChanged(res));
hubProxy.On<EventArgs>("configurationStateChanged", res => onConfigurationStateChanged(res));
hubProxy.On<EventArgs>("componentModifierChanged", res => onComponentModifierChanged(res));
hubProxy.On<EventArgs>("attributeFeasibility", res => onAttributeFeasibility(res));
hubProxy.On<EventArgs>("attributeModifierChanged", res => onAttributeModifierChanged(res));
hubProxy.On<EventArgs>("calculationSummary", res => onCalculationSummary(res));
hubProxy.On<EventArgs>("configurationError", res => onConfigurationError(res));
hubProxy.On<EventArgs>("unhandledTaskException", res => onUnhandledTaskException(res));
hubConnection.Start().ContinueWith(task => {
if (task.IsFaulted)
{
Console.WriteLine("There was an error opening the connection:{0}",
task.Exception.GetBaseException());
}
else
{
Console.WriteLine("Connected");
}
}).Wait();
hubConnection.Stop();
Error msg
I will be very appreciate for any help.

Related

NetCore3 API not returning/serializing my data

I have the following controller:
[HttpGet("idfull/{id}")]
public async Task<IActionResult> GetAccountByIdFull(int id)
{
try
{
var response = await _accountFacade.GetAccountByIdAsync(id, full: true).ConfigureAwait(false);
if (response == null)
return NoContent();
return Ok(response);
}
catch (KeyNotFoundException kEx)
{
return NotFound();
}
catch (Exception ex)
{
return StatusCode((int)HttpStatusCode.InternalServerError);
}
}
The Facade layer:
public async Task<AccountViewModel> GetAccountByIdAsync(int accountId, bool full = false)
{
try
{
var unmappedResponse = await _accountService.GetAccountByIdAsync(accountId, full);
var mappedResponse = _mapper.Map<AccountViewModel>(unmappedResponse);
return mappedResponse;
}
catch
{
throw;
}
}
The service layer:
public async Task<Account> GetAccountByIdAsync(int accountId, bool full = false)
{
try
{
Account account;
if (full)
{
account = await _repo.GetOneAsync<Account>(x => x.AccountId == accountId);
account.Company = await _repo.GetOneAsync<Company>(filter: x => x.CompanyId == account.CompanyId,
includes: source => source
.Include(c => c.CompanyTransferType)
.ThenInclude(ctt => ctt.PartnerCompanyAccountType)
.Include(c => c.CompanyTransferType).ThenInclude(ctt => ctt.TransferType)
.Include(c => c.CompanyEquipment).ThenInclude(ce => ce.Equipment)
.Include(c => c.CompanyAccountGroup)
.Include(c => c.CompanyAccountType));
account.AccountContact = await _repo.GetAsync<AccountContact>(filter: x => x.AccountId == accountId);
account.AccountEquipment = await _repo.GetAsync<AccountEquipment>(filter: x => x.AccountId == accountId,
includes: source => source
.Include(ae => ae.AccountEquipmentFee).Include(ae => ae.CompanyEquipment).ThenInclude(ce => ce.Equipment));
account.AccountPickVolumeDefaultAccount = await _repo.GetAsync<AccountPickVolumeDefault>(filter: x => x.AccountId == accountId,
includes: source => source
.Include(a => a.Equipment).Include(a => a.PartnerAccount));
}
else
{
account = await _repo.GetByIdAsync<Account>(accountId);
}
if (account == null)
throw new KeyNotFoundException($"Could not find Account with ID: {accountId}");
return account;
}
catch
{
throw;
}
}
What I do not understand is, the controller returns OK status and all of my fields are populated. However, the API hangs and does not return my data, in other words, the Swagger API (including front-end application) does not receive the response and keeps on showing the loading button.
I have a funny feeling it has something to do with Serialization, but not sure how to fix it.
I have made sure to turn off SelfRefenceLooping, as can be seen here:
services.AddControllers().AddNewtonsoftJson(setup =>
{
setup.SerializerSettings.ContractResolver = new DefaultContractResolver();
setup.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});
Why is the API not returning the JSON object?
Can you try without the .ConfigureAwait(false)?
Except for that, you code seems ok and the API should work fine.
If you don't have it, I would recommend adding Swagger to your API, it's just a matter of 5-10 lines and it helps a lot in the development phase (and also avoid manual mistakes while testing). Here is the official documentation: ASP.NET Core web API help pages with Swagger / OpenAPI
You can also try to add a very dumb action in your controller, to try to identify where the issue comes from (Controller layer? Service layer? Facade layer?)

response.success() is not a function

I have installed parse-server-example and I have uploaded my cloud code. I have a function there but I got error response.success is no function.
Parse.Cloud.define("submitWeeklyScore", function (request, response) {
const gameScore = new Parse.Object("WeeklyGameScore");
gameScore.set("id", request.params.id);
gameScore.set("score", request.params.score);
gameScore.set("name", request.params.name);
gameScore.set("family", request.params.family);
gameScore.set("username", request.params.username);
gameScore.save(null, {useMasterKey: true}).then((saveResult) => {
var playerScore = saveResult.get("score");
var playerCreatedAt = saveResult.createdAt;
var objectId = saveResult.id;
var mainQuery = new Parse.Query("WeeklyGameScore");
mainQuery.greaterThanOrEqualTo("score", playerScore);
mainQuery.lessThan("createdAt", playerCreatedAt);
mainQuery.count({useMasterKey: true}).then((count) => {
var obj = {rank: count + 1, objId: objectId};
response.success(obj);
}, (error) => {
response.error(error);
});
}, (error) => {
response.error(error);
});
});
if I replace response.success(obj); with return obj; I get this :
info: Ran cloud function submitWeeklyScore for user undefined with:
Input: {"score":1337,"rubikaId":11111,"name":"","family":"","username":""}
Result: undefined {"functionName":"submitWeeklyScore","params": {"score":1337,"rubikaId":11111,"name":"","family":"","username":""}}
The object would be save without any problem but there is no result.
Parse Server example installs the latest version of parse server. Version 3.0.0 of Parse Server removed response.success(). Please see the migration guide for details on updating your cloud code.

Question for RawRabbit: sends various messages autonomously

I didn't understand, I have a client that sends various messages autonomously, it doesn't wait for the ack but it has to send them and that's it, but seems that it send only the first one and all the others only when I close the application.
where am I wrong? what should i set?.
var config = new RawRabbitConfiguration()
{
Username = username,
Password = password,
VirtualHost = "/",
Hostnames = new List<string>() { hostname },
AutoCloseConnection = false,
//Ssl = new SslOption() { Enabled = true },
Port = port,
Exchange = new GeneralExchangeConfiguration
{
AutoDelete = false,
Durable = true,
Type = RawRabbit.Configuration.Exchange.ExchangeType.Direct
},
Queue = new GeneralQueueConfiguration
{
Exclusive = false,
AutoDelete = false,
Durable = true
}
};
var options = new RawRabbitOptions() { ClientConfiguration = config };
client = RawRabbitFactory.CreateSingleton(options);
client.SubscribeAsync<MessageModel>(async msg =>
{
return await Task.Run(() => MessageReceived(msg));
},
ctx => ctx.UseSubscribeConfiguration(
cfg => cfg.FromDeclaredQueue(
queue => queue.WithName(queueName))))
.GetAwaiter();
UPDATE: function for sending that I use...
public void SendMessage(MessageModel message, string machineName = null, string exchangeName = null)
{
if (!string.IsNullOrEmpty(machineName))
message.MachineName = machineName;
else if (string.IsNullOrEmpty(message.MachineName))
message.MachineName = this.MachineName;
if (!string.IsNullOrEmpty(LastMessageReceived?.ID))
message.RequestID = LastMessageReceived.ID;
else
message.RequestID = string.Empty;
if (!string.IsNullOrEmpty(LastMessageReceived?.MachineName))
message.MachineNameDest = LastMessageReceived.MachineName;
else if (string.IsNullOrEmpty(message.MachineNameDest))
message.MachineNameDest = string.Empty;
try
{
if (string.IsNullOrEmpty(exchangeName))
client.PublishAsync<MessageModel>(message);
else
client.PublishAsync<MessageModel>(message,
ctx => ctx.UsePublishConfiguration(
cfg => cfg.OnExchange(exchangeName)));
}
catch (Exception ex)
{
OnError?.Invoke(this, ex);
}
LastMessageReceived = null;
}
EDIT:
In what case is the error "Stage Initialized has no additional middlewares registered" generated ?
I cannot understand why this error is generated on "SubscribeAsync" and after does not send messages. :(
Please, help me.

Downloading Excel file via aurelia-http-client

I am working on a task, in which I have to download a report in xlsx format. The report file is generated successfully from server, and is received on client side (aurelia-http-client) as well but I don't know how to go further with downloading.
I would do something like in this answer https://stackoverflow.com/a/30270714/6677648
... that would end up in something like a response interceptor in Aurelia like this:
.withResponseType('blob')
.withInterceptor({
response(message) {
var defaultFileName = "default.txt";
var disposition = message.headers.headers['content-disposition']?message.headers.headers['content-disposition']:message.headers.headers['Content-Disposition'];
if (disposition) {
var match = disposition.match(/.*filename=\"?([^;\"]+)\"?.*/);
if (match[1])
defaultFileName = match[1];
}
defaultFileName = defaultFileName.replace(/[<>:"\/\\|?*]+/g, '_');
if (navigator.msSaveBlob)
return navigator.msSaveBlob(message.response, defaultFileName);
var blobUrl = window.URL.createObjectURL(message.response);
var anchor = document.createElement('a');
anchor.download = defaultFileName;
anchor.href = blobUrl;
document.body.appendChild(anchor);
anchor.click();
document.body.removeChild(anchor);
}
})
I used the downloadjs library. Install the library, add it to your aurelia.json and then add
import * as download from 'downloadjs'
Then write your code as follows:
this.httpClient.fetch('your/url/here')
.then((response: Response) => response.blob())
.then((blob: Blob) => download(blob, 'filename.extension', 'mime type of the file'));
And voila, your file will be downloaded.
Helo with .withInterceptor() was generated errors in the response, change it to fix the error in no responce and unload multiple files simultaneously.
getLogsCsv(param) {
this.http.configure(config => {
config
.withResponseType('blob');
});
return this.http.get("/admin/api/logs" + param)
.then(response => {
if (response.statusCode == 200) {
var defaultFileName = "FileName.csv";
var blobUrl = window.URL.createObjectURL(response.response);
var anchor = document.createElement('a');
anchor.download = defaultFileName;
anchor.href = blobUrl;
document.body.appendChild(anchor);
anchor.click();
document.body.removeChild(anchor);
return response.content;
} else {
console.log('response was not ok.');
console.log(response);
}
})
.catch(error => {
console.log(error);
});
}

Alternative to Application.DoEvents in console application to make Forms.WebBrowser load javascripts

I'm using System.Windows.Forms.WebBrowser in console application to render a web page then invoke scripts on it. To render the web page, I use Application.DoEvents to load and execute scripts.
However sometime the app hangs on calling Application.DoEvents. I found no reason. I don't think I'm creating deadlock on the event loop.
Many people on the web says that one should not use Application.DoEvents at all because it creates more problems than it solves. So I'm thinking there must be an alternative to it. But I've searched a lot and find no alternative to Application.DoEvents.
Does anyone know one?
Any information is appreciated. Thank you in advance!
Thanks to Noseratio's help, I finished drafting my code but still there's freezing issue.
Take following code as example(code is too long so I pasted it on pastebin): http://pastebin.com/DkDcrirU
When you run this code, occasionally there will be at least one window fail to close. And if you attach to the frozen process, you will find the code stuck at following line(indicated by ">>>"):
public static bool NavigateLoadAndRender(WebBrowserContext browserContext, string url, TimeSpan loadTimeout, TimeSpan renderTime, out string errMsg)
{
ForceInitActiveXInstance(browserContext);
object axi = null;
Func<Uri> getBrowserUri = null;
Action<Uri> navigateBrowser = null;
Func<IHTMLDocument2> getBrowserDoc = null;
switch (browserContext.WebBrowserType)
{
case WebBrowserTypeEnum.Forms:
{
var browser = browserContext.GetWebBrowserAsFormsType();
getBrowserUri = () => browser.Url;
navigateBrowser = u =>
{
var finished = false;
browserContext.SyncContext.Post(state =>
{
browser.Navigate(u);
finished = true;
}, null);
while (!finished) Thread.Sleep(DefaultConfig_SyncContextPostCheckInterval);
};
getBrowserDoc = () =>
{
IHTMLDocument2 doc = null;
bool finished = false;
browserContext.SyncContext.Post(state =>
{
doc = (IHTMLDocument2)browser.Document.DomDocument;
finished = true;
}, null);
>>> while (!finished) Thread.Sleep(DefaultConfig_SyncContextPostCheckInterval);
return doc;
};
axi = GetActiveXInstance(browserContext);
}
break;
case WebBrowserTypeEnum.Wpf:
{
var browser = browserContext.GetWebBrowserAsWpfType();
axi = GetActiveXInstance(browser);
getBrowserUri = () => browser.Source;
navigateBrowser = u =>
{
var finished = false;
browserContext.SyncContext.Post(state =>
{
browser.Navigate(u);
finished = true;
}, null);
while (!finished) Thread.Sleep(DefaultConfig_SyncContextPostCheckInterval);
};
getBrowserDoc = () =>
{
IHTMLDocument2 doc = null;
bool finished = false;
browserContext.SyncContext.Post(state =>
{
doc = (IHTMLDocument2)browser.Document;
finished = true;
}, null);
while (!finished) Thread.Sleep(DefaultConfig_SyncContextPostCheckInterval);
return doc;
};
axi = GetActiveXInstance(browserContext);
}
break;
default: throw new ArgumentException("unknown browser type", browserContext.WebBrowserType.ToString());
}
var success = NavigateLoadAndRender(
axi, url,
getBrowserUri,
navigateBrowser,
//() => DoEvents(browser),
getBrowserDoc,
loadTimeout, renderTime, out errMsg);
return success;
}
Anyone knows what's happening?