I use a simple postsharp.config file :
<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.postsharp.org/1.0/configuration">
<Multicast xmlns:my="clr-namespace:ExceptionAutoSerializer.Aspects;assembly:ExceptionAutoSerializer">
<my:MethodBoundaryAspect AttributeTargetTypes="MyTopLevelNamespace.*" />
<my:MethodBoundaryAspect AttributeTargetMembers="*ctor*" AttributeExclude="true"/>
<my:MethodBoundaryAspect AttributeTargetMembers="get_*" AttributeExclude="true"/>
<my:MethodBoundaryAspect AttributeTargetMembers="set_*" AttributeExclude="true"/>
</Multicast>
</Project>
All my project in my solution are under the namespace MyTopLevelNamespace. And every single project in the solution has the aspect applied to it correctly except for my website project. I'm not familiar with the solution as I just got in the dev team.
All I know is that I would like to apply aspect to classes within this project and that postsharp seems to ignore that particular project. The config file is located in the src/ folder and should be applied to all project.
I've made sure the types I'm applying my aspect to are under the namespace specified in the config file and that it doesn't match any of the excluding patterns.
Did I provide enough information ? I'm not sure it is due to the project beeing a website project but I can't see anything else.
Edit: I've made sure I added the nuget package to the project. I also tried to manually add the aspect with an attribute to a specific method of this project and the aspect doesn't trigger.
Edit2: this is the method that I use to test:
[MethodBoundaryAspect]
public bool Foo(string bar1, string bar2)
{
// at runtime test contains indeed one attribute MethodBoundaryAspect
var test = this.GetType().GetMethod("ValidateUser").GetCustomAttributes(false);
//here the exception is caught higher up but the "onException" of my attribute doesn't trigger
throw new Exception("test exception");
}
and my postsharp aspect :
namespace ExceptionAutoSerializer.Aspects
{
[Serializable]
public class MethodBoundaryAspect : OnMethodBoundaryAspect
{
//[...]
public override void OnEntry(MethodExecutionArgs args)
{
//[...]
}
public override void OnSuccess(MethodExecutionArgs args)
{
//[...]
}
public override void OnException(MethodExecutionArgs args)
{
//[...]
}
}
}
According to an old answer of a developper at PostSharp Technologies :
PostSharp is (currently) integrated via MSBuild (as also mentioned by
John Saunders), which is not used by website projects.
While in it's core PostSharp is a command-line tool, it gets so much
information from MSBuild that it's quite hard to make it work
separately (and neither advised nor documented nor supported in the
first place). Daniel Balas
I didn't find any update on that subject for version older than 4.3. For 4.3 and earlier according to the previous answer and this documentation (p. 45) website project are not supported.
Edit: when questioning the previously quoted author about the current validity of they answer they responded this in comment :
#Amon For project-less websites (which IIRC are not creatable from the
UI in VS 2017 and later) it is still true. However, all web projects
that have csproj/vbproj (.NET or .NET Core) are working as expected
(this also didn't change since then). – Daniel Balas
Related
Before I start, I've tried all suggestions from the following and none work:
Integration testing ASP.NET Core with .NET Framework - can't find deps.json
https://zimmergren.net/unable-to-find-deps-json-dotnet-azure-devops/
So I'm trying to write some integration tests for dotnet 6. However, my WebApplicationFactory throws the following error:
System.InvalidOperationException: Can't find
'/repos/subscription-info-api/tests/SubscriptionInfoApi.Tests.Integration/bin/Debug/net6.0/...
System.InvalidOperationException Can't find
'/repos/subscription-info-api/tests/SubscriptionInfoApi.Tests.Integration/bin/Debug/net6.0/testhost.deps.json'.
This file is required for functional tests to run properly. There
should be a copy of the file on your source project bin folder. If
that is not the case, make sure that the property
PreserveCompilationContext is set to true on your project file. E.g
'true'. For
functional tests to work they need to either run from the build output
folder or the testhost.deps.json file from your application's output
directory must be copied to the folder where the tests are running on.
A common cause for this error is having shadow copying enabled when
the tests run. at
Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactory1.EnsureDepsFile() at Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactory1.EnsureServer()
at
Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactory1.CreateDefaultClient(DelegatingHandler[] handlers) at Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactory1.CreateDefaultClient(Uri
baseAddress, DelegatingHandler[] handlers) at
Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactory1.CreateClient(WebApplicationFactoryClientOptions options) at Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactory1.CreateClient()
at SubscriptionInfoApi.Tests.Integration.UnitTest1.Test1() in
/repos/subscription-info-api/tests/SubscriptionInfoApi.Tests.Integration/UnitTest1.cs:line
14 at SubscriptionInfoApi.Tests.Integration.UnitTest1.Test1() in
/repos/subscription-info-api/tests/SubscriptionInfoApi.Tests.Integration/UnitTest1.cs:line
16 at
Xunit.Sdk.TestInvoker1.<>c__DisplayClass48_0.<<InvokeTestMethodAsync>b__1>d.MoveNext() in /_/src/xunit.execution/Sdk/Frameworks/Runners/TestInvoker.cs:line 264 --- End of stack trace from previous location --- at Xunit.Sdk.ExecutionTimer.AggregateAsync(Func1 asyncAction) in
//src/xunit.execution/Sdk/Frameworks/ExecutionTimer.cs:line 48 at
Xunit.Sdk.ExceptionAggregator.RunAsync(Func`1 code) in
//src/xunit.core/Sdk/ExceptionAggregator.cs:line 90
My actual test code is extremely simple:
[Fact]
public async Task Test1()
{
await using var app = new WebApplicationFactory<Program>();
using var client = app.CreateClient();
var res = await (await client.GetAsync("/alive-test")).Content.ReadAsStringAsync();
Assert.Equal("Alive!", res);
}
As per the suggestions, I've made sure I'm directly referencing Microsoft.AspNetCore.Mvc.Testing -> 6.0.0 in my integration tests project. I've also tried the various tweaks to the .csproj files that were suggested but nothing seems to be working.
I'm stuck for things to try to debug this further, any ideas?
You are probably targeting the wrong namespace for Program in your test file (like I was).
I had to add the following at the end of my Program.cs file (last line) to make it visible to my test projects needing it:
public partial class Program { }
An example can be found here: minimal api testing example
I had the same problem, although for an entirely different reason.
I am using .net 6 but I deliberately chose to use an implementation that actually has a Program.cs file.
When I copied the code from the official MS integration test guide, I let VS pull in all the dependencies. The dependency used to resolve the Program.cs was not my own (PersonalSite for the sake of this answer), but one of MS's own implementation:
A small error on my part, sure, but maybe I can help somebody out.
For those who actually need the partial class implementation gimmick, the MS integ test guide I linked lists guidelines to do just that.
FWIW there is another approach that works as well (which doesn't require modifying code).
In your app's .csproj file add the following (Assuming your test project is called 'Tests'):
<ItemGroup>
<InternalsVisibleTo Include="Tests" />
</ItemGroup>
This allows your Tests project to see your Program.cs file.
change your Program class access specifier in your api from internal to Public
The setup is as follows:
a .NET Standard 2.0 library
a NUnit test project for it, targeting .NETFramework 4.6.1
Latest VS 2017, latest NUnit.
I've been working on the project on weekend from home, uploaded my work to git and today started working from work (I've already worked from both places before). Only now I found that something was wrong with the project (I don't remember very well what was wrong at the start, but it seems the problem was the same as I have now, described later).
After fiddling around to unrepairable state with it, I wholly deleted it and cloned the git repo anew.
The project compiles fine, but at runtime tests throw "Method not found" exception. A bit of poking around showed that the problem only manifests on one overload of the following method:
public static YNABClient GetInstance(HttpMessageHandler _handler)
{
if (instance is null)
{
instance = new YNABClient(_handler);
}
return instance;
}
public static YNABClient GetInstance() => GetInstance(new HttpClientHandler());
The one without parameters is fine, the one with is not. Deleting and adding library as a reference to tests, deleting and adding both test and library project. Other solutions for similar situations I found on the internet all pertain to ASP.NET MVC, which is not my case, though this question did lead me to checking overloads and finding that one of them actually works.
At home everything still works fine, though I have yet to try to delete and reinstall the project as I did at work. This leads to 2 possible sources for problems: environment, though I haven't managed to find a meaningful difference, or git, though I use a "stock" git ignore for VS (this one), so there shouldn't be problems there. The basic setup for my projects didn't change during weekend and worked before, so something broke from recent fiddling.
Also, if I add a console application(.Net Framework 4.6.1) to solution and try calling the problematic method from it, it actually works fine.
If that would help, my github for the project is here
I've been asked for calling examples in the comments. Basically, I have 2 Test Fixture classes with different setups - one for real API calling for ease of debugging actual use, and one with faking it, as per good test practices.
Works:
[OneTimeSetUp]
public void Setup()
{
ynabClient = YNABClient.GetInstance();
ynabClient.RefreshAccessToken(ApiKeys.AccessToken);
}
Throws exception:
[OneTimeSetUp]
public void Setup()
{
handler = new StubHandler();
ynabClient = YNABClient.GetInstance(handler);
}
Some poking around shows that my problem is quite likely related to System.Net.Http versioning discrepancy with .NET Framework and .NET Standard, that is quite a widespread problem if you google it. However none of the examples I dug up exhibit my particular symptoms, and I'm not yet sure what to do. And why everything works fine on my home PC.
The issue that you have is that your GetInstance method accepts HttpMessageHandler as parameter, and in your test you are passing HttpClientHandler object. So, you have declared one parameter, but provide different object when you call the method.
I got this error in my environment:
Severity Code Description Project File Line Suppression State
Error CS0433 The type 'HttpMessageHandler' exists in both
'System.Net.Http, Version=4.2.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a' and 'System.Net.Http,
Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
Your YNABConnector is .NET Standard 2 but Unit test is 4.6.1, they are using different signature for same assembly.
Here is official document to test:
https://github.com/nunit/docs/wiki/.NET-Core-and-.NET-Standard
created a .NET Core Library(be aware that: cannot be .NET Standard library by above link),
copy your test code there,
follow the official document to add references,
your code works then, no errors.
But in your base code, I still prefer this code:
public class YNABClient
{
private static YNABClient instance;
private HttpClient client;
private HttpMessageHandler handler;
private YNABClient(HttpMessageHandler _handler = null)
{
handler = _handler ?? new HttpClientHandler();
client = new HttpClient(_handler);
}
public static YNABClient GetInstance(HttpMessageHandler _handler = null)
{
return instance ?? (instance = new YNABClient(_handler));
}
......
}
So, it turns out, as DongDong suggested, the problem is indeed with interfacing between .NET Framework and .NET Standard. The problem is not really that they're incompatible, or that Test project needed some additional dependencies, but that they're shipped with different versions of System.Net.Http.
The diagnostics were hindered by showing no visible errors. However, changing parameter types showed that indeed, the problem is only with classes from that namespace.
Another problem with diagnosing the issue was that the project works fine on some machines (my home PC and Daisy Shipton's from comments to the question).
However after determining the source of the problem I was able to google what problems exist with the library in the first place, and eventually found a trove of uncompatibility issues on .NET github.
I tried the solution used in those cases and added a "binding redirect" to a concrete version of the library, and after that it works fine. I added the redirect to app.config of my Tests project. For reference it looks like this:
<dependentAssembly>
<assemblyIdentity name="System.Net.Http" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.2.0.0" newVersion="4.2.0.0" />
</dependentAssembly>
I still have no understanding of why the project worked fine on some machines.
I'm trying to get .Net Framework and NetStandard assemblies to communicate with each other (to learn what is possible). I currently have four projects, two Framework 4.5.2 projects and two NetStandard1.2 projects:
Framework452.Library
NetStandard12.CentralLibrary
NetStandard12.BaseLibrary
Framework452.Tests
The referencing structure is:
Framework452.Tests references NetStandard12.CentralLibrary: working by adding the NetStandard.Library nuget package to Framework452.Tests.
NetStandard12.CentralLibrary references NetStandard12.BaseLibrary: working without modification.
NetStandard12.CentralLibrary references Framework452.Library: Not working, even when Framework452.Library has the NetStandard.Library nuget package installed.
Can NetStandard projects reference Framework projects? If so, what do I need to do to get them to communicate? At the moment I can add the reference, but it is not visible to the code.
Update
I recreated the solution and added the code below, which when I try to compile gives the following error from the Framework452.Tests project:
Error CS0006: Metadata file
'~\TryNETStandard\NetStandard12.CentralLibrary\bin\Debug\netstandard1.2\NetStandard12.CentralLibrary.dll'
could not be found.
namespace Framework452.Library
{
public class Returner452 {
public static bool ReturnTrue() { return true; }
}
}
using Xunit;
namespace Framework452.Tests
{
public class Class1 {
[Fact]
public void FrameworkTest() {
Assert.True(NetStandard12.CentralLibrary.Class1.Return452());
}
[Fact]
public void NetStandardTest() {
Assert.True(NetStandard12.CentralLibrary.Class1.Return12());
}
}
}
namespace NetStandard12.BaseLibrary
{
public class Returner12 {
public static bool ReturnTrue() { return true; }
}
}
using Framework452.Library;
using NetStandard12.BaseLibrary;
namespace NetStandard12.CentralLibrary
{
public class Class1
{
public static bool Return452() { return Returner452.ReturnTrue(); }
public static bool Return12() { return Returner12.ReturnTrue(); }
}
}
According to this page https://learn.microsoft.com/en-us/dotnet/standard/net-standard#net-platforms-support you should be able to achieve your purpose because .NET Standard 1.2 support .NET Framework 4.5.1 (UPDATE: This statement is not 100% correct. Please see the Update section below.)
I tried to set up a solution in VS 2017 and set the references as you described. Here is the result.
and this is the Class1.cs in NetStandard12.CentralLibrary
The code compiles fine without any errors.
Note: your code may fail if the Framework452.Library uses an API that is not supported by .NET Standard 1.2 (e.g Winforms, Win32 API or any Microsoft proprietary library that does not make sense for cross platform).
I recommend this youtube playlist on the .NET standard introduction from one of the MSFT https://www.youtube.com/watch?v=YI4MurjfMn8&list=PLRAdsfhKI4OWx321A_pr-7HhRNk7wOLLY
In .NET Standard - Checking Compatibilty , he recommended tools to help you find out what API is not supported in the .NET Standard.
Thing will become easier with .NET Standard 2.0 and 'compat shim'
UPDATE:
After trying again with more data provided by the question, it's true that a library targeting (depends) .NET Standard could not depend on a library that target .NET Framework. For some strange reason, the compiler allows me to compile the example that I gave above. This could be a bug in tooling.
After a little more research, I found a good example demonstrate the relationship between NetStandard and NetFramework: How .NET Standard relates to .NET Platform.
The graph here show the dependencies
According to the graph, there is no way a library that depends on .NET Standard could see/use the .NET framework implementation.
When .NET Standard 2 is released, this may change a little bit and you could reference .NET Framework via Compatibility Shim. See this video for more in-depth explanation https://youtu.be/vg6nR7hS2lI?list=PLRAdsfhKI4OWx321A_pr-7HhRNk7wOLLY&t=169
No, .NET Standard projects cannot reference framework projects.
.NET Standard projects need to be usable across platforms, forcing a dependency on the .NET framework by referencing an assembly targeting it makes this impossible.
Note that with some of the magic Microsoft is doing with .NET Standard 2.0 this is less true but the overall idea still stands.
I apologise for this - it's an idiot question and I hate myself for asking it, but I can't figure out a reason for this behaviour.
I have a namespace which contains a mixture of static and non-static classes.
namespace MyNameSpace.UI.Helpers
{
public static class OrderHelper
{ // static methods
}
}
namespace MyNameSpace.UI.Helpers
{
public class CountToCampaignConverter : IMultiValueConverter
{ // non-static methods
}
}
These being helper classes, they're used throughout the application. In this class:
using MyNameSpace.UI.Helpers;
namespace MyNameSpace.UI.ViewModels
{
public class QuickCountViewModel : BaseViewModel
{
private void BuildOrderExclusionsOnCount()
{
CurrentAvailability.OrderExclusions = CountHelper.BuildOrderExclusionAsCsv(ordersToExclude);
}
}
}
However in this class:
using MyNameSpace.UI.Helpers;
namespace MyNameSpace.Service.Services
{
public class FulfillJobs : BaseService
{ // stuff
}
}
When I try to use my helpler classes, I've got access to the non-static ones, but none of the static ones.
I can't see any naming clash here - if that were the problem, surely I wouldn't be able to get the non-static ones either?
So where else can I look to resolve the issue?
This is an old post, but no fix was discovered and this issue just happened to me. Here's my particular scenario and the resolution.
I had a Visual Studio 2019 C# solution with two projects: a .NET Standard 2.0 class library and a .NET Core 3.1 console app that used the library. Everything worked fine until I changed the library from .NET Standard 2.0 to 2.1. Afterward, new static items (classes, properties, methods) defined in the library would not be recognized in the app or Visual Studio. If I reset the library back to .NET Standard 2.0 then the static items became visible, but that was not a viable solution for me.
To solve the problem, I set the library's target framework back to .NET Standard 2.1. Then I opened the app project's Reference Manager (Solution Explorer > App Project > Dependencies (right click) > Add Project Reference). I cleared the existing reference to the library and clicked OK. Then I repeated the process, but restored the reference to the library. Suddenly, the app and Visual Studio recognized all the new static items in the library.
The reason is because in the second sample, the class is in a different namespaceMyNameSpace.Service.Services.
If you add a "using" for the namespace MyNameSpace.UI.Helpers in your file, it will be visible.
You can also reference your class as UI.OrderHelper from your services, since both share the root "MyNamespace".
Has anyone been able to get an extension up and running Expression Blend + Sketchflow preview? I'm looking for an example project.
I was following this article, but it is a bit outdated.
So far I:
Created a .Net 4.5 class library project
Added a reference to the Microsoft.Expression.Extensibility.dll in the new Blend Preview directory
Set my project to deploy to the appropriate Addins directory
Setup Visual Studio to run the new Blend.exe for debugging
Hooked up MEF and inherited IPlugin as in the example
But my plugin doesn't seem to load and no breakpoints are hit.
After reading your question I decided to start working on a new version of that tutorial.
A few things to get you started right away.
I've created the basic plugin like this:
using System.ComponentModel.Composition;
using Microsoft.Expression.Extensibility;
namespace Demo.Extension
{
[Export(typeof (IPackage))]
public class Demo : IPackage
{
public void Load(IServices services)
{
}
public void Unload()
{
}
}
}
Make sure you:
place the plugins in ...\Blend Preview\extensions
run visual studio as administrator to be able to deploy to that folder during debug
implement the IPackage instead of IPlugin
Got it working by following the demo here.
I used the few modifications above, and put things in the Blend Preview directory.