I am getting a "Specified cast is not valid" valid when doing only a release build from MSBuild 4.0. I tested this out in using a release build from Visual Studio 2012 and didn't get this issue. I also tested this out using a debug build from MSBuild 4.0 and didn't get this issue.
Exception:
Code
public abstract class CachedSessionBase : ISessionObject
{
protected Dictionary<MethodBase, Object> _getAndSetCache = new Dictionary<MethodBase, object>();
protected TResult SetAndGet<TResult>(ObjectFactory factory, Func<TResult> func)
{
StackTrace stackTrace = new StackTrace();
var methodBase = stackTrace.GetFrame(1).GetMethod();
if (!_getAndSetCache.ContainsKey(methodBase))
{
_getAndSetCache[methodBase] = func.Invoke();
}
return (TResult)_getAndSetCache[methodBase];
}
The error is being thrown on this line
return (TResult)_getAndSetCache[methodBase];
It is likely that the call stack is different than what you are expecting it to be. Your method may be getting inlined, then GetFrame(1) is retrieving the caller's caller. When the value is retrieved from the dictionary, it is of a different type because it is for a different method.
You could try adding the attribute [MethodImpl(MethodImplOptions.NoInlining] to SetAndGet to prevent the inlining optimization for the method.
I had the same problem when running nuget pack which invoked
MSBuild auto-detection: using msbuild version '15.0'...
but the problem was solved by running dotnet pack which invoked
Microsoft (R) Build Engine version 15.3.409.57025 for .NET Core
Related
I have created a Visual Studios Extension using the AsyncPackage Class that looks something line this:
public sealed class Tools : AsyncPackage, IDisposable
{
internal const string PrjCATIDCSharpFileBrowseObject = "{8D58E6AF-ED4E-48B0-8C7B-C74EF0735451}";
private readonly List<IDisposable> _extenderProviders = new List<IDisposable>();
protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress<ServiceProgressData> progress)
{
await base.InitializeAsync(cancellationToken, progress);
_extenderProviders.Add(new BrowseProvider(this, PrjCATIDCSharpFileBrowseObject));
}
}
I am getting 4 Errors with the code CS1748 on BrowseProvider. What I do not understand is that the Errors it gives are for Types that BrowseProvider does not use. One of the errors is for IAsyncServiceProvider, but BrowseProvider uses IServiceProvider. AsyncPackage does inherit IServiceProvider, but I changed BrowseProvider to use IAsyncServiceProvider however this did not solve the problem. Creating a new BrowseProvider object anywhere in Tools shows this CS1748 error.
I have looked around and found that this error is caused by a reference DLL. I set Microsoft.VisualStudio.Shell.Framework to have its Embed Interop Type Property set to False, but the errors still persists.
All of my code shows no errors except when I try and create a BrowseProvider object from with in the Tools Package. I do not understand why creating a new object anywhere in the Tools Class shows errors for type that are no being used.
Please make sure that you reference the correct dll or the nuget package in your project. Usually you get this error, when there is no reference.
I am getting a System.TypeInitializationException in C# when i try to call the following:
List<BuyShopItem> buyShopItemList = new List<BuyShopItem>(0);
BuyShopItem is in an external assembly and contains the following:
namespace GameProtocol
{
public struct BuyShopItem
{
public int ShopItemID;
public int Amount;
public int GoldPrice;
public int SilverPrice;
public int CharacterPointPrice;
public int ResearchPointPrice;
}
}
It's probably because of the external assembly, right?
Unfortunately, i cannot change it as i need to pass the BuyShopItem back again to another external Assembly.
Some information about the assembly: It's from a Unity game, .NET 3.5 (according to DotPeek: msil, .Net Framework v3.5)
I'm having the issue in SharpDevelop as well as Visual Studio 2017, so it probably not IDE-related.
Result of peverify:
Microsoft (R) .NET Framework PE Verifier. Version 4.0.30319.0
Copyright (c) Microsoft Corporation. Alle Rechte vorbehalten.
[MD]: Error: Field has a duplicate, token=0x040059d7. [Token:0x040059CF]
[MD]: Error: Field has a duplicate, token=0x040059cf. [Token:0x040059D7]
[MD]: Error: Field has a duplicate, token=0x0400a48b. [Token:0x0400A478]
[MD]: Error: Field has a duplicate, token=0x0400a478. [Token:0x0400A48B]
4 Fehler wird/werden überprüft Assembly-CSharp.dll
If you have any Hints of what it could be, please tell me. I will try it out as soon as i can.
Here is a screenshot of the Exception in Visual Studio 2017:
https://i.imgur.com/WHCbWTM.png
Update: I just tried the following: Console.WriteLine(typeof(BuyShopItem));, same error occured. Why isn't it possible to get the type?
It is OK to create a zero-length list of structs.
It is also OK to create a list of some type that is defined in a different assembly - but check to make sure that the necessary DLL can be located at runtime.
Instances of structs are generally fairly safe to construct - but check to see if there is a custom constructor that is throwing an exception.
Also carefully check to see if the BuyShowItem struct specifies any static fields that call into other code, which in turn may be failing. This is often the root cause of TypeInitializationException.
See: https://msdn.microsoft.com/en-us/library/system.typeinitializationexception(v=vs.110).aspx
I have the following code:
namespace NS{
public class ClassName{
public PropertyName{get;}
}
}
I get the following error:
TestFile.cs(11,32): error CS0840: 'NS.ClassName.PropertyName.get' must
declare a body because it is not marked abstract or extern.
Automatically implemented properties must define both get and set
accessors.
When compiled in VS2015 everything is working good. When trying to build using MSBuild the error happens.
I am compiling against .NET 4.6.2 with C# 6.0 and ToolsVersion 14.0.
What am I missing?
What is almost certainly happening here is that your version of MSBuild is old and is compiling against version 5 of C#. Consider this code:
public class Foo
{
public Foo()
{
Bar = 1;
}
public int Bar { get; }
}
This will compile happily in C# 6 (i.e. VS2015) but will throw the error you experience from MSBuild (and also if you used VS2013.)
If you want to compile with MSBuild then you need to download and install the updated build tools: https://www.microsoft.com/en-us/download/details.aspx?id=48159
Recently in my WinForm project, I installed MiniProfiler.Windows and write following decorator for my QueryHandlers(I'm using CQRS):
public class MiniProfilerQueryHandlerDecorator<TQuery,TResult>:IQueryHandler<TQuery,TResult> where TQuery : IQueryParameter<TResult>
{
private readonly IQueryHandler<TQuery, TResult> _decoratee;
public MiniProfilerQueryHandlerDecorator(IQueryHandler<TQuery, TResult> decoratee)
{
_decoratee = decoratee;
}
public TResult Handle(TQuery request)
{
TResult result;
using (StackExchange.Profiling.MiniProfiler.Current.Step("Call QueryHandler"))
{
result =_decoratee.Handle(request); //call some Linq to entity queries
}
var friendlyString = ConsoleProfiling.StopAndGetConsoleFriendlyOutputStringWithSqlTimings();
Debug.WriteLine(friendlyString);
return result;
}
}
I get following error at var friendlyString=ConsoleProfiling.StopAndGetConsoleFriendlyOutputStringWithSqlTimings()
line.
An unhandled exception of type 'System.MissingMethodException' occurred in IASCo.Application.Core.dll
Additional information: Method not found: 'Boolean StackExchange.Profiling.MiniProfiler.get_HasSqlTimings()'.
Does anyone know where is the problem?
MissingMethodException = an attempt is made to dynamically access a deleted or renamed method of an assembly that is not referenced by its strong name (msdn).
Or as this answer puts it:
This is a problem which can occur when there is an old version of a DLL still lingering somewhere around
I notice that the MiniProfiler.Windows library is using a very old (over 2 years) version of MiniProfiler. That version of the code did indeed have a MiniProfiler.HasSqlTimings property. However, the current version (3.0.11) no longer has this property.
I am guessing that you are using the code from the MiniProfiler.Windows library that you linked above, but instead of using the v2 MiniProfiler dll that they have saved in /packages, you are using a v3 MiniProfiler dll (maybe downloaded from nuget). This would explain the exception that you are getting.
If this is indeed the case, then you can solve this by either downloading the version 2.0.2 nuget (Install-Package MiniProfiler -Version 2.0.2) or by upgrading the code in ConsoleProfiling to be compatible with MiniProfiler v3.
I've added the Windows Azure Cache 1.8.0 nuget package to my solution, but it ends up crashing Visual studio when I load the project. I've found that I can "prevent" the crashing by removing the dlls from the bin folder, and then again when visual studio adds them back to the bin while the project loads.
The dlls I'm removing are:
Microsoft.ApplicationServer.Caching.AzureClientHelper.dll
Microsoft.ApplicationServer.Caching.AzureCommon.dll
Microsoft.ApplicationServer.Caching.Client.dll
Microsoft.ApplicationServer.Caching.Core.dll
When I look at the event viewer for the visual studio crash I get this:
Application: devenv.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.ArgumentNullException
Stack:
at System.Threading.Monitor.Enter(System.Object)
at Microsoft.ApplicationServer.Caching.DataCacheFactory.Close()
at Microsoft.ApplicationServer.Caching.DataCacheFactory.Finalize()
I'm uncertain why VS is doing things with the dlls while the project is loading, but I admit I'm not an expert on that.
I've basically followed the process described on this page to add a dedicated cache worker role for caching:
http://www.windowsazure.com/en-us/develop/net/how-to-guides/cache/
I've tried removing and reinstalling the package, removing and reinstalling the Visual Studio SDK (Oct 2012), but the problem comes back.
Also, I don't have the App Fabric Server installed.
Thanks in advance for your help!
In case anyone else runs into this problem, I'm providing what seemed to work for me here.
In order to get visual studio to load the project, I removed the DLLs from the project. I also removed them as the project was loading and VS put the dlls back in the bin folder.
I removed the references to the dlls. Then I removed my code that was using the datacachefactory.
In the end I believe that it was caused by an improper use of the cache in my code that I had performed a build on. I was able to correct the usage of it, build the solution and get all the dlls back into the project.
Previously by datacache object had not be static.
here's my correct usage of the datacache factory:
using System;
using Microsoft.ApplicationServer.Caching;
namespace WebRole1.Classes
{
public class AzureCache
{
public static DataCache cache { get; set; }
public static DataCacheFactory dataCacheFactory { get; set; }
public AzureCache()
{
if (cache == null){
DataCacheFactoryConfiguration cfg = new DataCacheFactoryConfiguration();
cfg.AutoDiscoverProperty = new DataCacheAutoDiscoverProperty(true, "CacheWorkerRole1");
dataCacheFactory = new DataCacheFactory(cfg);
cache = dataCacheFactory.GetDefaultCache();
}
}
public void Add(string item, object value)
{
cache.Add(item, value);
}
public void Add(string item, object value, TimeSpan timeout)
{
cache.Put(item, value, timeout);
}
public object Get(string item)
{
return cache.Get(item);
}
public TimeSpan TimeRemaining (string item)
{
DataCacheItem DCitem = cache.GetCacheItem(item);
return DCitem.Timeout;
}
public void Flush()
{
cache.Clear();
DataCacheFactory cacheFactory = new DataCacheFactory();
cache = cacheFactory.GetDefaultCache();
}
}
}
We may need to capture a dump of the visual studio process(devenv.exe) to see what is causing this exception. You can use debugdiag("http://www.microsoft.com/en-us/download/details.aspx?id=26798") to capture the dump.
You may need to involve Microsoft support services("http://www.windowsazure.com/en-us/support/contact/") to further investigate this since the exception is coming from the cache code itself.
It's not an issue exclusively related to Visual Studio. I get it while running my webrole.
Check out this other article.