public static class Contract && .net core 3.1 && macOS - c#

how do I make Contract work on macOS?
the following code
private static int GetInt(string s)
{
Contract.Requires<ArgumentNullException>(s != null);
return 10;
}
static void Main()
{
Console.WriteLine(GetInt("s"));
}
leads to the exception:
An assembly (probably "TestConsoleApp") must be rewritten using the code contracts binary rewriter (CCRewrite) because it is calling Contract.Requires and the CONTRACTS_FULL symbol is defined. Remove any explicit definitions of the CONTRACTS_FULL symbol from your project and rebuild. CCRewrite can be downloaded from http://go.microsoft.com/fwlink/?LinkID=169180. \r\nAfter the rewriter is installed, it can be enabled in Visual Studio from the project's Properties page on the Code Contracts pane. Ensure that "Perform Runtime Contract Checking" is enabled, which will define CONTRACTS_FULL.
it's 2020 today, I work with dot.net core on my mac, but
the link from above is for downloading windows installer that was implemented 5 years ago in 2015 and works with Visual Studio 2010, 2012, 2013, 2015.
And I just wonder if public static class Contract is something that Microsoft uses internally or obsolete or something...
I hope someone can shed some light on the matter, can't you? ))

you were asking "I just wonder if public static class Contract is something that Microsoft uses internally or obsolete or something".
As per my understanding, it's unfortunately obsolete (it used to work with VS 2015 as you pointed out, provided you installed an extension).
See:
Does Visual Studio 2017 work with Code Contracts?
You could perhaps try PostSharp's version of Code Contracts?
I hope that MS will continue support of code contracts sometime in the future.

Related

C# 9.0 Support for Top-level programs in Visual Studio 2019

