No Definition for Plugin in XSockets.net - asp.net-mvc

I am working on a RTC Project in ASP.net and using XSockets.net for signalling purpose in VS 2013. But as I install XSockets.net 4.1.0 and try to create Xsockets.Net.BootStrapper class under App_Start folder it comes up with an error that Project doesn't contain definition for Plugin.
BootStrapper.cs:
using System.Web;
using XSockets.Core.Common.Socket;
[assembly: PreApplicationStartMethod(typeof(RTC.App_Start.XSockets), "Start")]
namespace RTC.App_Start
{
public static class XSockets
{
private static IXSocketServerContainer container;
public static void Start()
{
container = XSockets.Plugin.Framework.Composable.GetExport<IXSocketServerContainer>();
container.Start();
}
}
}

Use this instead of yours
using System.Web;
using XSockets.Core.Common.Socket;
[assembly: PreApplicationStartMethod(typeof(XSockets.WebRTC.App_Start.XSocketsWebBootstrapper), "Start")]
namespace XSockets.WebRTC.App_Start
{
public static class XSocketsWebBootstrapper
{
private static IXSocketServerContainer container;
public static void Start()
{
container = XSockets.Plugin.Framework.Composable.GetExport<IXSocketServerContainer>();
container.Start();
}
}
}

Related

Calling SignalR functions outside of Hub Class

I am are trying to get an instance of a Hub Class to call front-end methods from the backend from a class outside of the Hub class.
I am using IHostLifeTime that has a register function that will be running in the background while the server is running in a while loop.
There will be events in the while loop that will trigger signalR to send a message to the client.
Question: How am I supposed to get access to the hub and send a message to the client inside of my manager class in the ApplicationReady() function?
TestHub.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
namespace SignalREventHandle
{
public class TestHub : Hub
{
public async Task SendMessage(string user, string message)
{
Console.WriteLine($"user: {user} message:{message}");
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
}
}
Startup.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR;
using System.Threading;
namespace SignalREventHandle
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
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.AddRazorPages();
services.AddSignalR();
}
// This method gets called by the runtime. Use this method to configure the HTTP request //pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime lifetime, IHubContext<TestHub> hubContext)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
}
lifetime.ApplicationStarted.Register(OnAppStarted);
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapHub<TestHub>("/testHub");
});
}
public async void OnAppStarted()
{
//Get Singleton Instance of Manager and then start the application
var manager = Manager.Instance;
manager.ApplicationReady();
}
}
}
Manager.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR;
namespace SignalREventHandle
{
public class Manager
{
private bool _isServerRunning;
/// <summary>
/// Instance of class to implement Singleton
/// </summary>
private static readonly Manager _instance = new();
/// <summary>
/// Getter for Class instance
/// </summary>
public static Manager Instance
{
get => _instance;
}
public async void ApplicationReady()
{
var task = Task.Run(() =>
{
_isServerRunning = true;
while (_isServerRunning)
{
// Want to Send Message to Client with SignalR here
Thread.Sleep(10000);
}
});
}
}
}
In ASP.NET 4.x SignalR use GlobalHost to provide access to the IHubContext:
public static async Task SendMessage(string user, string message)
{
Console.WriteLine($"user: {user} message: {message}");
// Get an instance of IHubContext from GlobalHost
var hubContext = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
await hubContext.Clients.All.SendAsync("ReceiveMessage", user, message);
}
In ASP.NET Core SignalR, you can access an instance of IHubContext from the web host.
Program.cs
public class Program
{
public static IHost WebHost;
public static void Main(string[] args)
{
WebHost = CreateHostBuilder(args).Build();
WebHost.Run();
}
...
}
Then:
public static async Task SendMessage(string user, string message)
{
Console.WriteLine($"user: {user} message: {message}");
// Get an instance of IHubContext from IHost
var hubContext = Program.WebHost.Services.GetService(typeof(IHubContext<ChatHub>)) as IHubContext<ChatHub>;
await hubContext.Clients.All.SendAsync("ReceiveMessage", user, message);
}
Documentation:
https://learn.microsoft.com/en-us/aspnet/core/signalr/hubcontext?view=aspnetcore-5.0
signalr how i can i post a message from server to caller

How to simply execute stored procedure in blazor server app?

