I am using signalR 1.0.0 rc2 and have the code as following:
using System.Web;
using System.Threading.Tasks;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
[HubName("chat")]
public class Chat : Hub
{
public Chat()
{
}
[HubMethodName("send")]
public void Send(string message,string connectionId)
{
Clients.All(message);
}
}
and i have the client side js :
$(function () {
var myHub= $.connection.chat;
}
here i get the chat undefined.
i looked at the signalr/hubs and found
$.extend(signalR, {
//here should have extended hub methods but has nothing
});
what is the problem here is the hub not being initilized .I haven't included
RouteTable.Routes.MapHubs() in global.asax.cs (is it necessary to include this line?) . also when i include this line i get an error :
Method not found: 'Void Microsoft.AspNet.SignalR.DependencyResolverExtensions.InitializePerformanceCoun>ters(Microsoft.AspNet.SignalR.IDependencyResolver, System.String,System.Threading.CancellationToken)'.
thanks .
Related
I'm trying to build my first NserviceBus application, but I cannot get it to work. The message arrives on the "backend" but the handler uses DI and NServicebus claims it cannot find the service for the interface. But the code was lifted directly from the examples. I'm missing something and I cannot figure it out.
The Error:
dbug: NServiceBus.LoadHandlersConnector[0]
Processing message type: Messages.JobStartCommand
Message headers:
NServiceBus.MessageId : 0044f261-e3b3-4287-b6f0-ad7400ef43cb
NServiceBus.MessageIntent : Send
NServiceBus.ConversationId : bb4f276f-63fe-450b-b234-ad7400ef43cd
NServiceBus.CorrelationId : 0044f261-e3b3-4287-b6f0-ad7400ef43cb
NServiceBus.ReplyToAddress : ClientUI
NServiceBus.OriginatingMachine : L19002992
NServiceBus.OriginatingEndpoint : ClientUI
$.diagnostics.originating.hostid : e1fecb2b72b8185e47341bb4dfb37dd7
NServiceBus.ContentType : text/xml
NServiceBus.EnclosedMessageTypes : Messages.JobStartCommand, Messages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
NServiceBus.Version : 7.5.0
NServiceBus.TimeSent : 2021-07-29 14:31:08:228497 Z
NServiceBus.Retries : 3
NServiceBus.Retries.Timestamp : 2021-07-29 14:31:40:397277 Z
Handlers to invoke:
Extractor.JobStartHandler
Extractor.JobStartHandler
info: NServiceBus.RecoverabilityExecutor[0]
Immediate Retry is going to retry message '0044f261-e3b3-4287-b6f0-ad7400ef43cb' because of an exception:
System.InvalidOperationException: Unable to resolve service for type 'IExtract' while attempting to activate 'Extractor.JobStartHandler'.
at Microsoft.Extensi
My backend program.cs
using Microsoft.Extensions.Hosting;
using System;
using System.Diagnostics;
using System.Linq;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NServiceBus;
using System.Threading.Tasks;
using Messages;
using Extractor;
namespace ExtractorOsiris
{
class Program
{
static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args)
{
var builder = Host.CreateDefaultBuilder(args);
builder.UseWindowsService();
//builder.UseMicrosoftLogFactoryLogging();
builder.ConfigureLogging((ctx, logging) =>
{
logging.AddConfiguration(ctx.Configuration.GetSection("Logging"));
//logging.AddEventLog();
logging.AddConsole();
logging.SetMinimumLevel(LogLevel.Debug);
});
#region back-end-use-nservicebus
builder.UseNServiceBus(ctx =>
{
var endpointConfiguration = new EndpointConfiguration("Sample.Extractor");
endpointConfiguration.UseTransport<LearningTransport>();
var transport = endpointConfiguration.UseTransport<LearningTransport>();
transport.Routing().RouteToEndpoint(typeof(ProcessObjectCommand), "Sample.Processor");
endpointConfiguration.DefineCriticalErrorAction(OnCriticalError);
return endpointConfiguration;
});
#endregion
#region back-end-register-service
builder.ConfigureServices(services =>
{
services.AddSingleton<IExtract, ExtractOsiris>();
});
#endregion
return builder;
}
private static Task OnCriticalError(ICriticalErrorContext arg)
{
throw new NotImplementedException();
}
}
}
The Interface
using Newtonsoft.Json.Linq;
using NServiceBus;
using System;
using System.Threading.Tasks;
namespace Extractor
{
public interface IExtract
{
Task<JArray> Extract(string #object, DateTime deltaTime);
}
}
The handler
using System.Threading.Tasks;
using Messages;
using Newtonsoft.Json.Linq;
using NServiceBus;
namespace Extractor
{
#region back-end-handler
public class JobStartHandler : IHandleMessages<JobStartCommand>
{
private readonly IExtract extractor;
public JobStartHandler(IExtract extractor)
{
this.extractor = extractor;
}
public async Task Handle(JobStartCommand message, IMessageHandlerContext context)
{
Task<JArray> result = extractor.Extract("Medewerkers", message.DeltaTime);
await result;
JArray test = result.Result;
foreach (JObject x in test)
{
// send the object to be processed.
//await context.Send(new ProcessObjectCommand(x.ToString()));
}
}
}
#endregion
}
The implementation of the interface
using System;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using Extractor;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NServiceBus;
namespace ExtractorOsiris
{
public class ExtractOsiris : IExtract
{
private readonly ILogger logger;
public ExtractOsiris(ILogger<ExtractOsiris> logger)
{
this.logger = logger;
}
public Task<JArray> Extract(string #object, DateTime deltaTime)
{
logger.LogInformation($"getting {#object} for delta time {deltaTime}");
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("https://xx.yy");
WebResponse response = request.GetResponse();
JObject temp = JObject.Load(new JsonTextReader(new StreamReader(response.GetResponseStream())));
return Task<JArray>.FromResult(temp["items"] as JArray);
}
}
}
I know the code ain't pretty, but it's pure quick and dirty testing code.
I cleaned out the offending interface from the code and still got the error on an interface that was not even there anymore. I removed the bin folder and build everything back up step by step. Stupid thing is, source control says I am back where I started, without changes. And it just works....
So must have bin something stupid with VS2019. Sorry to anyone who's time I wasted
I am trying to Xamarin.uiTest to automate an application and I got this error in very initial stage.
System.InvalidOperationException : Sequence contains no elements
Code: AppInitializer.cs
using System;
using System.IO;
using System.Linq;
using Xamarin.UITest;
using Xamarin.UITest.Queries;
namespace MyXamarinApp1_Test1
{
public class AppInitializer
{
public static IApp StartApp(Platform platform)
{
if (platform == Platform.Android)
{
return ConfigureApp
.Android
//.InstalledApp("com.companyname.MyXamarinApp1")
.ApkFile("C:\\Users\\...\\Desktop\\com.companyname.MyXamarinApp1.apk")
.StartApp();
}
return ConfigureApp
.iOS.StartApp();
}
}
}
Code: Test.cs
using System;
using System.IO;
using System.Linq;
using NUnit.Framework;
using Xamarin.UITest;
using Xamarin.UITest.Queries;
namespace UITest1
{
[TestFixture(Platform.Android)]
[TestFixture(Platform.iOS)]
public class Tests
{
IApp app;
Platform platform;
public Tests(Platform platform)
{
this.platform = platform;
}
[SetUp]
public void BeforeEachTest()
{
app = AppInitializer.StartApp(platform);
}
[Test]
public void AppLaunches()
{
app.Screenshot("First screen.");
}
}
Any idea to resolve the issue is appreciated.
I am using the signed app, could it be an issue.
Xamarin version : 2.0.3
Nunit : 2.6.4
try downgrading or upgrading it to Xamarin 2.2.1 or less and try cleaning solution or delete debug folder and build and run the command in fresh command line window, it may fix.. not 100% sure
I am migrating an ASP.NET Web API application to OWIN. That is not intended to use none OWIN deployments. So Global.asax is going to be removed. There are some code put into Global.asax event handlers specially in Application_EndRequest that should be handled by OWIN.
I have read some article about OWIN and searched the internet but couldn't determine how it can be done. Can anyone please describe how it can be done?
My environment:
Visual Studio 2015 RC
.Net Framework 4.5
Microsoft.AspNet.Cors.5.0.0
Microsoft.AspNet.WebApi.5.2.3
Microsoft.Owin.3.0.1
Owin.1.0
UPDATE: Here it is some sections of current code
using System;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using ProjectX.Web.AppStart;
using ProjectY.Domain.Contracts;
namespace ProjectX.UI
{
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_EndRequest(object sender, EventArgs e)
{
var unitOfWork = DependencyResolver.Current.GetService(typeof(IUnitOfWork)) as IUnitOfWork;
unitOfWork.SaveChanges();
}
}
}
namespace ProjectY.Domain.Contracts
{
public interface IUnitOfWork
{
void SaveChanges();
IRepository<T> GetRepository<T>() where T : class, IEntity, IHistory;
IDbContext GetDbContext();
}
}
using ProjectY.Core.Repositories;
using ProjectY.Domain.Contracts;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectY.Core.UnitOfWork
{
public class UnitOfWork : IUnitOfWork
{
public UnitOfWork(IProjectYDbContextFactory contextFactory)
{
_context = contextFactory.GetContext();
}
public void SaveChanges()
{
if (_context == null)
throw new ApplicationException("Something wrong has been happened. _context must not be null.");
_context.SaveChanges();
}
}
}
I stumbled upon this question while updating some legacy applications. For those still seeking the answer: you can solve this by creating a middleware:
app.Use(async (context, next) =>
{
await next.Invoke().ConfigureAwait(false);
//Do stuff after request here!
var unitOfWork = DependencyResolver.Current.GetService(typeof(IUnitOfWork)) as IUnitOfWork;
unitOfWork.SaveChanges();
});
You can use stage markers if you need more control on when your middleware will be called in the request processing pipeline.
See also https://learn.microsoft.com/en-us/aspnet/aspnet/overview/owin-and-katana/owin-middleware-in-the-iis-integrated-pipeline#stage-markers
I have a MVC4 application setup to test SignalR push notification and which is not working. (I have tested the chat application on the MVC official site and its working perfectly, the problem is when i pushing a message from controller). Please someone help me on this.
(1) I have startup cs as follows,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.Owin;
using Owin;
namespace MvcApplication3
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
}
(2) Hub class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
namespace MvcApplication3
{
[HubName("notificationHub")]
public class NotificationHub : Hub
{
}
}
(3) what im doing on controller is,
public ActionResult Index()
{
SendMessage("This should be displayed on client !!");
return View();
}
private void SendMessage(string message)
{
var context = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();
context.Clients.All.viewMessage(message);
}
(4) Finally on the Index view,
<style type="text/css">
#span-display
{
color: red;
font-size: 16px;
}
</style>
<span id="span-display"></span>
#section scripts
{
<script src="~/Scripts/jquery.signalR-2.0.1.min.js"></script>
<script src="~/signalr/hubs"></script>
<script type="text/javascript">
$(function () {
var notificationhub = $.connection.notificationHub;
notificationhub.client.viewMessage = function (message) {
$('#span-display').html(message);
};
$.connection.hub.start();
});
</script>
}
please do help me guys , im on a deadline and couldn't solve this out. Please excuse me if this is a simple thing but im new to this technology.
Thank you in advance :-)
I tested with a code almost equal, and it works, the only diference I found was in the startup class, there I have as well:
[assembly: OwinStartup(typeof(SignalR_Example.Hubs.Startup))]
namespace SignalR_Example.Hubs
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
// Any connection or hub wire up and configuration should go here
app.MapSignalR();
}
}
}
Try using the first line changing my values with your values, other thing important is the JS, have you checked your browser console?, is there any error or something like that?
i just installed the signalr sample (downloaded with nuget)
everything from nuget installed fine and it's a clean project (just to test the sample), yet i get the following error:
throw "SignalR: Connection must be started before data can be sent. Call .start() before .send()";
use package manager
install-package Microsoft.Owin.Host.SystemWeb
and do changes in startup.cs
using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(Microsoft.AspNet.SignalR.StockTicker.Startup), "Configuration")]
namespace Microsoft.AspNet.SignalR.StockTicker
{
public static class Startup
{
public static void Configuration(IAppBuilder app)
{
Microsoft.AspNet.SignalR.StockTicker.Startup.ConfigureSignalR(app);
}
public static void ConfigureSignalR(IAppBuilder app)
{
app.MapSignalR();
}
}
}
Replace code in Startup.cs file with the following code block, that will fix the js error hopefully
using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(Microsoft.AspNet.SignalR.StockTicker.Startup))]
namespace Microsoft.AspNet.SignalR.StockTicker
{
public static class Startup
{
public static void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
}
you have first to call,
$.connection.hub.start
for example :
var myConnection = $.connection.myConnection;
$.connection.hub.start({ transport: 'auto' }, function () {
alert('connected');
});
/// now you can do what ever you want.
myConnection.SendHello('Just Testing');
now when you load open the page, you should see the browser message (connected), to make sure that the signalR has established a connection.
You can find a full working demo with source code at :
Example including VS2010 solution
This worked for me first time.