Do I need to have a Startup.cs on my Frontend? - asp.net

This question is related to this:
The problem I'm having is that I am trying to implement a SignalR with CORS from one ASP.NET (localhost:50000) project called Frontend to another ASP.NET MVC project (in the same solution) (localhost:60000).
When I run the application I get this error message in the console:
The following errors occurred while attempting to load the app.
- No assembly found containing an OwinStartupAttribute.
- No assembly found containing a Startup or [AssemblyName].Startup class. 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.
When I add a OWIN Startup class I don't get this error message:
HTTP Error 404.0 - Not Found The resource you are looking for has been
removed, had its name changed, or is temporarily unavailable.
And I guess it's because it is trying to find the hubs in it's own project.
Question 1:
Do I need a startup on my Frontend?
Question 2 (if Question 1 == yes):
Must I in the Startup map SignalR to my Backend?
EDIT:
index.html:
<!--Script references -->
<link href="Content/bootstrap.min.css" rel="stylesheet">
<script src="Scripts/jquery-1.9.1.min.js"></script>
<script src="Scripts/jquery.signalR-2.2.0.min.js"></script>
<script src="http://localhost:50000/signalr/hubs" type="text/javascript"></script>
<!-- HEAD ^^^ -->
<!-- Deleted stuff -->
<!-- BODY vvv -->
<script type="text/javascript">
$(function () {
var broadcaster = $.connection.loginHub;
console.log("broadcaster: " + broadcaster)
$.connection.hub.start().done(function () {
});
});
</script>
After re-creating my Frontend project and only installing the Microsoft.AspNet.SignalR.JS package I know receive this error in the console:
HTTP Error 404.0 - Not Found .... Requested URL
http://localhost:60000/signalr/negotiate?clientProtocol=1.5&connectionData=%5B%5D&_=1443076975867
http://localhost:60000 is the Frontend so I'm not sure why that is the requested URL.
When checking http://localhost:50000/signalr/hubs I get a website from ASP.NET SignalR JavaScript Library v2.2.0 and also when I print out broadcaster in the console it says broadcaster: [object Object] so some sort of connection seems to be established.

You probably need to set up the client to point to your actual hub location since by default it's the current server.
$.connection.hub.url = '<yourbackendurl>;
Do that before connection.hub.start is called and it should work for you.

In your Backend project you need to install these packages:
PM> Install-Package Microsoft.AspNet.SignalR
PM> Install-Package Microsoft.Owin.Cors
And its Startup class should be like this:
public void Configuration(IAppBuilder app)
{
app.UseCors(CorsOptions.AllowAll);
app.MapSignalR();
}
In your Frontend project you need to install this package:
PM> Install-Package Microsoft.AspNet.SignalR.JS
Also you can install SignalR for .NET client:
PM> Install-Package Microsoft.AspNet.SignalR.Client

Related

InvalidOperationException: Could not find 'UserSecretsIdAttribute' on assembly