With the coming of C# 9.0 and .NET 5 a new feature is getting introduced called "Top-level programs".
This functionality takes away a lot of the boilerplate code necessary to create a simple C# application by not having to wrap your code in the usual namespace/class/Main method, as explained in the Welcome to C# 9.0 blog
To create a simple "Hello World" application the only required code for a Top-level program is the following (taken from the blog)
using System;
Console.WriteLine("Hello World!");
To try out this feature I have installed the latest .NET 5 preview package (5.0.100-preview.6.20318.15) running in Visual Studio 2019 (v16.6.5) and created the following "normal" project which compiles and runs from wihtin VS:
using System;
namespace TestProgram
{
class Test
{
static void Main(string[] args)
{
Console.WriteLine("Hello world!");
var fooBar = "Foo" + "bar";
Console.WriteLine(fooBar);
Console.ReadLine();
}
}
}
To test out the Top-level program and see what could(n't) be done with it I got rid of the namespace, class definition and Main method:
using System;
Console.WriteLine("Hello world!"); // 1
var fooBar = "Foo" + "bar"; // 2
Console.WriteLine(fooBar); // 3
Console.ReadLine(); // 3
Which should now be valid syntax. This is the only file in the project and to my knowledge it conforms to all other criteria mentioned in that blog:
Any statement is allowed. The program has to occur after the usings and before any type or namespace declarations in the file, and you can only do this in one file, just as you can have only one Main method today.
However in practise VS underlines everything with the errors preventing me from compiling as either release or debug from within VS.
(1) A namespace cannot direclty contain members such as fields or methods
(2) The contextual keyword 'var' may only appear within a local variable declaration or in script code
(3) The name Console.WriteLine(/ReadLine) does not exist in the current context
Which is what one would expect to see in VS pre-.NET 5, however .NET 5 is surely enabled, and so are language preview functions. As seen in the .csproj:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<LangVersion>preview</LangVersion>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
</Project>
To me the odd thing is that when I try to compile from the CLI using dotnet build the program compiles, and the executable runs flawlessly.
Is Visual Studio at fault here that it does not support this syntax yet, or do I have to enable something somewhere to make Top-level programs a thing?
Summarizing the comments, you have to use the latest preview version of Visual Studio (that's obvious, because the C# 9 is in preview state right now) or build your app from console (like you've already done with dotnet build).
You can track the status of implemented features using Language Feature Status page in Roslyn repo. As you can see, top-level statements feature were merged into 16.7p3 branch. I suppose it means that feature will work in version 16.7 preview 3 at least (you confirmed that it works in 16.7.0 preview 4.0 version).
As an option, you can also try sharplab.io for that feature, just switch a Roslyn branch on top right corner of left panel

Visual Studio 2017 publish ASP.NET Core app with C# 7.2

I have a Asp.Net MVC Core website that's using public static async Task Main(). For that to work I've set the language version to C# 7.2 (in the properties -> build -> advanced dialog, double checked in the csproj) for both Debug and Release build configurations.
App builds and starts fine in both Debug and Release mode.
Now, I'm trying to publish it to an Azure Website directly from Visual Studio 2017 15.5.2 (with WebDeploy) and I get this:
Program.cs(17,29): Error CS8107: Feature 'async main' is not available
in C# 7.0. Please use language version 7.1 or greater. CSC(0,0): Error
CS5001: Program does not contain a static 'Main' method suitable for
an entry point
In the output window I see it's running C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Roslyn\csc.exe with some flags, probably one of them is wrong?
Anyone know if this is a known issue or I'm doing something wrong?
This appears to be a bug in Visual Studio.
Adding this line to main property group in the .csproj file resolved the issue for me:
<LangVersion>latest</LangVersion>
The issue was also reported here in the ASP.NET Home repository.
Not an answer, per se, but for what it's worth async Main is just syntactic sugar. Behind the scenes Roslyn just adds the standard void Main wrapper construction:
static void Main(object[] args)
{
MainAsync(args).GetAwaiter().GetResult();
}
static async Task MainAsync(object[] args)
{
// your code
}
It's probably not worth your time trying to get the server on the same page C# version-wise, just to save literally three lines of code.

C# - How to use new features from 2017 in 2012

I have both visual studio 2017 and 2012.
My project that I'm creating working only with VS2012 (I really don't know why, there are some additional installations that can be installed only on VS2012).
Here is part of my code.
For example:
enum Colors
{
blue = 0,
green = 1,
red = 2,
}
public Class LED
{
private ComponentLED[] _arr;
public LED()
{
//Here I create the array and fill him with the objects.
}
private ComponentLED GetLEDObjectByColor(string color)
{
//This line don't work
//('System.Enum' does not contain a definition for 'Parse'
int index = (int)( (Colors)Enum.Parse(typeof(Colors), color) );
return _arr[index];
}
}
From what I understood: System.dll don't define some functions.
The only functions I see that works on Enum class are:
Enum.Equals
Enum.ReferenceEquals
So I thought the problem may be in the system.dll it's self.
Maybe you know what is the problem or how to solve it. I would very appreciate you.
Here some information about my current system.dll
Path: C:\Program Files (x86)\Microsoft .NET Micro Framework\v4.2\Assemblies\le\System.dll
Runtime Version: v4.0.30319
Version: 4.2.0.0
and Application information:
Target Framework: .Net Micro FrameWork 4.2 (It's most - can't change it)
The .NET MicroFramework is a very, very slimmed down version of the .NET framework that can run on embedded systems. In order to fit in the tight memory limits for these systems, a lot of features of the .NET base library have been stripped to leave the most important ones only. The correct .NET MicroFramework system library guidance for enums can be found here. And you'll see that it doesn't contain any Parse options.
In the case of your Color enum parsing, you'll probably have to implement your own code to do so based on the underlying int values. That will also make it much faster on these limited systems.
The .NET MicroFramework development slowed down considerably in the past years, but recently a new team has picked up development for it and ported it to Visual Studio 2017. A nice intro can be found on Channel9 and the code to build against 2017 can be tracked in this GitHub issue.
Thank you.
So the optimal solution would be...
private ComponentLED GetLEDObjectByColor(string color)
{
if(Colors.blue.ToString() == color)
return _arr[(int)Colors.blue];
//And continue it until I passed all the enums...
}

Visual Studio Online CI daily builds fail since switching to VS 2015 and using C# 6 Roslyn features

