Using Visual Studio Code and using defined symbols - c#

EDIT: I have edited the whole question, since this is not only for Unity3D, but at all .sln projects.
I have a installation of Visual Studio Code(Not Visual Studio, but this:https://code.visualstudio.com/) on my Macbook at work. VSCode is otherwise working just fine with normal and Unity3D projects. I get Intellisense on all classes, including Unity3D specific ones, like GameObject. So I think my installation and startup sequence is correct.
Only problem I have, is that VSCode does not seem to recognize constants defined in the .csproj files. First I noticed this with some Unity3D plugins, but it is persistent on normal Visual Studio projects too.
My sample project is a dummy application downloaded from internet, but it is fully working on MonoDevelop. This is my code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DummyConsoleApplication
{
class Program
{
static void Main(string[] args)
{
tester();
}
#if DEBUG
static void tester(){
}
#endif
}
}
The function call in Main causes a not found exception on the editor, but it compiles fine, since the .csproj file has this line:
<DefineConstants>DEBUG;TRACE</DefineConstants>
Any verification on if this is normal behaviour for VSCode would be greately appreciated. Also, if anyone is aware of any solution, even hacky ones, to get past this bug and force Intellisense to autocomplete would help out too.
The error I get is:
The name 'tester' does not exist in the current context [DummyConsoleApplication]
My hardware is a Macbook with Yosemite and my compiler is dnx-mono.1.0.0-beta4.

This is a known limitation with OmniSharp, the C# engine that Visual Studio Code is built around. There is an open enhancement request for adding <DefineConstants> support, but it is tied to a larger issue with regards to MSBuild Support.
Currently, this isn't a supported configuration under Visual Studio Code. You can try to define your constants through the launch.json instead, but support is minimal at best.

It should work...
As a sanity check, have you:
"Sync MonoDevelop Project" recently?
Make sure Visual Studio Code has the -csharp solution (.sln) selected? (Click the flame in the status bar to change)

Related

Auto import usings not working Visual Studio 2019

I have the following selective problem with VS 2019 and IntelliSense.
When I start typing a class name which's namespace is not imported yet, IntelliSense suggests it in the Autocomplete column.
Once I press tab instead of completing the name and importing the using directives it autocompletes the whole path e.g.:
Typing 'UserView...' -> App.Web.Areas.Users.ViewModels.UserViewModel
instead of importing -> using App.Web.Areas.Users.ViewModels; and completing the typing to just UserViewModel
But if I write the whole class name and then press Ctrl + ., then IntelliSense imports the using directive.
Do someone know which setting triggers this behaviour?
Actually, I did not face the same issue on my PC.
My Visual Studio 2019 version is 16.7.5 without any other third party vs extensions and I used Newtonsoft.Json.dll.
Actually, you should enable the option Show items from unimported namespaces and it will import using Newtonsoft.Json; automatically when you use TAB to complete the code.
In my side, I typed json and then use TAB to complete the class JsonArrayAttribute. And I did not face the issue as you described.
So I am confused that why this happened in your side.
Or you could try the following steps:
1) If your VS2019 is not the latest version, please update it to the latest version and the new version will add the latest, most comprehensive features.
2) disable any third party vs installed extensions under Extensions-->Manage Extensions in case you have installed some extensions which caused that.
3) reset vs settings under Tools-->Import and Export Settings-->Reset all settings
4) after that, close VS, delete .vs hidden folder under your solution folder, bin and obj folder. Then, restart your project to test again.
Besides, if I misunderstood your issue, please point out and provide any detailed info to describe the issue to help us troubleshoot it quickly.

Handling multiple projects in Visual Studio

I'm trying to handle in one time multiple projects in Visual Studio (SteamVR, Obi). Problem only occures in Visual Studio, in Unity Editor everything works fine.
My projects in Visual Studio 2019 look like this:
Now, I want to write code in main project script which will connect all projects. Code:
using Obi;
using UnityEngine;
using UnityEngine.Rendering;
using Valve.VR.InteractionSystem;
public class ObiURPSteamVR : MonoBehaviour
{
//1 - Obi - no problem in Unity, VS error in declaration
public ObiEmitter emitter;
//2 - URP Volume - working
public Volume URPVolume;
//3 - SteamVR - no problem in Unity, VS error in declaration AND in "using"
public Player steamVRPlayer;
}
My question is how to connect all projects, is it possible? And i will just add one more time, in Unity Editor everything is working, i can drag-drop SteamVR player and ObiEmitter, no errors are in console output. Thanks for every idea.
In Visual Studio, create an "empty solution". Add all your projects to this solution. When one project is referencing types from another project, right click on that project and "Add Reference".
So apparently its a bug in Unity 2019.3.12f version. Checked on 2019.4.01f and everything is working perfectly.

