Cannot obtain value because it has been optimized away - c#

I have a problem with debugging...
All of a sudden I can't see the values of most variables while debugging.
I've managed to get two different messages in the Immediate Window:
Cannot obtain value of local or argument 'parameter' as it is not available at this instruction pointer, possibly because it has been optimized away.
and
Internal error in the expression evaluator.
I've tried and checked the following things:
Solution Configuration is set to debug (not release)
Project -> Settings -> Build -> Optimize code is not set
Tools -> Options -> Debugging -> Use Managaed Compatibility Mode (didn't work)
Do you have any further ideas how I can properly debug again? :(
Thanks in advance
Edit
The code is nothing special.. it happens when I try to watch what's inside parameter[Key]
public void AddOrUpdateQuartzJob(string jobName, IList<KeyValuePair<string, string>> parameters)
{
var jobDetail = this.GetJobDetail(jobName);
if (jobDetail != null)
{
foreach (var parameter in parameters)
{
jobDetail.JobDataMap[parameter.Key] = parameter.Value;
}
}
else
{
this.ScheduleNewJob(jobName, parameters);
}
}

The best way I've found to convince the JIT compiler not to optimize the code is to use an INI file with the name of the assembly in the same folder the assembly is in with the contents:
[.NET Framework Debugging Control]
GenerateTrackingInfo=1
AllowOptimize=0
Note that it has to be the name of the assembly, not the name of the process EXE (unless it is the EXE assembly you want to debug). E.g. if you have an assembly MyCode.dll the INI file name would be MyCode.ini.
Here are some slides from a presentation on .Net debugging which show the difference:
With Optimization:
Without Optimization:

Go to -> Project Properties -> under Build -> set "Optimize Code" checkbox Unchecked.
Also,
Under Project Properties -> Build -> Advanced -> set the "Debug Info" dropdown to "Full" in the Options

For anyone else who was stumped on this, you may be making the same simple mistake I was: my build mode was set to Release from another project I had to build for release earlier in the day. Flip it back to Debug; problem solved.

After making the changes listed by codekaizen and isanka thalagala, do not forget to clean, rebuild and publish to make the changes effective.

Related

Current solution contains incorrect configurations mapping using Premake5 with C#

I'm trying to develop an engine and I was looking for a GUI library in C# in order to build the editor for my engine. I found Avalonia but I'm having some problems setting up the whole environment.
I'm using Premake5 as build tool mixing C++ and C# but I think the problem here is not the languages mixing.
I'm getting this error when I generate my visual studio solution file. Sorry about the image, I needed to post it that way cause when I press the "Open Configuration Manager" the error is gone and exit the Configuration Manager window the compilation works as expected, quite weird.
Here's my code:
This is the premake5 script I run:
include "Dependencies.lua"
workspace "LeafEngine"
startproject "LeafEditor"
configurations { "Debug", "Release" }
platforms { "x64" }
flags { "MultiProcessorCompile" }
outputdir = "%{cfg.buildcfg}-%{cfg.system}-%{cfg.platform}"
group "Dependencies"
include "Leaf/vendor/glfw"
include "Leaf/vendor/imgui"
group ""
include "Leaf"
include "LeafEditor"
include "LeafGame"
Leaf is my C++ engine and LeafGame just a C++ test. Leaf editor is the C# project, which looks like this:
project "LeafEditor"
kind "WindowedApp"
language "C#"
clr "On"
targetdir ("%{wks.location}/bin/" .. outputdir .. "/%{prj.name}")
objdir ("%{wks.location}/bin-obj/" .. outputdir .. "/%{prj.name}")
dotnetframework "net6.0"
nuget { "Avalonia:0.10.13", "Avalonia.Desktop:0.10.13",
"Avalonia.Diagnostics:0.10.13", "Avalonia.ReactiveUI:0.10.13",
"XamlNameReferenceGenerator:1.3.4"
}
files
{
"src/**.cs",
"src/**.xaml",
"src/**.xaml.cs",
}
links
{
"Microsoft.CodeAnalysis.CSharp.NetAnalyzers",
"Microsoft.CodeAnalysis.NetAnalyzers",
"System.Text.Json.SourceGeneration",
"Microsoft.NETCore.APP",
}
filter "system:Windows"
defines "LF_WINDOWS"
filter "system:Unix"
defines "LF_LINUX"
filter "configurations:Debug"
defines "LF_DEBUG"
runtime "Debug"
symbols "on"
filter "configurations:Release"
defines "LF_RELEASE"
runtime "Release"
optimize "full"
Another curious thing about Avalonia: as you can see I only have one available platform ("x64") for building. Well, Avalonia compiles with ("Any CPU") platform and that also breaks my whole building set up. Besides, Avalonia gets compiled with Any CPU when I load the project not when I compile the project, is that right?
Thanks in advance, this error is killling me.
I just had the same issue, both when my C# project was built with premake and with it as an external project.
The solution (granted I gave up on premake for C# so this may only apply to externalproject) is to not add architecture or any specific platform to your workspace, and instead add it to all but your C# project. I would leave a comment since this might not be the answer you're looking for, but I don't have enough reputation. Anyway, for example,
workspace "Lotus"
startproject "LotusEditor"
configurations
{
"Debug",
"Release"
}
project "CppProject"
architecture "x86_64" -- sets CppProject as x64 but not the workspace
-- more project config
externalproject "CsProject" -- no architecture/platform set for this. Might work for non externalprojects too
location "path"
uuid "insert uuid"
kind "WindowedApp"
language "C#"
Even with my project made manually not with premake, and set with target platform as x64, it still seems to want "Any CPU" as the configuration, which premake can't do.

VS 2017 : The security debugging option is set but it requires the Visual Studio hosting process which is unavailable

My solution (which contains a dozen projects) works perfectly in Visual Studio 2013.
In Visual Studio 2017, I can open the solution and compile it.
But if I start the debug, I systematically get this error message:
The security debugging option is set but it requires the Visual Studio
hosting process which is unavailable in this debugging configuration.The
security debugging option will be disabled. This option may be re-enabled in
the Security property page. The debugging session will continue without
security debugging
And then, nothing happens. Nothing starts.
For information, this is a solution with multiple startup projects (including a WPF project).
Edit :
By disabling the option "Enable ClickOnce security settings" under Project -> Properties -> Security tab, it works.
This solved my issue:
Most likely, you have accidentally gotten the bit flipped to debug
with ClickOnce security settings. Can you get the project properties
for your app, go to the "Security" tab, and make sure to uncheck
"Enable ClickOnce Security settings" or check the "This is a full
trust application" radio button.
In case it helps anyone else - I have the same scenario - a multiple startup solution that includes a client that will be deployed with ClickOnce. To eliminate the problem that the client doesn't start after getting the Security Settings dialog, I moved it higher in the list in the startup projects dialog. If the client project is above the server project in the list, no error, everything debugs. If the client project is below the server project, then I get the error and the client never opens. This doesn't exactly SOLVE the problem but is a perfectly adequate workaround for me.
EDIT: You might need to close and reopen your Visual Studio for this workaround to be effective.
I spent hours trying to figure out the issue, this resolved it.
Go to Projct > Properties... > Build
Uncheck the checkbox Prefer 32-bit
MS have removed the VS hosting process in VS2017 - see
https://vslive.com/Blogs/News-and-Tips/2017/02/Debugging-Visual-Studio-2017-aims-to-speed-up-your-least-favorite-job.aspx
Because of this changing the EnableSecurityDebugging setting in the project user file to True simply results in the Error dialog appearing again at run-time.Clicking on OK in the dialog changes the user file setting back to False.
AFAIK there is no workaround although MS seem to be posting very frequent VS updates (latest is 15.3) In the meantime ClickOnce apps. will be unable to use the security debugging option.
This could likely be a glitch in some configuration file. The "Enable ClickOnce security settings" was already unmarked in the project settings but still this dialogue appeared every time the application was started. I did the following to get rid of this dialogue:
Open the project->security setting page
Mark "Enable ClickOnce security settings"
Unmark "Enable ClickOnce security settings"
Save the properties and start the application again
Properties
Here's a workaround that enabled me to debug my ClickOnce app.​ in VS2017 without getting the error message "Unable to determine identity of caller" when accessing Isolated Storage. The workaround should also work in any situation that requires the ClickOnce security settings.
To recreate the settings that were previously generated when the Enable ClickOnce security settings on the Security tab of the project's properties was checked, do the following:
1.Uncheck Enable ClickOnce security settings on the Security tab of your project's properties
2.Add the following to your App.Config file if not already present
<runtime>
<NetFx40_LegacySecurityPolicyenabled="true"/>
</runtime>
3.Add a reference to ​Microsoft.Build.Tasks.v4.0 to your project
The code to recreate the ClickOnce settings can go anywhere, but the following sample Main method illustrates the general idea
using System;
using System.Reflection;
using System.Runtime.Hosting;
using System.Security;
using System.Security.Permissions;
using System.Security.Policy;
using System.Windows.Forms;
using Microsoft.Build.Tasks.Deployment.ManifestUtilities;
namespace SecurityDebuggingTest
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
if (args.Length > 0 && args[0] == "startui")
{
Application.Run(new Form1());
}
else
{
PermissionSet permissions = new PermissionSet(PermissionState.Unrestricted);
string AppName = Assembly.GetEntryAssembly().GetName().Name;
string AppExe = $"{AppName}.exe";
string DebugSecurityZoneURL = $"{AppExe}.manifest";
string AppManifestPath = $"{AppName}.application";
string appType = "win32";
AssemblyIdentity ca = AssemblyIdentity.FromManifest(AppManifestPath);
string appIdentitySubString = $"Version={ca.Version}, Culture={ca.Culture}, PublicKeyToken={ca.PublicKeyToken}, ProcessorArchitecture={ca.ProcessorArchitecture}";
string assemblyIdentity = $"http://tempuri.org/{AppManifestPath}#{AppManifestPath}, {appIdentitySubString}/{AppExe}, {appIdentitySubString},Type={appType}";
System.ApplicationIdentity applicationIdentity = new System.ApplicationIdentity(assemblyIdentity);
ApplicationTrust appTrust = new ApplicationTrust();
appTrust.DefaultGrantSet = new PolicyStatement(permissions, PolicyStatementAttribute.Nothing);
appTrust.IsApplicationTrustedToRun = true;
appTrust.ApplicationIdentity = applicationIdentity;
AppDomainSetup adSetup = new AppDomainSetup
{
ApplicationBase = AppDomain.CurrentDomain.BaseDirectory,
ActivationArguments = new ActivationArguments(
ActivationContext.CreatePartialActivationContext(
applicationIdentity,
new string[] { AppManifestPath, DebugSecurityZoneURL })
),
ApplicationTrust = appTrust
};
Evidence e = new Evidence();
e.AddHostEvidence(appTrust);
AppDomain a = AppDomain.CreateDomain("Internet Security Zone AppDomain", e, adSetup, permissions);
a.ExecuteAssembly(AppExe, e, new string[] { "startui" });
}
}
}
}
You may see the warning message about the VS Hosting process being unavailable when you first run the above code but thereafter the EnableSecurityDebugging setting in your project's user file will have been set to False and the code should run as normal.
Thanks to Microsoft's ClickOnce team for their help on this workaround.
I have yet another cause for why this message may come up. In my case, while testing cloning my solution from Git, I noticed that Visual Studio decided to set the Active solution platform to "Any CPU", whereas my startup project is explicitly targetting "x86". This caused the startup project to not build when I ran the build solution command.
Checking the Build box in the Configuration Manager for that project got rid of the error message.
In case anyone asks, I don't remember exactly why that one project is explicitly targetting x86.
I just had the same issue. Prefer 32-Bit was disabled.
I looked in the Output Path and it was bin\Release.
I created a bin\debug path and set the Output Path to this.
Resolved.
For me the solution was to switch to "The application is available offline as well" in Publish tab of project properties
Before I had "The application is available online only"
My issue seemed to be associated with the folder that the solution was in. My DEV branch solution worked without issue but the CERT branch (different local folder) gave the Security Debugging message when the ClickOnce Security settings were checked.
My solution: launch VS2019 as Admin. Problem is gone when debugging. And now I can launch without Admin and debugging is still good.
A quick solution with no explanation on why: Running my application in "Debug" configuration stopped the error and allowed my application to run.