After deploying ASP.NET Core app to azure and opening the site, I get the following error:
InvalidOperationException: Could not find 'UserSecretsIdAttribute' on
assembly '******, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=null'.
The exception details also include that the error happens at Startup.cs on this line of code:
builder.AddUserSecrets();
Thank you
There was an update to the user secrets module just recently. Version 1.0.1 and up now requires you specify an assembly-level attribute for the id of the user secrets, or as a fallback, the way it was previously in project.json.
Here is the announcement on GitHub: https://github.com/aspnet/Announcements/issues/209
You can define the secrets id in the .csproj like this:
<PropertyGroup>
<UserSecretsId>aspnet-TestApp-ce345b64-19cf-4972-b34f-d16f2e7976ed</UserSecretsId>
</PropertyGroup>
This generates the following assembly-level attribute. Alternatively, instead of adding it in the .csproj file, you can of course add it yourself e.g. to Startup.cs:
[assembly: UserSecretsId("aspnet-TestApp-ce345b64-19cf-4972-b34f-d16f2e7976ed")]
Also, you should use:
builder.AddUserSecrets<Startup>();
It will search for that attribute in the assembly of the given type, in this case I used the Startup class.
Note: this will be deprecated in 2.0: (1.0.2 and 1.1.1 have marked it obsolete)
builder.AddUserSecrets();
I checked the source code for the user secrets configuration, and calling AddUserSecrets() without the type does this:
var attribute = entryAssembly.GetCustomAttribute<UserSecretsIdAttribute>();
if (attribute != null)
{
return AddUserSecrets(configuration, attribute.UserSecretsId);
}
// try fallback to project.json for legacy support
try
{
var fileProvider = configuration.GetFileProvider();
return AddSecretsFile(configuration, PathHelper.GetSecretsPath(fileProvider));
}
catch
{ }
// Show the error about missing UserSecretIdAttribute instead an error about missing
// project.json as PJ is going away.
throw MissingAttributeException(entryAssembly);
It's trying to find the UserSecretsId attribute on your assembly, and failing that, checking if it could find it in project.json. Then (as commented) returns an error about the missing attribute as they wouldn't want to complain about project.json anymore as it is being deprecated.
I want to add to this answer, for those in my situation.
I am writing a .NET Core console app, trying to use the secrets manager (not sure it's meant for console apps). The only way I was able to rid myself of the error was using the assembly level attribute on the assembly where I was using the secrets manager.
As I said, I am not sure if the secrets manager is meant for console apps. So maybe there is an issue with .xproj files vs. .csproj files.
My .NET Core 3.1 Worker Service required additional setup (more than a Web project).
In Program.cs in the CreateHostBuilder method I needed this:
.ConfigureAppConfiguration((ctx, builder) =>
{
// enable secrets in development
if (ctx.HostingEnvironment.IsDevelopment())
{
builder.AddUserSecrets<Worker>();
}
})
But (unlike my Web project) I explicitly needed to add this nuget package:
install-package Microsoft.Extensions.Configuration.UserSecrets
After that I could access secrets.

ReactJS.NET - Bundles - TinyIoCResolutionException: Unable to resolve type: React.IReactEnvironment

I'm attempting to minify my .JSX files with ASP.NET Minification and Optimization via System.Web.Optimization.React. I've installed the MVC4 React Package as well as the Optimization package, but whenever I try to include a bundle I get the following:
React.TinyIoC.TinyIoCResolutionException: Unable to resolve type: React.IReactEnvironment
The InnerException is always null
My bundles are setup as follows:
bundles.Add(new ScriptBundle("~/Bundle/Scripts/ReactJS").Include(
"~/Scripts/React/react-0.12.2.js",
"~/Scripts/React/react-with-addons-0.12.2.js",
"~/Scripts/React/JSXTransformer-0.12.2.js"
));
bundles.Add(new JsxBundle("~/Bundle/Scripts/ReactCalendar").Include(
"~/Scripts/React/Calendar/Main.react.jsx",
"~/Scripts/React/Calendar/Components/Calendar.react.jsx",
"~/Scripts/React/Calendar/Components/CalendarEvent.react.jsx",
"~/Scripts/React/Calendar/Components/CalendarControls.react.jsx",
"~/Scripts/React/Calendar/Components/CalendarTimeSlots.react.jsx"
));
And included in the view as:
#section scripts{
#Scripts.Render("~/Bundle/Scripts/ReactJS");
#Scripts.Render("~/Bundle/Scripts/ReactCalendar");
}
The error is always thrown on line:
#Scripts.Render("~/Bundle/Scripts/ReactCalendar");
Anyone got any ideas on how to solve / debug this one? Let me know if more info is needed.
I'm not sure if this is the same issue I was facing, but I googled the exact same error, found this SO topic as the first hit, with no definitive answer, so I thought I'd offer my solution.
I'm using .NET 4.5 in an MVC app, and React.Web.Mvc4 v3.0.0.
I managed to work around this issue with the help of this comment on Github.
Here's my entire ReactConfig.cs:
using React;
using React.TinyIoC;
using React.Web.TinyIoC;
namespace NS.Project
{
public static class ReactConfig
{
public static void Configure()
{
Initializer.Initialize(AsPerRequestSingleton);
ReactSiteConfiguration.Configuration
.SetLoadBabel(false)
.AddScriptWithoutTransform("~/React/dist/server.bundle.js");
}
private static TinyIoCContainer.RegisterOptions AsPerRequestSingleton(
TinyIoCContainer.RegisterOptions registerOptions)
{
return TinyIoCContainer.RegisterOptions.ToCustomLifetimeManager(
registerOptions,
new HttpContextLifetimeProvider(),
"per request singleton"
);
}
}
}
Then, I'm callingReactConfig.Configure explicitly from Application_Start.
"Unable to resolve type: React.IReactEnvironment" with no InnerException generally means ReactJS.NET is not initialising properly for some reason. In web apps, ReactJS.NET handles initialisation through the use of WebActivator. Make sure your project is referencing React.Web, React.Web.Mvc4 and WebActivatorEx, and all the corresponding .dll files are ending up in your app's bin directory.
Also, you do not need to (and should not) include JSXTransformer in your JavaScript bundles, as ReactJS.NET does all the JSX compilation server-side.
Something looks like changed from React.Web.MVc4 version 4.0.0. versions before didnt have that problem.
as stated here
Install the React.Web.Mvc4 package through NuGet. You will also need to install a JS engine to use (either V8 or ChakraCore are recommended). See the JSEngineSwitcher docs for more information.
To use V8, add the following packages:
JavaScriptEngineSwitcher.V8
JavaScriptEngineSwitcher.V8.Native.win-x64
ReactConfig.cs will be automatically generated for you. Update it to register a JS engine and your JSX files:
using JavaScriptEngineSwitcher.Core;
using JavaScriptEngineSwitcher.V8;
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(React.Sample.Mvc4.ReactConfig), "Configure")]
namespace React.Sample.Mvc4
{
public static class ReactConfig
{
public static void Configure()
{
ReactSiteConfiguration.Configuration
.AddScript("~/Content/Sample.jsx");
JsEngineSwitcher.Current.DefaultEngineName = V8JsEngine.EngineName;
JsEngineSwitcher.Current.EngineFactories.AddV8();
}
}
}
If anyone needs this, just install this nuget and it will resolve this issue.
System.Web.Optimization.React