I am building a Blazor server app using a repository pattern and am trying to execute a stored procedure from a Razor component page.
However I am getting an error when I run it:
blazor.server.js:21 [2021-03-29T02:03:38.207Z] Error: System.InvalidOperationException: Cannot provide a value for property 'ICalculateImportanceService' on type 'ThePositionerBlazorServerDapperSyncfusion.Pages.DBProcessing.CalculateItemImportance'. There is no registered service of type 'ThePositionerBlazorServerDapperSyncfusion.Data.CalculateImportanceService'.
Not sure why I am getting the error because I believe I registered the service.
Here is the relevant code:
CalculateItemImportance.razor
#using ThePositionerBlazorServerDapperSyncfusion.Data
#page "/DBProcessing/calcultateitemImportance"
#inject CalculateImportanceService ICalculateImportanceService
#inject NavigationManager NavigationManager
<h1 style="text-align:center">#pagetitle</h1>
#code {
public string pagetitle = "Calculate Importance";
protected override async Task OnInitializedAsync()
{
// Kick off stored procedure to calculate importance
await ICalculateImportanceService.CalculateImportance();
}
}
ICalculateImportanceService.cs
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using ThePositionerBlazorServerDapperSyncfusion.Data;
namespace ThePositionerBlazorServerDapperSyncfusion.Data
{
public interface ICalculateImportanceService
{
Task<bool> CalculateImportance();
}
}
CalculateImportanceService.cs
using Dapper;
using Microsoft.Data.SqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Threading.Tasks;
namespace ThePositionerBlazorServerDapperSyncfusion.Data
{
public class CalculateImportanceService : ICalculateImportanceService
{
private readonly SqlConnectionConfiguration _configuration;
public CalculateImportanceService(SqlConnectionConfiguration configuration)
{
_configuration = configuration;
}
public async Task<bool> CalculateImportance()
{
using (var conn = new SqlConnection(_configuration.Value))
{
await conn.ExecuteAsync("CalculateTheItemImportance", commandType: CommandType.StoredProcedure);
}
return true;
}
}
}
Startup.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ThePositionerBlazorServerDapperSyncfusion.Data;
using Syncfusion.Blazor;
namespace ThePositionerBlazorServerDapperSyncfusion
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddServerSideBlazor();
//services.AddSingleton<WeatherForecastService>();
//Syncfusion support
services.AddSyncfusionBlazor();
services.AddControllers().AddNewtonsoftJson();
var sqlConnectionConfiguration = new SqlConnectionConfiguration(Configuration.GetConnectionString("SqlDBContext"));
services.AddSingleton(sqlConnectionConfiguration);
services.AddScoped<IApplicConfsService, ApplicConfsService>();
services.AddScoped<IPOSSUMMARYService, POSSUMMARYService>();
services.AddScoped<IPOSDETAILService, POSDETAILService>();
services.AddScoped<IDESCRIPTIONTYPEService, DESCRIPTIONTYPEService>();
services.AddScoped<IIMPService, IMPService>();
services.AddScoped<IITEMCATEGORYService, ITEMCATEGORYService>();
services.AddScoped<IKNOWDEPService, KNOWDEPService>();
services.AddScoped<IMembersService, MembersService>();
services.AddScoped<IPRDSRVService, PRDSRVService>();
services.AddScoped<IPROCESSESService, PROCESSESService>();
services.AddScoped<ITASKKNOService, TASKKNOService>();
services.AddScoped<ITMPOVERLAPService, TMPOVERLAPService>();
services.AddScoped<ITEXTUALService, TEXTUALService>();
services.AddScoped<ITIMESCALEService, TIMESCALEService>();
services.AddScoped<IWORKHIERService, WORKHIERService>();
services.AddScoped<ICalculateImportanceService, CalculateImportanceService>();
services.AddScoped<ICalculateFTEService, CalculateFTEService>();
}
}
}
The stored procedure has no parameters and simply executes processing on the database.
Any help would be appreciated. Thanks
Change
#inject CalculateImportanceService ICalculateImportanceService
to
#inject ICalculateImportanceService CalculateImportanceService
and further down
// await ICalculateImportanceService.CalculateImportance();
await CalculateImportanceService.CalculateImportance();

Appsettings and middleware Core 2.1

I have made a custom middleware and now I want to access the appsettings that are in another project in my solution. Should I inject the IConfiguration object into the middleware constructor, and add the using statement of Microsoft.Extensions.Configuration? Or is there a better way to do this?
I am working with ASP.net Web page with Core 2.1.
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using System;
using System.Threading.Tasks;
public class MyMiddleware
{
public IConfiguration _configuration;
public MyMiddleware(RequestDelegate next, IConfiguration config)
{
_next = next;
_ configuration = config;
}
If you don't need all your configuration passed to your middleware but just a section you can use
IOptions<T>
Create MyConfig.cs Class file:
public class MyConfig
{
public string MyConfig1 {get; set;}
public string MyConfig2 {get; set;}
}
In ConfigureServices method in Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.Configure<MyConfig>(Configuration.GetSection("MyConfig"));
}
In your middleware
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using System;
using System.Threading.Tasks;
public class MyMiddleware
{
private readonly IOptions<MyConfig> _appSettings;
public MyMiddleware(RequestDelegate next, IOptions<MyConfig> config)
{
_next = next;
_configuration = config;
}
public MyMethod()
{
_configuration.Value.MyConfig1
}
}
In appsettings.json file:
{
"AppSettings": {
"AppId": "0001",
"AppName": "xxxx",
},
"MyConfig": {
"MyConfig1": "xxxxxxx",
"MyConfig2": "xxxxxxx",
},
}