Unity3D Unsafe code requires the `unsafe' command line option to be specified

i am using Unity3D 4.3 and calling a DLL that i created.
when trying to call the only function it have which is this:
void GetModelReferences(int &nVertices, float * vertices, int &nTriangles, int * triangles, float * normals, float * uvCoordinates);
unity gives me an error:
Unsafe code requires the `unsafe' command line option to be specified
so in my MonoDevelop i opened : Project->Assembly-Csharp options and turned on the unsafe mode.
it reduces part of the errors but this last one wont go away
Unsafe code requires the `unsafe' command line option to be specified
what shoud i do?
Go to your project properties page and check under Build the checkbox Allow unsafe code.
This should solve your problem.
Here is what worked for me with Unity3D 5.3:
- If in your Unity Build Setting->Player Setting->Other Settings, "API Compatibility Level" is ".Net 2.0", create a file under your Unity Asset folder called gmcs.rsp, add this following line to the file:
-unsafe
Close Unity and open it again.
- If the "API Compatibility Level" is ".Net 2.0 Subset", the above file name should be: smcs.rsp.
See the picture bellow to find the location of ""API Compatibility Level" setting in Unity.
The answer is given here: http://answers.unity3d.com/questions/804103/how-to-enable-unsafe-and-use-pointers.html
You need to add a file "smcs.rsp" (or "gmcs.rsp") in your "Assets" directory, which contains the line:
-unsafe
Have you tried this ?
look at the fifth comment
Firstly show the contents of Unity.App and drill down to Contents/Frameworks/MonoCompiler.framework.
Open the file called compile_any.pl and in the section "# Run the
csharp compiler" change #Base_Args options as below:
my #base_args=($mono_path, $mcs_path, '-debug', '-unsafe', '-target:library', '-nowarn:0169', '-out:'.$output, );
You can change the settings through the MonoDevelop:
go to the solution files tree ->
Solution -> your expand your solution -> Assempely-CSharp -> Right Click -> options -> Build -> General -> Language options -> enable "Allow 'unsafe' code"
If you're in a unity project, open Project Settings>Other Settings>Allow Unsafe Code

Problems with settings file depending on configuration (debug, release)

I'm now localizing my WPF application and there is this little piece of code in the constructor of the MainWindow:
System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(Settings.Default.Language);
It crashes right after I start it, saying:
XmlParseException:{"'The invocation of the constructor on type 'Program.MainWindow' that matches the specified binding constraints threw an exception.' Line number '3' and line position '9'."}
its inner: CultureNotFoundException: Culture is not supported. Parameter name: nameen-UK is an invalid culture identifier.
Now I know that there is no such a culture name as en-UK. I just typed it once by accident... I thought there was.
Now everything contains: en-GB. (settings, appconfig, etc.)
Steps I have done:
restart devenv
delete all the bin and obj folders.
search in the entire solution for the expression: "en-UK" (with and without case sensitivity)
search with total commander for "asterisk dot asterisk" containing the text: "en-UK" (with and without case sensitivity)
no results...
Then I put a breakpoint into the constructor and the
Settings.Default.Language
has the value "en-UK".
The point: everything works fine in release mode. It occurs only in Debug mode. How is this possible?
in release mode, the Settings.Default.Language has the en-GB value (which is fine).
Have you met this problem before? Is it a Visual Studio bug or did I go mad? Thank you.
in Visual Studio the debug mode or the release mode each one have a separated config file;
so when you debug with Debug config the old config info still registered;
try to make like this in the constructor:
Setting.Default.Reset();
if this not help you please post some code for more detail.

Powershell, Service Bus For Windows Server Programmatically: Command found, module could not be loaded

From C# code I'm trying to retrieve all the namespaces from powershell... (Later more complex things, like creating namespaces)
PowerShell ps = PowerShell.Create();
ps.AddCommand("Import-Module").AddArgument("ServiceBus").Invoke();
var result = ps.AddCommand("Get-SBNamespace").Invoke();
Above code gives the following exception:
The 'Get-SBNamespace' command was found in the module 'ServiceBus',
but the module could not be loaded. For more information, run
'Import-Module ServiceBus'.
Does anyone know how to solve this error?
CURRENT STATUS: after some debugging I've found that no modules are loaded by default in the PowerShell object. Using the code:
InitialSessionState iss = InitialSessionState.CreateDefault();
iss.ImportPSModule(new string[]{#"serviceBus"});
PowerShell ps = PowerShell.Create(iss);
doesn't work to load the service bus module. Also the code:
ps.AddCommand("Import-Module").AddParameter("-Name", "serviceBus").Invoke();
doesn't work to import the service bus module. Running Visual Studio in administrator mode also doesn't make a difference
Thanks in advance
You didn't say which version of Visual Studio you're using. If it's VS 2012, when you tried the x64 platform target did you make sure that "Prefer 32-bit" was not checked? Even if it was not checked try checking it, saving the project configuration, clearing it and saving again - this worked for me on another project.
UPDATE
It's been suggested elsewhere that there's a bug in VS2012 that shows "Prefer 32-bit" as greyed-out and unchecked when it's actually active. I'm running Update 2 and I don't see that. But it sounds like you might be. I suggest you edit the .csproj file directly.
Whilst "Platform Target" is set at "Any CPU", in Solution Explorer, right-click on the Project name (or, with go to the PROJECT menu) and select "Unload Project". Project files will close and Solution Explorer will display project name (unavailable) > The project file was unloaded:
Right-click on the Project name again and select "Edit project name.csproj". The file is XML and mostly comprises PropertyGroup and ItemGroup elements. In a console project, the first PropertyGroup usually contains a Platform element which should read AnyCPU if you followed my instructions above. The next two PropertyGroups are normally for Debug and Release configurations. If you've added another configuration, it will have its own PropertyGroup. In each of these, look for an element which reads:
<Prefer32Bit>true</Prefer32Bit>
What you should have is an element which reads:
<Prefer32Bit>false</Prefer32Bit>
Either change it or insert it (in each configuration ProjectGroup), save the file and close it. Back in Solution Explorer, right-click the project and select "Reload Project". Let me know if that solves it. You can confirm your PowerShell is now running 64-bit by get the result of
[System.IntPtr]::Size
e.g.
ps.AddScript("[System.IntPtr]::Size");
which will be 4 in an x86 process and 8 in an x64 process.
Which my project set up like this, I was able to load ServiceBus using:
ps.AddCommand("Import-Module").AddArgument("ServiceBus");
Hopefully, you will, too.
I don't have ServiceBus installed so I can't verify exactly what you've tried but
ps.AddCommand("Import-Module").AddArgument("ActiveDirectory").Invoke();
worked for me, so your original syntax looks good.
Just to test for failure, I tried:
ps.AddCommand("Import-Module").AddArgument("CheeseDirectory");
ps.Commands.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);
var importResult = ps.Invoke();
foreach (PSObject result in importResult)
{
Console.WriteLine(result);
}
and got
The specified module 'CheeseDirectory' was not loaded because no valid
module file was found in any module directory.
Have you tried similar?
Do you take care of your Assembly target in your C# program (x86 versus X64). The module may exist in one target, not in the other. PowerShell exists in both.
Seems you're trying to import some modules and execute the cmdlet or function inside the module, right?
So I think you could try the following code:
PowerShell ps = PowerShell.Create();
Assembly ass = Assembly.LoadFile(#"yourServiceBus.dll");
ps.AddCommand("Import-Module").AddParameter("Assembly", ass).Invoke();
var result = ps.AddCommand("Get-SBNamespace").Invoke();
Hope this could help.

Categories