Since switching from VS 2013 to VS 2015 and using some new C# 6 features, our daily builds in Visual Studio Online have begun failing.
The errors on the build are all pointing to the new auto property feature but I assume all new features will cause this.
An example piece of code that causes a failure is using:
public int MyFavouriteNumber { get; set; } = 7;
instead of
private int _myFavouriteNumber = 7;
public int MyFavouriteNumber
{
get { return _myFavouriteNumber; }
set { _myFavouriteNumber = value; }
}
I've had a look around my build configuration, but I can't see anything that relates to C# 6 or Roslyn.
What do I have to change to make my daily builds work again?
Edit
Here's an example error (they're all the same, for auto properties).
Models\Core\Bookings\BookingProduct.cs (29, 0)
Invalid token '=' in class, struct, or interface member declaration
Models\Core\Bookings\BookingProduct.cs (29, 0)
Invalid token '(' in class, struct, or interface member declaration
And here is the offending line:
public virtual IList<BookingPricingAddon> AddonsPricing { get; set; } = new List<BookingPricingAddon>();
TheLethalCoder's comments pointed me in the right direction.
The problem was that all of my projects were using Default as the target Language Version, which is fine if you're using VS 2015, however, my .sln file had the following opening 3 lines:
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2013
VisualStudioVersion = 12.0.31101.0
Apparently, Visual Studio Online uses this to work out which version of MSBuild to use. (It was using 12).
Upgrading my solution to the following:
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
VisualStudioVersion = 14.0.23107.0
allowed Visual Studio Online to see that my IDE was using Roslyn, and therefore used MSBuild 14.
The easiest way I found to upgrade is to click on the solution in Solution Explorer and then going to File > Save As > Solution File and overwrite your existing solution file, it just upgrades the first 3 lines.
My builds are now successful.
I think the same could be achieved by setting the Language Version on each of your projects. This can be done by going to your .csproj files and navigating to:
Properties > Build > Advanced > Language Version > C# 6.0
A good reference about the Default settings in each IDE can be found here.

Setting custom interface written in C++/CLI to null may causes program to crash

I have a custom .Net interface written in C++/CLI:
public interface class IBackgroundExtractor
{
};
In my C# application, the interface is used by:
private IBackgroundExtractor extractor = null;
The above code runs smoothly in my computer (which installed visual studio) but it crashed in another one (without installing visual studio):
AppName: speedtest.exe AppVer: 1.0.0.0 ModName: kernel32.dll
ModVer: 5.1.2600.5512 Offset: 00012aeb
If I remove the null assignment, the code will run in both computer:
private IBackgroundExtractor extractor;
However, I made another interface in pure C#. Setting the interface to null will not make the program to crash:
interface IAnotherInterface
{
}
private IAnotherInterface test = null;
What's wrong in my C++/CLI interface?
[Remarks]
I've create two 'clean' new projects for testing, the first one is a C++/CLI Class Library (New Project -> Visual C++ -> CLR -> Class Library). Add the following lines into the .h file of the library:
public interface class ITest {
};
Then create a Windows Form Application project (Net Project -> Visual C# -> Windows -> Windows Forms Application) and declares an ITest variable in the main function:
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
ITest xxx = null;
}
The program will run in the development computer (installed visual studio) but crash in two other computers. One of the crashed computers is physical machine and the other one is an virtual machine.
I am using Windows XP Pro SP3, Visual Studio 2010 and .Net Framework 4.0.
Have you checked to make sure the right version of the Microsoft Visual C++ Runtime is installed on the target machines? (Your development environment will already have this installed, but no current version of Windows includes this runtime by default).
If you set up your C++/CLI project to use "SAFE" mode, it will not reference the Microsoft Visual c++ runtime at all (just .NET). See this for reference: Pure and Verifiable Code. If you need to do native stuff, then there's a very high chance that you need to have the latest Visual C++ runtime installed. You can pick up the redistributable here: Microsoft Visual C++ 2010 Redistributable Package.
If you want to verify that this is the problem, you can use the sxstrace tool to diagnose these issues (helpful tutorial).
The null assigment is probably not the error but the trigger for the error. This assigment to null is probably first line of code that accesses that the C++/CLI assembly. So before the that null assigment is even executed, the unmanaged part of C++/CLI assembly is initialized. That is probably where the error is occuring.

Categories