How to enable c# 7 features on Unity3D projects

I wrote a new method in my Unity3D project (using Visual Studio 2017), and for that method I need C# 7 or greater. So I followed the instructions in this guide.
Now, when I try to open the project's properties, Visual Studio opens it, but then it suddenly closes right after opening. Now I can't even open project's properties.
This is how it looks:
Why am I getting the first and third errors? (the ones I showed in the gif)
EDIT
The Roslyn compiler is now supported in Unity 2018.3, which allows you to use the latest C# 7 features!
See: https://blogs.unity3d.com/2018/09/13/unity-2018-3-beta-get-early-access-now/
For Unity3D < 2018.3.*
I will tell you how I have enabled C# 7.3 in Unity3D projects (although some of its features can't be compiled yet). But beware: this method is a hack! It is a premature and experimental usage of C# 7 in Unity.
If you follow the instructions below, I believe you may be able to easily track down the issue, given that in the case of your question it is quite difficult to provide a full MCVE for the SO community. But I believe that what you actually are trying to achieve is enabling C# 7 for Unity, and not solve the bizarre bug in the project properties window.
Before proceeding, I would recommend completely reinstalling Visual Studio 2017 and Unity3D, just to make sure that you are not having any issue related to a bad installation. Always download Unity directly from Unity's webpage instead of using Viual Studio's Installer, so you can get the latest version available.
Enabling C# 7 in Unity 3D projects (tested on Unity3D v.2018.2.10f, VS 2017 v.15.8.5)
First create a new fresh empty project.
Go to Edit -> Project Settings -> Player, find the Other Settings section, then under Configuration / Scripting Runtime Version choose .NET 4.x Equivalent.
We want to tell mcs.exe to process the C# code using the new "experimental" features of C# 7. For that, just create the file mcs.rsp inside your Assets folder. Edit it and write the this line inside it:
-langversion:experimental
Now, create a new folder named Editor inside your Assets folder. Any scripts added to this folder will make Unity create a *.Editor.csproj project file, which holds contain scripts aimed to modify the Unity Editor.
We need to tell Visual Studio that your project supports the C# 7.3 language. This doesn't mean that Unity will be able to compile all features of C# 7.3, but at least Visual Studio will not bitch about the features you are trying to use experimentally.
However if you edit a csproj file directly, Unity will automatically overwrite it at some point (Unity always auto-generate project and solution files). So what you can do is to install a hook which is called when the project file is auto-generated, so you can open the project file yourself and add your customization to it (your customizations are not limited just to changing the language version: you could do more stuff, but you must understand what you are doing here).
For this purpose, place the following script inside the Editor folder:
#if ENABLE_VSTU
using SyntaxTree.VisualStudio.Unity.Bridge;
using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using UnityEditor;
using UnityEngine;
[InitializeOnLoad]
public class ProjectFilesGeneration
{
private class Utf8StringWriter : StringWriter
{
public override Encoding Encoding
{
get { return Encoding.UTF8; }
}
}
static ProjectFilesGeneration()
{
ProjectFilesGenerator.ProjectFileGeneration += (string name, string content) =>
{
// Ignore projects you do not want to edit here:
if (name.EndsWith("Editor.csproj", StringComparison.InvariantCultureIgnoreCase)) return content;
Debug.Log($"CUSTOMIZING PROJECT FILE: '{name}'");
// Load csproj file:
XNamespace ns = XNamespace.Get("http://schemas.microsoft.com/developer/msbuild/2003");
XDocument xml = XDocument.Parse(content);
// Find all PropertyGroups with Condition defining a Configuration and a Platform:
XElement[] nodes = xml.Descendants()
.Where(child =>
child.Name.LocalName == "PropertyGroup"
&& (child.Attributes().FirstOrDefault(attr => attr.Name.LocalName == "Condition")?.Value.Contains("'$(Configuration)|$(Platform)'") ?? false)
)
.ToArray();
// Add <LangVersion>7.3</LangVersion> to these PropertyGroups:
foreach (XElement node in nodes)
node.Add(new XElement(ns + "LangVersion", "7.3"));
// Write to the csproj file:
using (Utf8StringWriter str = new Utf8StringWriter())
{
xml.Save(str);
return str.ToString();
}
};
}
}
#endif
If you want to fully understand what has changed in your project file, just use any diff tool, to compare the previous version and the new version of the csproj file. The hack above basically does something similar to the link you've posted when changing the language version, except that it does that every time Unity auto-generates the project file. Microsoft also provides plenty of documentation on the definitions inside csproj files.
It looks like you are using Unity (you mention it in your post). I cannot tell by your gif because its like 4 pixels wide.
If you are indeed using Unity, you will be unable to use C# 7 features yet. They've only just allowed experimental support for C# 6 (see here).
Unfortunately you are out of luck if you want to use C# 7 in Unity right now.
The properties window not opening sounds like some issue with your installation of Visual Studio (which I can't give much advice on)
For the coding errors, it looks like you're trying to declare a method inside another method (which is quite odd):
void Update() {
...
public void Method1();
}
I imagine that's not your intention. It's complaining because the version of C# you're compiling in doesn't support that (and local methods in C#7 can't be marked public in any case). It's also complaining because your method isn't abstract (or extern) but doesn't have a body, which C# doesn't allow. Is this what you meant?
void Update() {
if (Input.GetKeyDown(KeyCode.R)) // Note no ; here!
{
GetComponent<Renderer>().material.color = Color.red;
}
}
public void Method1() {
// Some code
}
ALSO you have an erroneous ; after your if () statement in line 15. That will cause the GetComponent<Renderer> line (line 17) to always be run, not just if the condition is true. Again, this is probably not what you intended I imagine.

Compile/Run C# file in Xamarin Studio on Mac

Sheepishly looking for a short step-by-step guide on taking a single .cs file like:
using System
namespace Simple
{
class Program // declare a class
{
static void Main()
{
Console.WriteLine ("Hi there!");
}
}
}
and be able to compile and run it in Xamarin Studio (version 5.5.1, build 15) on the Mac (Mono SDK is already installed). I am not interested (yet!) in anything complex like developing an app or anything, but just a way to practice learning C#. I do know how to compile and run using Terminal, but can't seem to figure out how to compile/run a simple .cs file from XS. Thanks :) Hopefully my participation here at SO will be a bit more sophisticated in the future :)
I'm assuming you have created a solution and project in Xamarin Studio? There is a run button in the interface (looks like play on a remote). If you created your .cs file outside Xamarin, you'll probably have to import it into the solution by right clicking the project and clicking add files. I'm pretty sure you can also open a .cs in Xamarin without it having any solution/project attachments. Again, you should be able to hit the play button.
If you haven't got yourself a solution, fire up Xamarin to the welcome page and click new solution. You should have the option to choose C# console project (or even an empty project if you want to start from scratch) or something similar (I'm fuzzy on the details: I typically use MonoDevelop and my copy of Xamarin is buggy right now). Fill out the forms and voilĂ ! A "hello world!" file should be there.
Hope this helps!

