Error in calling a method from a WCF web service - asp.net

In my asp.net project there are class libraries called DataLayer, BusinessLayer, ModelLayer and the Web application project. i have added a WCF webservices project to the solution. In the WCF i have implemented a simple method
public string GetName(string name)
{
var Garage = new GarageView_ML();
{
Garage.GarageName = name;
};
return new GarageView_DL().GetNameDL(Garage);
}
In the DataLayer class GarageView_DL i have implemented the following method
public string GetNameDL(GarageView_ML ml)
{
return "OK" + ml.GarageName;
}
The "return" in the line return new GarageView_DL().GetNameDL(Garage); is underlined with dark blue color giving the error
The type 'System.Web.UI.Page' is defined in an assembly that is not
referenced. You must add a reference to assembly 'System.Web,
Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a'. E:\TestProjects\Myapp\WebApplication1\MVCS_WCFService\Service1.cs 42 13 MVCS_WCFService
I have tried adding the System.web reference but it didn't work. Any help is apprciated to solve the issue. thanks in advance.
ps: i can access other layers(Model and business) without any issue. Error comes only when accessing the datalayer.

Related

Asp.net Boilerplate - There is no argument given that corresponds to the required formal parameter

Used ASP.NET boilerplate to create Multi Page Web Application
(includes login, register, user, role and tenant management pages
https://aspnetboilerplate.com/Templates)
Getting below mention error while building the project. Kindly point me a direction to sort the mention issue.
Thank-you.
Error -
Severity Code Description Project File Line Suppression State
Error CS7036 There is no argument given that corresponds to the required formal parameter 'organizationUnitRepository' of 'AbpRoleManager.AbpRoleManager(AbpRoleStore, IEnumerable>, ILookupNormalizer, IdentityErrorDescriber, ILogger>, IPermissionManager, ICacheManager, IUnitOfWorkManager, IRoleManagementConfig, IRepository, IRepository)' test.Core C:\test\4.6.0\aspnet-core\src\test.Core\Authorization\Roles\RoleManager.cs 25 Active
Easily fixed - just add the required params yourself.
public class RoleManager : AbpRoleManager<Role, User>
{
public RoleManager(
RoleStore store,
IEnumerable<IRoleValidator<Role>> roleValidators,
ILookupNormalizer keyNormalizer,
IdentityErrorDescriber errors,
ILogger<AbpRoleManager<Role, User>> logger,
IPermissionManager permissionManager,
ICacheManager cacheManager,
IUnitOfWorkManager unitOfWorkManager,
IRoleManagementConfig roleManagementConfig,
IRepository<OrganizationUnit, long> organizationUnitRepository,
IRepository<OrganizationUnitRole, long> organizationUntiRoleRepository)
: base(
store,
roleValidators,
keyNormalizer,
errors, logger,
permissionManager,
cacheManager,
unitOfWorkManager,
roleManagementConfig,
organizationUnitRepository,
organizationUntiRoleRepository)
{
}
}
Looks like if you are trying to model your RoleManager after the one that designed to work with Abp your parameters don't match the ones that are required for the base class.
This link relates to the Sample they provide.
https://github.com/aspnetboilerplate/aspnetboilerplate/blob/dev/test/Abp.Zero.SampleApp/Roles/RoleManager.cs
This link refers to the implementation of the AbpRoleManager class itself.
https://github.com/aspnetboilerplate/aspnetboilerplate/blob/dev/src/Abp.ZeroCore/Authorization/Roles/AbpRoleManager.cs

Custom tags in App.config - type of my ConfigurationSection class is not recognised

I have followed (almost) to the letter the example from MSDN to create custom tags in my App.config (find documentation here:
https://msdn.microsoft.com/en-us/library/2tw134k3.aspx) but I am getting this error:
An unhandled exception of type
'System.Configuration.ConfigurationErrorsException' occurred in
System.configuration.dll
Additional information: An error occurred creating the configuration
section handler for MyServiceGroup/ServiceUpdater: Could not load type
'MyNamespace.ServiceUpdaterSection' from assembly
'System.configuration, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f33d50a4a'.
and the error is triggered on this line (inside Main from my Console App when I try to make use of the custom information from App.config):
MyNamespace.ServiceUpdaterSection serviceUpdaterSection =
(ServiceUpdaterSection)ConfigurationManager.GetSection("MyServiceGroup/ServiceUpdater");
and from the error message I can already see this is because it's trying to locate MyNamespace.ServiceUpdaterSection inside System.Configuration, on the contrary, it should find this class (ServiceUpdaterSection) inside MyNamespace as I have given it the fully qualified name.
Here is how my App.config looks:
<configSections>
<sectionGroup name="MyServiceGroup">
<section name="ServiceUpdater" type="MyNamespace.ServiceUpdaterSection"/>
</sectionGroup>
</configSections>
and further below inside App.config I have:
<MyServiceGroup>
<ServiceUpdater>
<licenseKey id="blablabla"/>
</ServiceUpdater>
As for the ServiceUpdaterSection class, it looks as follows:
namespace MyNamespace
{
public class LicenseKeyElement : ConfigurationElement
{
[ConfigurationProperty("id")]
public string Id
{
get
{
return (string)this["id"];
}
set
{
this["id"] = value;
}
}
}
public class ServiceUpdaterSection : ConfigurationSection
{
[ConfigurationProperty("licenseKey")]
public LicenseKeyElement LicenseKey
{
get
{
return (LicenseKeyElement)this["licenseKey"];
}
set
{
this["licenseKey"] = value;
}
}
}
}
What are your thoughts on this please?
Thank you.
The error was here:
<section name="ServiceUpdater" type="MyNamespace.ServiceUpdaterSection"/>
which should have been:
<section name="ServiceUpdater" type="MyNamespace.ServiceUpdaterSection, MyNamespace"/>
Will leave it in case someone else encounters the same issue.

Auto-start ASP.NET application hosting WebAPI instance

We're having an odd issue with a WebAPI application hosted by another ASP.NET webapp. The WebAPI controllers are all mapped with Ninject but the ASP.NET host site does not use Ninject.
The issue is that any requests to any of the WebAPI controllers fail with a Ninject error and HTTP 500:
"An error occurred when trying to create a controller of type 'MyObjectsController'. Make sure that the controller has a parameterless public constructor."
However, once even a single request to the main webapp is made (such as opening the login page) then the WebAPI calls all work as expected. The WebAPI is registered and initialized as part of the Application_Start global event. The start event is triggered regardless of whether the first request comes in under the WebAPI or the webapp so it's not bypassing the global startup when coming through the WebAPI before the main app. The WebAPI registration is pretty standard stuff:
GlobalConfiguration.Configure(AddressOf WebApiConfig.Register)
And the Register function itself is nothing unusual:
// Web API configuration and services
var cors = new EnableCorsAttribute("*", "*", "*", "X-Pagination");
//To allow cross-origin credentials in Web API
cors.SupportsCredentials = true;
config.EnableCors(cors);
// To disable host-level authentication inside the Web API pipeline and "un-authenticates" the request.
config.SuppressHostPrincipal();
config.Filters.Add(new HostAuthenticationFilter(Startup.OAuthBearerOptions.AuthenticationType));
// Web API routes
var constraintResolver = new DefaultInlineConstraintResolver();
constraintResolver.ConstraintMap.Add("nonzero", typeof(NonZeroConstraint));
//constraintResolver.ConstraintMap.Add("NonEmptyFolderIds", typeof(NonEmptyFolderIdsConstraint));
config.MapHttpAttributeRoutes(constraintResolver);
var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
The NinjectConfig is also pretty standard:
public static class NinjectConfig
{
/// <summary>
/// THe kernel of Ninject
/// </summary>
public static Lazy<IKernel> CreateKernel = new Lazy<IKernel>(() =>
{
var kernel = new StandardKernel();
kernel.Load(Assembly.GetExecutingAssembly());
RegisterServices(kernel);
return kernel;
});
private static void RegisterServices(KernelBase kernel)
{
kernel.Bind<IMyObjectRepository>().To<MyObjectRepository>().InRequestScope();
...
}
}
An example of the DI usage (again, very basic and standard) is:
public class MyObjectRepository : IMyObjectRepository
{
private readonly IMyOtherObjectRepository _objectRepository;
...
public MyObjectRepository(IMyOtherObjectRepository objectRepository)
{
_objectRepository = objectRepository;
...
}
...
}
We want to avoid the requirement of the initial request to the webapp before the WebAPI is available for requests but nothing seems to be getting us towards a solution.
We initially tried out the IIS preloading/app initialization by setting Start Mode to AlwaysRunning and Start automatically to True in the AppPool config. We also enabled preloadEnabled to true and then added the applicationInitialization config section to the web.config such as the following:
<system.webServer>
...
<applicationInitialization>
<add initializationPage="login.aspx" />
</applicationInitialization>
...
</system.webServer>
However, none of these changes and variations of made any difference to the behavior of the WebAPI. We've scoured the web for more help but are at somewhat of a loss as pretty much everything we've come across points to setting the Start Mode, Start Automatically, preloadEnabled, and applicationInitialization and then it will magically work but that's definitely not our experience.
Does anyone have suggestions or ideas?
Install Ninject integration for WebApi nuget package. It creates a file which initializes Ninject on startup. Here is the doc.

How do I make a SignalR external reference to hub and not perform circular reference?

So, I'm trying to create a sample where there are the following components/features:
A hangfire server OWIN self-hosted from a Windows Service
SignalR notifications when jobs are completed
Github Project
I can get the tasks queued and performed, but I'm having a hard time sorting out how to then notify the clients (all currently, just until I get it working well) of when the task/job is completed.
My current issue is that I want the SignalR hub to be located in the "core" library SampleCore, but I don't see how to "register it" when starting the webapp SampleWeb. One way I've gotten around that is to create a hub class NotificationHubProxy that inherits the actual hub and that works fine for simple stuff (sending messages from one client to all).
In NotifyTaskComplete, I believe I can get the hub context and then send the message like so:
private void NotifyTaskComplete(int taskId)
{
try
{
var hubContext = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();
if (hubContext != null)
{
hubContext.Clients.All.sendMessage(string.Format("Task {0} completed.", taskId));
}
}
catch (Exception ex)
{
}
}
BUT, I can't do that if NotificationHubProxy is the class being used as it's part of the SampleWeb library and referencing it from SampleCore would lead to a circular reference.
I know the major issue is the hub in the external assembly, but I can't for the life of me find a relevant sample that's using SignalR or MVC5 or setup in this particular way.
Any ideas?
So, the solution was to do the following two things:
I had to use the SignalR .NET client from the SampleCore assembly to create a HubConnection, to create a HubProxy to "NotificationHub" and use that to Invoke the "SendMessage" method - like so:
private void NotifyTaskComplete(string hostUrl, int taskId)
{
var hubConnection = new HubConnection(hostUrl);
var hub = hubConnection.CreateHubProxy("NotificationHub");
hubConnection.Start().Wait();
hub.Invoke("SendMessage", taskId.ToString()).Wait();
}
BUT, as part of creating that HubConnection - I needed to know the url to the OWIN instance. I decided to pass that a parameter to the task, retrieving it like:
private string GetHostAddress()
{
var request = this.HttpContext.Request;
return string.Format("{0}://{1}", request.Url.Scheme, request.Url.Authority);
}
The solution to having a Hub located in an external assembly is that the assembly needs to be loaded before the SignalR routing is setup, like so:
AppDomain.CurrentDomain.Load(typeof(SampleCore.NotificationHub).Assembly.FullName);
app.MapSignalR();
This solution for this part came from here.

ASP.NET MVC5 Customised Inbound Routing

I'm "playing" around with custom inbound URL routing and have came across a problem.
When I pass my custom route a URL to examine, that ends in *.+, my class is not fired when i submit the request.
An example URL would be "~/old/windows.html"
When I step through this in the debugger, my RouteBase implementation doesn't fire. If i edit the url that i pass to the constructor of my route to try to match against "~/old/windows", my implemetation is fired as expected.
Again, If i change the url ro examine to "~/old/windows." the problem reoccurs.
My Route Implementation is below :-
public class LegacyRoute : RouteBase
{
private string[] _urls;
public LegacyRoute(string[] targetUrls)
{
_urls = targetUrls;
}
public override RouteData GetRouteData(HttpContextBase httpContext)
{
RouteData result = null;
string requestedURL = httpContext.Request.AppRelativeCurrentExecutionFilePath;
if (_urls.Contains(requestedURL, StringComparer.OrdinalIgnoreCase))
{
result = new RouteData(this, new MvcRouteHandler());
result.Values.Add("controller", "Legacy");
result.Values.Add("action","GetLegacyURL");
result.Values.Add("legacyURL", requestedURL);
}
return result;
}
public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
{
return null;
}
}
In the RoutesConfig file I have registered my route like so :-
routes.MapMvcAttributeRoutes();
routes.Add(new LegacyRoute(new[]{"~/articles/windows.html","~/old/.Net_1.0_Class_Library"}));
Can anyone point out why there is a problem?
By default, the .html extension is not handled by .NET, it is handled by IIS directly. You can override by adding the following section in Web.config under <system.webServer> -
<handlers>
<add name="HtmlFileHandler" path="*.html" verb="GET" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
As pointed out here. The above will route EVERY .html file request to .NET, you might want to be more specific by providing a more complete path if you don't want your routing to handle every .html file.
I've found the problem, and I'm sure this will help out a lot of fellow developers.
The problem is with IIS Express that is running via Visual Studio.
There is a module configured in the applicationhost.config called :-
UrlRoutingModule-4.0
This is how it looks in file :-
<add name="UrlRoutingModule-4.0" type="System.Web.Routing.UrlRoutingModule" preCondition="managedHandler,runtimeVersionv4.0" />
You need to set the preCondition Parameter to "".
To do this :-
Run you app via Visual Studio
Right click on IIS Express in your system tray, select "Show All Applications"
Click on the project you wish to edit, then click the config URL.
Open the file with Visual Studio, Locate the module and ammend.
Hope this helps anyone else, who ran into a similar problem.

Resources