I am unable to run the chat application using singalr and I am facing problem with owin.
The following errors occurred while attempting to load the app:
No assembly found containing an OwinStartupAttribute.
No 'Configuration' method was found in class 'Microsoft.VisualStudio.Web.PageInspector.Runtime.Startup, Microsoft.VisualStudio.Web.PageInspector.Runtime, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.
To disable OWIN startup discovery, add the appSetting owin:AutomaticAppStartup with a value of "false" in your web.config.
To specify the OWIN startup Assembly, Class, or Method, add the appSetting owin:AppStartup with the fully qualified startup class or configuration method name in your web.config.
Sounds like you're mixing 1.0 and 2.0 components in your project. See the following tutorial for how to upgrade a 1.0 project to 2.0:
http://www.asp.net/signalr/overview/signalr-20/getting-started-with-signalr-20/upgrading-signalr-1x-projects-to-20
Do you have the Startup.cs in your project? More code please.
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
In addition have you setup any hubs?
public class ChatBoxHub : Hub
{
public ChatBoxHub()
{
}
}
Related
I have a .net framework 4.7 project which is essentially an HTTPmodule to be used independantly in IIS server to detect incoming requests and responses, to 3rd party applications installed in IIS,which then need to be modified.
We were adding the module using the webconfig for the respective applications.However now i am migrating it to .net core 6.we use a sample web api to test the httpmodule project.However it seems the addition has to be in startup.cs of the sample web app.
Issue:-
1.I add a middlware to the 1st project like below
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;
namespace Myspace.HttpModule.Example
{
// You may need to install the Microsoft.AspNetCore.Http.Abstractions package into your project
public class MyMiddleware
{
private readonly RequestDelegate _next;
public MyMiddleware(RequestDelegate next)
{
_next = next;
}
public Task Invoke(HttpContext httpContext)
{
return _next(httpContext);
}
}
// Extension method used to add the middleware to the HTTP request pipeline.
public static class MyMiddlewareExtensions
{
public static IApplicationBuilder UseMyMiddleware(this IApplicationBuilder builder)
{
return builder.UseMiddleware<MyMiddleware>();
}
}
}
2.Now i need to add this to the 2nd project which is the sample web app to test the HTTPModule.However when i try to add it to the startup.cs file that i created in the sample web app project
using Myspace.HttpModule.Example;
using System.Globalization;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseAuthorization();
app.UseMiddleware<MyMiddleware>();
app.UseMyMiddleware();
app.MapControllers();
app.Run();
I get compilation errors at
app.UseMiddleware<MyMiddleware>();
app.UseMyMiddleware();
So is it that i cant add like this.Wouldnt "using" work in this case?
Also is this the only way to add a middleware to be able to get requests globally or from the specific sample or 3rd party app?
I googled a lot but couldn't find piece together a definite answer. I am a newbie to .Net
The error is like below
Update:-
The error image is
your screenshot is pointing to a spelling mistake. its UseMiddleware not Middelware as it can be seen in your screenshot.
please check if you are using correct name.
and also you only need to use either
app.UseMiddleware<MyMiddleware>();
or
app.UseMyMiddleware();
not both.
the method should be included in
namespace Microsoft.AspNetCore.Builder
assembly:Microsoft.AspNetCore.Http.Abstractions.dll
which was included in Microsoft.AspNetCore.app in your project when you created the project :
please check the framewok if there's something wrong with it
I am a newbie in .Net Core,
I am always using .Net Framework to develop an application (Web App / Web API).
I have develop my custom Framework and it already established. my custom framework use Entity Framework 6.0 (DB First)
Now, I have assigned to develop Web Api in .Net Core. but still use my custom framework to process the data.
on .net core web api I need to assign connection string like web api on .net standard
In .Net Standard my Connection string like below
<connectionStrings>
<add name="CompanyEntities"
connectionString="metadata=res://*/CompanyModel.csdl|res://*/CompanyModel.ssdl|res://*/CompanyModel.msl;provider=System.Data.SqlClient;provider connection string="data source=127.0.0.10;initial catalog=XYZ;persist security info=True;user id=sa;password=zzzxxx123!;multipleactiveresultsets=True;application name=EntityFramework""
providerName="System.Data.EntityClient"/>
for application using .Net Standard Framework (WebApp/ WebApi)... there is no Issue with this. it runs normally
but I don't know, how I can set connection string on .Net Core? please help
I have tried connection string like this but failed
"ConnectionStrings": {
"CompanyEntities": "Data Source=127.0.0.10;Database=xyz;uid=sa;pwd=zzzxxx123!;MultipleActiveResultSets=true;Integrated Security=False"
}
this is the error :
Severity Code Description Project File Line Suppression State
Error CS0311 The type 'Classes.Model.Data.Library.CompanyEntities' cannot be used as type parameter 'TContext' in the generic type or method 'EntityFrameworkServiceCollectionExtensions.AddDbContext(IServiceCollection, Action, ServiceLifetime, ServiceLifetime)'. There is no implicit reference conversion from 'Clasess.Model.Data.Library.CompanyEntities' to 'Microsoft.EntityFrameworkCore.DbContext'.
and this my dbcontext
public partial class CompanyEntities : DbContext
{
public CompanyEntities()
: base("name=CompanyEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
Try this:
"ConnectionStrings": {
"CompanyEntities": "Server=yourServerName; Database=xyz;Trusted_Connection=True;"
},
Note that you need to install the NuGet package for the database provider you want to access.
For example, if you want to use the MS SQL Server database you need to install Microsoft.EntityFrameworkCore.SqlServer NuGet package.
You also need to install NuGet package for EF tools Microsoft.EntityFrameworkCore.Tools
Make sure to add this to your startup.cs:
services.AddDbContext<YourContext>(options => options.UseSqlServer
(Configuration.GetConnectionString("CompanyEntities")));
Modify your dbcontext as follows:
public partial class CompanyEntities : DbContext
{
public CompanyEntities()
{
}
public CompanyEntities(DbContextOptions<CompanyEntities> options)
: base(options)
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
Have a look at this tutorial on EF Core
If you want to use EF 6 (not core) in.NET core, this may be useful but personally I didn't use this before.
Try this exact below code in your DBContext class:-
public class CompanyEntities : DbContext
{
public CompanyEntities (DbContextOptions<CompanyEntities> options)
: base(options)
{ }
...
}
Hope now it will resolve your issue.
Background:
We are in the process of migrating .Net application to .Net Core.
As a strategy, we would like to keep the existing functionality intact on Full framework while migrating portion of the application to .Net Core. Full application would support .services over Net remoting and REST API whereas .Net core application will only support REST API services.
We have decided to keep the same code base for entire application and support compilation on multiple platforms (NetcoreApp2.1 and Net472).
There is a single application configuration file. Most of the components are dependent on the information stored in this file. Thus we would like to retain the single configuration file for both platforms.
I used System.Configuration.ConfigurationManager package to access configuration information.
Issue:
ConfigurationManager.GetSection(string) throws exception on .Net core platform whereas it works fine on Net472.
Error Message: Configuration system failed to initialize ---> System.Configuration.ConfigurationErrorsException: Unrecognized configuration section system.runtime.remoting
Work around tried so far:
ConfigurationManager.OpenExeConfiguration(configurationUserLevel).GetSection(string) works perfect on both the platforms for fetching the same section
Sample Code:
static MyConfigurationSection myConfigurationSettings { get; set; }
static void Main(string[] args)
{
LoadSettings();
}
private static void LoadSettings()
{
try
{
//Net472 : Works
//NetCoreApp2.1: Throws exception
myConfigurationSettings = ConfigurationManager.GetSection("myCustomSettings") as MyConfigurationSection;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
//Works on both platform
myConfigurationSettings = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal).GetSection("myCustomSettings") as MyConfigurationSection;
Console.WriteLine(myConfigurationSettings.Applications.Count);
Console.ReadLine();
}
Here is configuration file
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="myCustomSettings" type="TestConfigManager.MyConfigurationSection, TestConfigManager" />
</configSections>
<myCustomSettings>
<applications/>
</myCustomSettings>
<system.runtime.remoting>
<application>
<channels>
<channel ref="tcp" port="1111" />
</channels>
</application>
</system.runtime.remoting>
</configuration>
Unfortunately, accessing configuration works slightly differently in the Core Framework (and also .NET 5 and 6). Even with the help of the links below, it took me some time to find it out.
This is how it worked for me:
As preparation, go to NUGET package manager and import
Microsoft.Extensions.Configation,
Microsoft.Extensions.Configation.Json,
Microsoft.Extensions.Configation.Xml
and (optional) Microsoft.Windows.Compatibility
Depending on the type of config file, access it as follows:
App.Config
Example:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="myKey" value="myValue"/>
</appSettings>
</configuration>
Declare
public static AppSettingsSection AppConfig { get; private set; } = null;
Initialize it via
AppConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
.AppSettings;
Read any keys via:
var myValue = AppConfig.Settings["myKey"].Value;
appconfig.json
Example:
{
"AppSettings": {
"myKey": "myValue"
}
}
Declare
public static IConfigurationSection JsonConfig { get; private set; } = null;
Initialize it via
JsonConfig = new ConfigurationBuilder().AddJsonFile("appconfig.json",
optional: true, reloadOnChange: true).Build().GetSection("AppSettings");
Read any keys via:
var myValue = JsonConfig["myKey"];
Helpful links:
cant read app config in c-sharp
how to read appsettings values from json
Comparision between appSettings and ApplicationSettings
I have a simple SingulaR example that I've added to a legacy ASP.Net MVC application.
Here are the various parts:
OWIN Startup class
[assembly: OwinStartup(typeof (Startup))]
namespace MyApp.Web
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
}
SignalR Hub
using System.Collections.Generic;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
namespace MyApp.Web
{
[HubName("podService")]
public class PodServiceHub : Hub
{
public PodServiceHub()
{
;
}
public IEnumerable<string> GetMessages()
{
return new[] {"blah", "blah", "blah"};
}
}
}
Server-side facade
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
namespace MyApp.Web
{
public class PodService
{
PodService(IHubConnectionContext<dynamic> clients)
{
Clients = clients;
}
public PodService()
: this(GlobalHost.ConnectionManager.GetHubContext<PodServiceHub>().Clients)
{
}
IHubConnectionContext<dynamic> Clients { get; set; }
public void SendMessageToClient(string message)
{
Clients.All.doSomething(message);
}
}
}
Portions of startup Javascript:
var podService = $.connection.podService;
...
$.extend(podService.client, {
doSomething: function(message) {
console.log("received message:" + message);
}
});
// test
$.connection.hub.start()
.done(function() {
podService.server.getMessages()
.done(function(messages) {
console.log("received message:" + message);
});
});
Within one of the controllers called by the first page:
_podService.SendMessageToClient("Hello from the server!");
Upon executing the application, the following error is displayed in the console of Chrome's dev tools:
WebSocket connection to 'ws://localhost:62025/signalr/connect?transport=webSockets&clientProtocol=1.5&connectionToken=02LJFqBcRBWKXAOlaSwgMPWG0epV7AFl19gNjFCvA0dxD2QH8%2BC9V028Ehu8fYAFN%2FthPv65JZKfK2MgCEdihCJ0A2dMyENOcdPkhDzEwNB2WQ1X4QXe1fiZAyMbkZ1b&connectionData=%5B%7B%22name%22%3A%22podservice%22%7D%5D&tid=6' failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET
After this error, however, the podService.server.getMessages() returns with the message from the server printing ["blah", "blah", "blah"] to the console and subsequently the doSomething client function is invoked printing "received message: Hello from the server!".
The calls from both the client and the server are transmitting data, so this error doesn't appear to be breaking the app. It definitely seems to be an issue though. The code above was based upon the sample code generated by the Microsoft.AspNet.SignalR.Sample NuGet package which doesn't display the same behavior. The only difference I'm aware of between my example and NuGet-based sample is that I've added this to a legacy MVC app vs. a pure OWIN-based app. Based upon a comment I read on this SO question this shouldn't be an issue.
So, what's wrong with this example usage and/or what could be causing the connection reset?
I made sure:
the web socket component is enabled in IIS
and the "allowKeepAlive" setting is not set to false in my web.config
But in my case the problem was caused by a packages version mismatch:
In the packages.config Microsoft.Owin.Host.SystemWeb version 2.1.0 was referenced accidentally
<package id="Microsoft.Owin.Host.SystemWeb" version="2.1.0" targetFramework="net452" />
While all the other Owin related packages were referencing version 3.0.1
I updated Microsoft.Owin.Host.SystemWeb to version 3.0.1
Then I had to make sure in the web.config file the "httpRuntime" element targeted the framework version 4.5
<system.web>
<httpRuntime targetFramework="4.5" />
</system.web>
The two steps above solved the problem.
Just ran in to this one myself. In my case the answer seems to be enabling WebSockets for IIS.
Enable WebSockets in IIS 8.0
It works because signalR falls back to one of the following depending on the capabilities of the browser and server.
Server Sent Events.
Forever Frame
AJAX Long Polling
For more information on the transports used and their fallbacks see here
In my case, I had to remove
<httpProtocol allowKeepAlive="false" />
from our web.config (it was there for historical reasons).
In my Case I was using
string sqlConnectionString = ConfigurationManager.ConnectionStrings["GAFI_SignalR"].ConnectionString;
GlobalHost.DependencyResolver.UseSqlServer(sqlConnectionString);
The problem was accessing the database when the user didin't have permission to connect to the database.
I'm developing a plugin like application for a web site. Due to requirements it will live in the same physical path and the same application pool as the main web site which I do not have the source code for. So they both share the same Web.config and some other dependencies.
I need to set a license for a third party dependency at application start, but I have no way of accessing the code behind for Global.asax as that code is owned by a different company.
So, is there an alternate way of appending events to Application Start without involving Global.asax or is my only solution to inherit/extend the current Global.asax?
You can use a HTTPModule:
public class MyModule : IHttpModule
{
#region IHttpModule Members
public void Dispose()
{
}
public void Init(HttpApplication context)
{
...
}
#endregion
}
web.config
<httpModules>
<add name="MyModule" type="MyNamespace.MyModule, MyAssembly" />
</httpModules>
You can use WebActivator if you know your target projects will all be .NET 4.0 or greater.
https://github.com/davidebbo/WebActivator
[assembly: WebActivatorEx.PostApplicationStartMethod(typeof(Bootstrapper), "Start")]
public class Bootstrapper
{
public static void Start()
{
// Put everything in motion here
}
}
Note you also have the option of running before or after the Global.asax Application_Start() function - this example runs afterward.