'bootstrap' is not a valid script name. The name must end in '.js'

I'm learning asp.net and so I'm trying to build up the project named "Wingtip Toys" from MSDN.
The project is developed on VS 2013 and I have VS 2012. When I try to add Bootstrap per the instruction from here I get the error on runtime in browser.
Server Error in '/' Application.
'bootstrap' is not a valid script name. The name must end in '.js'.
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: 'bootstrap' is
not a valid script name. The name must end in '.js'.
when I add the .js on the master page it shows me to another error:
The assembly 'System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' does not contain a Web resource that has the name 'bootstrap.js'. Make sure that the resource name is spelled correctly.
I also add the CSS file to Bundle.config but still the same result. I already have the NuGet package available, like for the jQuery.js error, but I'm unable to sort this out yet.
Here's what worked for me.
I added this to my BundleConfig.cs file:
ScriptManager.ScriptResourceMapping.AddDefinition("bootstrap", new ScriptResourceDefinition
{
Path = "~/scripts/bootstrap.min.js",
DebugPath = "~/scripts/bootstrap.js",
LoadSuccessExpression = "bootstrap"
});
Please go to Tools -> NuGet Package Manager -> Manage NuGet Packages for Solutions.
In Browse, search for: AspNet.ScriptManager.bootstrap
If your version of bootstrap is higher than AspNet.ScriptManager.bootstrap first uninstall bootstrap and then install AspNet.ScriptManager.bootstrap
go to:
Tools
NuGet Package Manager
Manage NuGet Packages for Solutions...
search for Bootstrap.css
install it
try to run your app

Servlet class is not a javax.servlet.Servlet