ASPNETCORE ConfigureServices does not run

I follow the Microsoft document to implement the policy-based authorization in my web service but the function "ConfigureServices" does not run. Please let me know if I have something missing.
Startup.cs
using Microsoft.Owin;
using Owin;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.DependencyInjection;
[assembly: OwinStartupAttribute(typeof(WebApplication1.Startup))]
namespace WebApplication1
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
public void ConfigureServices(IServiceCollection services)
{
//Some codes here...
}
}
}

No Parameterless constructor defined for this object...With a twist?

I'm building an MVC4 app using EF5 and ninject. Something broke when I upgraded from MVC3 to 4. So I created a brand new solution, got all my nuget packages, added all my references, then copied in my code.
Project builds, thats fabulous.
My problem is the (Ninjection) sp? doesn't seem to be wiring up correctly. I get the "No Parameterless constructor defined for this object" as a runtime error when I try to load the page. However, if I simply add an empty public parameterless constructor, the page renders and all is right with the world.
My App_Start Code runs fine, NinjectWebCommon.cs (included at the bottom of the question) I've stepped through the code, but other that copying and pasting, and following tutorials online. I don't understand IoC well enough to know what to do next.
namespace search.Controllers
{
public class HomeController : Controller
{
ICamaService _service = null;
[Inject]
public HomeController(ICamaService service)
{
_service = service;
}
************** ADDING THIS FIXES THE RUNTIME ERROR *********
public HomeController(){
;
}
***********
//TODO: ADD ACTIONS
public ViewResult Index()
{
return View();
}
}
}
Here is my composition root:
[assembly: WebActivator.PreApplicationStartMethod(typeof(search4.App_Start.NinjectWebCommon), "Start")]
[assembly: WebActivator.ApplicationShutdownMethodAttribute(typeof(search4.App_Start.NinjectWebCommon), "Stop")]
namespace search4.App_Start
{
using System;
using System.Web;
using Microsoft.Web.Infrastructure.DynamicModuleHelper;
using Ninject;
using Ninject.Web.Common;
using search.Services;
using search.Data;
public static class NinjectWebCommon
{
private static readonly Bootstrapper bootstrapper = new Bootstrapper();
public static void Start()
{
DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
bootstrapper.Initialize(CreateKernel);
}
public static void Stop()
{
bootstrapper.ShutDown();
}
private static IKernel CreateKernel()
{
var kernel = new StandardKernel();
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
RegisterServices(kernel);
return kernel;
}
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<ICamaContext>().To<CamaContext>().InRequestScope();
kernel.Bind<ICamaService>().To<CamaService>().InRequestScope();
}
}
}
![Screen Capture of Exception][1]
http://shareimage.ro/viewer.php?file=svs5kwamqy0pxbyntig4.gif
I am not a Ninject user, but from my experiences with other IOC frameworks in MVC, you would need to replace the DefaultControllerFactory with an implementation that injects objects instead of requiring a default constructor.
Looks like your bindings arn't being registered propertly.
Im not sure exactly what's wrong, but I create a NinjectApplicationModule that works for me:
/// <summary>
/// Load your modules or register your services here!
/// </summary>
/// <param name="kernel">The kernel.</param>
private static void RegisterServices(IKernel kernel)
{
kernel.Load(new NinjectApplicationModules());
}
public class NinjectApplicationModules : NinjectModule
{
/// <summary>
/// Loads the Binding module into the kernel. Used to map Abstract Classes to Concrete classes at runtime.
/// </summary>
public override void Load()
{
// Bindings...
Bind<ICamaContext>().To<CamaContext>().InRequestScope();
Bind<ICamaService>().To<CamaService>().InRequestScope();
}
}
Check you data model class.
Public Class A ()
{
public A() {
}
public string Name{get; set;}
}
But you need to remove this default Class A Constructor.
Public Class A ()
{
public string Name{get; set;}
}
I was already facing No Parameter less constructor defined for this object

Resources