Access Violation Exception only appearing when running C# app without debugger attached

I have an application that works fine in Visual Studios 2008, and I am trying to get it into VS 2010 in order to use .NET 4, and I have a really weird problem. When I run the code from either Release mode or Debug mode with the debugger attached (F5), I have no problems running the program. However, when I run the program from either Release or Debug without the debugger attached (Shift+F5), I get an Access Violation Exception when I attempt to run some code in a dll from GDCM. I've created the dlls by using CMake and Swig and following the instructions here adjusting the instructions where necessary to build for VS 2010 and .NET 4.
Does any one have any ideas why this is happening and how I can fix it?
Here's an example of a program where the error occurs. Again, if you create a project with the following as the program in VS 2010 it will run fine when the debugger is attached and fail if the debugger is not attached.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using gdcm;
namespace GDCMVS2010Test
{
class Program
{
static void Main(string[] args)
{
if (args.Length != 1)
{
Console.WriteLine("This program prints the patient name of a dicom file with gdcm");
Console.WriteLine("Usage: [input.dcm]");
return;
}
gdcm.Reader reader = new gdcm.Reader();
reader.SetFileName(args[0]);
reader.Read();
gdcm.File file = reader.GetFile();
gdcm.StringFilter filter = new gdcm.StringFilter();
filter.SetFile(file);
string value = filter.ToString(new gdcm.Tag(0x0010, 0x0010));
Console.WriteLine("Patient Name: " + value);
}
}
}
You should really start using GDCM specific groups to communicate your issues, see:
http://sourceforge.net/apps/mediawiki/gdcm/index.php?title=General_questions#Where_are_the_GDCM_mailing_lists_.3F
100 of GDCM users are on this list and will be able to help you.
You should also provide a dataset (the DICOM file) to help with reproducing the bug.
Thanks
The client profile misses out chunks of the .Net framework that you are unlikely to need on a client machine. ASP .Net for example. See this link http://msdn.microsoft.com/en-us/library/cc656912.aspx
This was because the version of SWIG I was using wasn't working correctly. A new version of SWIG was recently released (version 2.0) which solves this problem. After I reran CMake on GDCM, and then rebuilt GDCM with VS 2010, and put the GDCM dlls back into my example code, everything worked fine.
Check your project properties. I have encountered this problem when I had my Target Framework set to .NET Framework 4.0 Client Profile, when it should have been the one w/out Client Profile. Or vice versa.

Categories

Resources