I am developing a GWT application, but I got the following Exception when I deploy it into a Equinox-jetty server:
404 Servlet class com.cartif.gui.autentication.server.AppServiceImpl is not a javax.servlet.Servlet <html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
<title>Error 404 Servlet class com.cartif.gui.autentication.server.AppServiceImpl is not a javax.servlet.Servlet</title>
</head>
<body><h2>HTTP ERROR 404</h2>
<p>Problem accessing /baasGUIAutentication/baasgui/autentication. Reason:
<pre>
Servlet class com.cartif.gui.autentication.server.AppServiceImpl is not a javax.servlet.Servlet</pre></p><h3>Caused by:</h3><pre>javax.servlet.UnavailableException: Servlet class com.cartif.gui.autentication.server.AppServiceImpl is not a javax.servlet.Servlet
at org.mortbay.jetty.servlet.ServletHolder.checkServletType(ServletHolder.java:362)
at org.mortbay.jetty.servlet.ServletHolder.doStart(ServletHolder.java:243)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
at org.mortbay.jetty.servlet.ServletHandler.initialize(ServletHandler.java:685)
at org.mortbay.jetty.servlet.Context.startContext(Context.java:140)
at org.mortbay.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1250)
at org.mortbay.jetty.handler.ContextHandler.doStart(ContextHandler.java:517)
at org.mortbay.jetty.webapp.WebAppContext.doStart(WebAppContext.java:467)
at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50)
at org.springframework.osgi.web.deployer.jetty.JettyWarDeployer.startWebAppContext(JettyWarDeployer.java:210)
at org.springframework.osgi.web.deployer.jetty.JettyWarDeployer.startDeployment(JettyWarDeployer.java:122)
at org.springframework.osgi.web.deployer.support.AbstractWarDeployer.deploy(AbstractWarDeployer.java:93)
at org.springframework.osgi.web.extender.internal.activator.WarLoaderListener$DeploymentManager$DeployTask.doRun(WarLoaderListener.java:257)
at org.springframework.osgi.web.extender.internal.activator.WarLoaderListener$DeploymentManager$BaseTask.run(WarLoaderListener.java:215)
at org.springframework.scheduling.timer.DelegatingTimerTask.run(DelegatingTimerTask.java:66)
at java.util.TimerThread.mainLoop(Unknown Source)
at java.util.TimerThread.run(Unknown Source)
</pre>
<hr /><i><small>Powered by Jetty://</small></i><br/>
The code header for the AppServiceImpl class is:
public class AppServiceImpl extends RemoteServiceServlet implements AppService
And AppService:
#RemoteServiceRelativePath("autentication")
public interface AppService extends RemoteService {
User getUser(String user, String pass) throws Exception;
}
Moreover, the web.xml declares the servlet as follows:
<servlet>
<servlet-name>baasguiServlet</servlet-name>
<servlet-class>com.cartif.gui.autentication.server.AppServiceImpl</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>baasguiServlet</servlet-name>
<url-pattern>/baasgui/autentication</url-pattern>
</servlet-mapping>
And baasgui is the folder where the GWT Java code is compiled. I have also checked the javax.servlet class and it is used only once.
Could anyone help me??
Thank you very much in advance!!
Jose
This typically happens if you embed the javax.servlet package into your bundle. Then jetty sees the normal javax.servlet deployed as a bundle while your application sees only the embedded class. So the interfaces are considered to be different.
The best solution is to not embed external stuff into your bundle. If you can not avoid it then export and import the javax.servlet package. So the framework can wire jetty and you bundle to the same classloader providing the package.
Start equinox with console
If it is equinox 3.7.x, -Dosgi.console=6666
If it is equinox 3.8 or newer: -Dosgi.console.enable.builtin=true -Dosgi.console=6666
You will be able to telnet to port 6666
Enter the command in telnet session: packages javax.servlet
In the result list, you will see that the package is available in your OSGi container multiple times. Jersey wires to one of them while your wab wires to the other one. Try to achieve having the package only ones in the container.
I got the solution. In the GWT libraries bundle I had to add the following lines:
Bundle-SymbolicName: gwtlibraries; singleton:=true
Require-Bundle: javax.servlet
Instead of importing packages, the tag Require-Bundle and the part of singleton bundle. Also in the GUI manifest I had to add the next line:
Bundle-SymbolicName: GUI; singleton:=true
Require-Bundle: gwtlibraries //apart from importing the specific libraries
Eclipse-RegisterBuddy: com.cartif.gwt
Eclipse-BuddyPolicy: registered
This was not happening with the previous versions of the GWT libraries I had deployed, but the bundle structure was different because now I am using the unzipped libraries and in previous ones the zipped jar files.
Thank you for your collaboration and help!!!!
Here is a rather mundane reason why I got this exception. I adapted my new servlet from an old servlet. Right above the class definition in the .java file, there is a line of the kind: #WebServlet(name="OldServlet",urlPatterns={"/OldServlet"}). Although I properly renamed my class from OldServlet to NewServlet throughout (in the java and web.xml files), I forgot to change the name in the above line. After I changed the above line to #WebServlet(name="NewServlet",urlPatterns={"/NewServlet"}), I stopped getting this exception. Hope this helps.

ASP.net app crashes - Could not load file or assembly 'Microsoft.Threading.Tasks.Extensions.Desktop'

I want to build a Google BigQuery C# ASP.net application using OAuth2 and the .Net 4.5 framework. I ran these NuGet installs
Install-Package Google.Apis.Bigquery.v2 -Pre
Install-Package Google.Apis.Authentication.OAuth2 -Version 1.2.4696.27634
Install-Package Google.Apis -Pre
Install-Package Google.Apis.Auth -Pre
and I placed the relevant "usings" in code-behind file "default.aspx.cs":
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Bigquery.v2;
using Google.Apis.Bigquery.v2.Data;
namespace BigQueryDemoApp
{
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
UserCredential credential;
FileStream stream;
using (stream = new FileStream(
Server.MapPath("~/client_secrets.json"),
FileMode.Open, FileAccess.Read)
)
{
GoogleWebAuthorizationBroker.Folder =
"Tasks.Auth.Store";
credential = GoogleWebAuthorizationBroker.
AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
new[] { BigqueryService.Scope.Bigquery },
"user", CancellationToken.None).Result;
}
// Initialize the service.
var Service = new BigqueryService(
new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "BigQueryDemo"
}
);
}
}
}
I set this specific page as the project start page. I picked "Installed application" when I built the Client ID file at the Google console
APIS & auth -> Credentials -> CREATE NEW CLIENT ID
and I made sure I added this file (client_secrets.json) with the solution explorer in VS2013. In the code-behind, I made sure that I correctly mapped to the client_secrets file with Server.MapPath. For the credential machinery, I used this code
<https://code.google.com/p/google-api-dotnet-client/wiki/OAuth2>
as the starting point. When I run the app, it returns a browser error page that starts with
Could not load file or assembly 'Microsoft.Threading.Tasks.Extensions.Desktop, Version=1.0.16.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.
and crashes at the "credential =" line. I tried to add in some images of the actual ASP.net crashed browser page showing the Assembly Load Trace / Stack Trace / etc. but it looks like I don't have the account rights for this. When I set a breakpoint at the "credential =" line and then run the app through
DEBUG -> Start Debugging
in VS2013, the page stops at the "credential =" line and a file picker opens, looking for file
"GoogleClientSecrets.cs"
from directory
"c:\code\google.com\google-api-dotnet-client\default\Tools\Google.Apis.Release\bin\Debug\output\default\Src\GoogleApis.Auth\OAuth2\GoogleClientSecrets.cs"
which is nowhere on the drive. Using the Assembly Load Trace in the generated ASP.net error page, I tried digging around through the suggested configuration files but nothing worked. More generally, I tried looking for this issue in StackOverflow and while I did find some mention of it, none of that material helped.
Because the error is based on the fact that the latest version of Microsoft.Bcl.Async doesn't work in .NET 4.5, you can try to do the following:
Open your Package Manager Console, and run the following commands:
1) Uninstall-Package Microsoft.Bcl.Async -Force
2) Install-Package Microsoft.Bcl.Async -Version 1.0.16
It works in a sample I'm currently writing. Please let me know if it works for you.
UPDATE (March 21st):
You can update the package (new version 1.0.166-beta is available - https://www.nuget.org/packages/Microsoft.Bcl.Async/1.0.166-beta).
I tested it on VS2013 with .NET 4.5 framework and it works.
They released a new version of -Package Microsoft.Bcl.Async.
If somebody has this issue, please install the "latest" version instead of 1.0.16.
I hope it works for you.
I already encountered this error before. It looks like the Bcl.Async package contains a reference to Microsoft.Threading.Tasks.Extensions.Desktop when you run a .NET 4.0 applications but somehow it is missing in .NET 4.5 application.
My advice for you (until I'll figure our with the owner of Microsoft.Bcl.Async why it happens) is to copy Microsoft.Threading.Tasks.Extensions.Desktop from packages\Microsoft.Bcl.Async.1.0.165\lib\net40\Microsoft.Threading.Tasks.Extensions.Desktop.dll to your BIN folder. It should solve this issue.
UPDATE (March 17th):
Consider adding the following Post-build event to your project:
copy /Y "$(SolutionDir)packages\Microsoft.Bcl.Async.1.0.16\lib\net40\Microsoft.Threading.Tasks.Extensions.Desktop.dll" "$(TargetDir)Microsoft.Threading.Tasks.Extensions.Desktop.dll"
Unfortunately, there isn't a solution for this problem yet from the owners of the Bcl.Async package.
This approach did not fix the issue - I got the same runtime error. But after a rebuild, I noticed that the VS2013 compiler showed this warning, which I formatted a little for the SO editor
C:\Program Files (x86)\MSBuild\12.0\bin\Microsoft.Common.CurrentVersion.targets(1635,5): warning
MSB3247: Found conflicts between different versions of the same dependent assembly. In Visual
Studio, double-click this warning (or select it and press Enter) to fix the conflicts;
otherwise, add the following binding redirects to the "runtime" node in the application
configuration file:
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Microsoft.Threading.Tasks.Extensions.Desktop" culture="neutral" publicKeyToken="b03f5f7f11d50a3a" />
<bindingRedirect oldVersion="0.0.0.0-1.0.165.0" newVersion="1.0.165.0" />
</dependentAssembly>
</assemblyBinding>
so I dropped the suggested block in the app web.config file. Then the app decided to work. I have no idea why it works now, but I get the impression that the XML block and / or the reference fix you mentioned somehow touched the Microsoft.Threading.Tasks.Extensions.Desktop DLL, or some low-level machinery inside .Net, or both. Or neither, for all I know. Anyway, thanks for your help. I only wish I had a better understanding of the internal machinery.

Resources