Is C# 7 working in VS 15 Preview 4? - c#

I tried a simple test but it didn't like out variables
As a simple test, I wrote this (perhaps there is something simple wrong with it, but I also had trouble with patterns and with tuples)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
public class Program
{
static void Main(string[] args)
{
Runner runner = new ConsoleApplication2.Runner();
Point p = new ConsoleApplication2.Point();
runner.PrintCoordinates(p);
}
}
public class Point
{
int x = 20;
int y = 50;
public void GetCoordinates(out int a, out int b)
{
a = x;
b = y;
}
}
public class Runner
{
public void PrintCoordinates(Point p)
{
p.GetCoordinates(out int x, out int y);
Console.WriteLine($"({x}, {y})"); // x does not exist in current context
}
}
}

According to this post, where the PrintCoordinates example method comes from:
Note: In Preview 4, the scope rules are more restrictive: Out variables are scoped to the statement they are declared in. Thus, the above example will not work until a later release.
The new tuples suffer from a similar problem, though it seems you can partially work around that with a NuGet download:
Note: Tuples rely on a set of underlying types, that aren’t included in Preview 4. To make the feature work, you can easily get them via NuGet:
Right-click the project in the Solution Explorer and select “Manage NuGet Packages…”
Select the “Browse” tab, check “Include prerelease” and select “nuget.org” as the “Package source”
Search for “System.ValueTuple” and install it.

Related

DLL created in C# does not show members when referenced in Excel-VBA

I am new to C# and am trying to create DLLs with functions that I can use in VBA. I have created a test DLL with simple functions that work fine when referenced in another C# assembly. I am also able to reference the DLL in VBA, and the class created by it (named FunctionsVS) appears in the object browser.
In VBA, I have the following code snippet:
Sub Test1()
Dim z As Integer
Dim func As New FunctionsVS
z = func.Add(4, 5)
End Sub
When I run this sub, I get I get an error message stating
"Class not registered".
I have tried to register the DLL with regsvr32 but I get an error stating:
The module "c:\windows\system32\functionslibframework.dll" was loaded but the entry point DllRegisterServer was not found.
Any advice would be greatly appreciated.
The C# code I used to create the DLL is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FunctionLibVS
{
public class FunctionsVS
{
public int Add(int x, int y)
{
return x + y;
}
public int Multiply(int x, int y)
{
return x * y;
}
}
}

Parse command line arguments/options in C#

I have a console application with some arguments and options so I would like to use a free third-party library.
I have found two libraries for this purpose: NDesk.Options and Command Line Parser Library
Finally I have decided to use Command Line Parser Library because it is clearer using properties so I have downloaded it and added a reference to it.
The problem is that when adding the reference to my .NET Framework 3.5 project I get a warning icon. From the above page where I have downloaded it, it says that compatibility is .NET Framework 3.5+ so I understand 3.5 is compatible, am I right? If not which previous version of it is compatible with .NET Framework 3.5?
You can also use the new Microsoft CommandLineUtils library.
The nuget package is here, but only for .NET Core or Framrwork 4.5.2.
But you can download the source code (only 7 files) and include in your projet. For the Framework 3.5, you have only 2 compilation errors to solve: remove an extra method (using Tasks) and remove one line (in HandleUnexpectedArg).
Nuget: https://www.nuget.org/packages/Microsoft.Extensions.CommandLineUtils
Source: https://github.com/aspnet/Common/tree/dev/shared/Microsoft.Extensions.CommandLineUtils.Sources
To use this library, find here a first sample:
static void Main(string[] args)
{
var cmd = new CommandLineApplication();
var argAdd = cmd.Option("-a | --add <value>", "Add a new item", CommandOptionType.SingleValue);
cmd.OnExecute(() =>
{
Console.WriteLine(argAdd.Value());
return 0;
});
cmd.HelpOption("-? | -h | --help");
cmd.Execute(args);
}
I recommend FluentArgs (see: https://github.com/kutoga/FluentArgs). I think it is very easy to use:
namespace Example
{
using System;
using System.Threading.Tasks;
using FluentArgs;
public static class Program
{
public static Task Main(string[] args)
{
return FluentArgsBuilder.New()
.DefaultConfigsWithAppDescription("An app to convert png files to jpg files.")
.Parameter("-i", "--input")
.WithDescription("Input png file")
.WithExamples("input.png")
.IsRequired()
.Parameter("-o", "--output")
.WithDescription("Output jpg file")
.WithExamples("output.jpg")
.IsRequired()
.Parameter<ushort>("-q", "--quality")
.WithDescription("Quality of the conversion")
.WithValidation(n => n >= 0 && n <= 100)
.IsOptionalWithDefault(50)
.Call(quality => outputFile => inputFile =>
{
/* ... */
Console.WriteLine($"Convert {inputFile} to {outputFile} with quality {quality}...");
/* ... */
return Task.CompletedTask;
})
.ParseAsync(args);
}
}
}
There are many other examples on the github page.
McMaster.Extensions.CommandLineUtils is the best command line parser for c# that I've used. I especially like that it supports subcommands well.
Source code is here: https://github.com/natemcmaster/CommandLineUtils
dotnet add package McMaster.Extensions.CommandLineUtils
This is a simple example of how to use it using attributes:
using System;
using McMaster.Extensions.CommandLineUtils;
public class Program
{
public static int Main(string[] args)
=> CommandLineApplication.Execute<Program>(args);
[Option(Description = "The subject")]
public string Subject { get; } = "world";
[Option(ShortName = "n")]
public int Count { get; } = 1;
private void OnExecute()
{
for (var i = 0; i < Count; i++)
{
Console.WriteLine($"Hello {Subject}!");
}
}
}
Or you could use a builder:
using System;
using McMaster.Extensions.CommandLineUtils;
var app = new CommandLineApplication();
app.HelpOption();
var subject = app.Option("-s|--subject <SUBJECT>", "The subject", CommandOptionType.SingleValue);
subject.DefaultValue = "world";
var repeat = app.Option<int>("-n|--count <N>", "Repeat", CommandOptionType.SingleValue);
repeat.DefaultValue = 1;
app.OnExecute(() =>
{
for (var i = 0; i < repeat.ParsedValue; i++)
{
Console.WriteLine($"Hello {subject.Value()}!");
}
});
return app.Execute(args);
Microsoft have also been working on a command line parser: https://github.com/dotnet/command-line-api but it's been in preview for ages.
System.CommandLine might do the trick. Though as of November 2022 it is still in beta.
I suppose the .NET team is going to include it in some upcoming .NET framework release.
https://github.com/dotnet/runtime/issues/68578
https://www.nuget.org/packages/System.CommandLine
If you're looking for a third-party library to help you parse command-line arguments and options in C#, you might want to check out the TreeBasedCli library. It is a C# library designed to simplify the process of creating command-line interfaces (CLIs) with nested subcommands, and offers a number of benefits for both developers and users.
One of the key features of TreeBasedCli is its modular structure, which allows you to easily organize and structure your CLI's functionality using leaf and branch commands. Leaf commands represent specific actions that can be performed, and are implemented as individual classes with their own command definition, input parser, and asynchronous handler. Branch commands, on the other hand, represent a group of subcommands and do not have an associated action. This allows you to easily create complex CLIs with multiple levels of nesting.
Another benefit of TreeBasedCli is its support for asynchronous command execution. It also includes a lightweight Dependency Injection (DI) interface, allowing you to use your preferred method of DI type resolution.
public class CreateCatCommand :
LeafCommand<
CreateCatCommand.Arguments,
CreateCatCommand.Parser,
CreateCatCommand.Handler>
{
private const string NameLabel = "--name";
public CreateCatCommand() : base(
label: "create-cat",
description: new[]
{
"Prints out a cat."
},
options: new[]
{
new CommandOption(
label: NameLabel,
description: new[]
{
"Required. The name of the cat to print."
}
),
})
{ }
public record Arguments(string CatName) : IParsedCommandArguments;
public class Parser : ICommandArgumentParser<Arguments>
{
public IParseResult<Arguments> Parse(CommandArguments arguments)
{
string name = arguments.GetArgument(NameLabel).ExpectedAsSingleValue();
var result = new Arguments(
CatName: name
);
return new SuccessfulParseResult<Arguments>(result);
}
}
public class Handler : ILeafCommandHandler<Arguments>
{
private readonly IUserInterface userInterface;
public Handler(IUserInterface userInterface)
{
this.userInterface = userInterface;
}
public Task HandleAsync(Arguments arguments, LeafCommand _)
{
this.userInterface.WriteLine($"I am a cat 😸 with the name {arguments.CatName}!");
return Task.CompletedTask;
}
}
}

Error 1 The name 'WriteAt' does not exist in the current context

I'm trying to write a game in C# that runs on my cmd on Windows and I need to be able to write to any part of the box to do that. I found WriteAt used extensively for this purpose, however it doesn't seem to work in VS 2010. I get the error: "The name WriteAt does not exist in the current context"
I have the default:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
at the top of my code. So why can't I use WriteAt?
Here's my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace GamePCL
{
class Program
{
static void Main(string[] args)
{
Console.Clear();
for (int x = 0; x < 24; x += 2)
{
WriteAt("█", x, 0);
WriteAt("█", x, 30);
}
}
}
}
When you call a method without an object or type prefix, as in this case WriteAt() (as opposed to for example Console.WriteLine(), which is called on the Console type), the method must exist in the current context, i.e. in the current class.
You copied that code from MSDN without copying the relevant method:
protected static void WriteAt(string s, int x, int y)
{
try
{
Console.SetCursorPosition(origCol+x, origRow+y);
Console.Write(s);
}
catch (ArgumentOutOfRangeException e)
{
Console.Clear();
Console.WriteLine(e.Message);
}
}

Scope Resolution Operator in c# to access global variable?

I have a Program in C++
int x=100; //Global declaration
main()
{
int x=200;
{
int y;
y=x;
cout<<"Inner Block"<<endl;
cout<<x<<endl;
cout<<y<<endl
cout<<::x<<endl;
}
cout<<"Outer Block"<<"\n";
cout<<x<<"\n";
cout<<::x;
}
Output of this program is:
Inner Block
200
200
100
Outer Block
200
100
I want to try similar thing in c# but when I type ::x,i gives me error...
Please help
What I have tried is
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CAScopeResolution_Operator
{
class Program
{
static int x = 100;
static void Main(string[] args)
{
int x = 200;
{
int y;
y = x;
Console.WriteLine("Inner Block");
Console.WriteLine(x);
Console.WriteLine(y);
Console.WriteLine(Program.x);
}
Console.WriteLine("Outer Block");
Console.WriteLine(x);
Console.WriteLine(Program.x);
Console.ReadLine();
}
}
}
I have declared static x,but I dont think this is the solution to have similar code in c#... Please help
As C# does not deal with global variables as C++ does, the :: has a different meaning. It is about namespaces here, as you can identify each member by the class it belongs to.
So if you have namespaces and/or types that share an identifier but in different namespace, you can identify them using ::-operator.
using colAlias = System.Collections;
namespace System
{
class TestClass
{
static void Main()
{
// Searching the alias:
colAlias::Hashtable test = new colAlias::Hashtable();
// Add items to the table.
test.Add("A", "1");
test.Add("B", "2");
test.Add("C", "3");
foreach (string name in test.Keys)
{
// Searching the global namespace:
global::System.Console.WriteLine(name + " " + test[name]);
}
}
}
}
generates this
A 1
B 2
C 3
See here for MSDN reference.

Mapping C# classes to Lua functions via dll

In my "LuaTest" namespace I have a class called "Planet". The C# code reads like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LuaInterface;
namespace LuaTest
{
public class Planet
{
public Planet(string name)
{
this.Name = name;
}
public Planet() : this("NoName") { }
public string Name
{
get;
private set;
}
public void printName()
{
Console.WriteLine("This planet's name is {0}", Name);
}
}
}
Then I built LuaTest.dll and copied this file to the same folder where my Lua script is saved. In the Lua script I wrote:
--define Path for required dlls
package.cpath = package.cpath .. ";" .. "/?.dll"
package.path = package.path .. ";" .. "/?.dll/"
require 'luanet'
luanet.load_assembly("LuaTest")
local Planet = luanet.import_type("LuaTest.Planet")
local planet = Planet("Earth")
planet.printName()
However, this piece of code does not work. Lua interpreter throws this error:
lua: dllTest.lua:7: attempt to call local 'Planet' (a nil value)
I suspect that my LuaTest assembly is not loaded at all. Could anyone point out where I did wrong? I would very much appreciate it, since I've been stuck by this problem for days.
Also it might be helpful to add that my LuaInterface.dll is the rebuilt version in .NET4.0 environment.
So I spent a LOT of time similarly. What really drove me bonkers was trying to get Enums working. Eventually I ditched my project for a very simplified console application, very similar (ironically also named 'LuaTest').
Edit: I've noted that the initial "luanet.load_assembly("LuaTest")" appears superfluous. Works with it, or surprisingly without it.
Another Edit: As in my badly edited comment below, when I removed:
print(luanet.LuaTest.Pointless)
It all stopped working (LuaTest.Pointless became nil). But adding the luanet.load_assembly("LuaTest") then makes it work. It may be that there is some sort of odd implicit load in the print or in just expressing they type. Very Strange(tm).
In any case, it seems to work for me (note: after a lot of experimentation). I don't know why yours is failing, I don't note any real difference, but here's all my code in case someone else can spot the critical difference:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LuaInterface;
namespace LuaTest
{
public class Program
{
static void Main(string[] args)
{
Lua lua = new Lua();
lua.DoFile("test.lua");
}
public int some_member = 3;
}
public class Pointless
{
public enum AnEnum
{
One,
Two,
Three
};
public static string aStaticInt = "This is static.";
public double i;
public string n = "Nice";
public AnEnum oneEnumVal = AnEnum.One;
private AnEnum twoEnumVal = AnEnum.Two;
private string very;
public Pointless(string HowPointLess)
{
i = 3.13;
very = HowPointLess;
}
public class MoreInnerClass
{
public string message = "More, please!";
}
public void Compare(AnEnum inputEnum)
{
if (inputEnum == AnEnum.Three)
Console.WriteLine("Match.");
else
Console.WriteLine("Fail match.");
}
}
}
and test.lua:
luanet.load_assembly("LuaTest")
--Pointless is a class in LuaTest assembly
local Pointless = luanet.import_type("LuaTest.Pointless")
print(Pointless)
--Gives 'ProxyType(LuaTest.Pointless): 46104728
print(Pointless.aStaticInt)
--'This is static.'
--Fails if not static, as we expect
--Instantiate a 'Pointless'.
local p = Pointless("Very")
print(p)
--Gives 'LuaTest.Pointless: 12289376'
--Now we can get at the items inside the Pointless
--class (well, this instance, anyway).
local e = p.AnEnum;
print(e)
--ProxyType(LuaTest.Pointless+AnEnum): 23452342
--I guess the + must designate that it is a type?
print(p.i)
--3.14
print(p.oneEnumVal)
--Gives 'One: 0'
print(p.twoEnumVal)
--Gives 'twoEnumVal'... private
--behaves very differently.
print(e.Two:ToString())
--Gives 'Two'
local more = p.MoreInnerClass()
print(more.message)
--'More, Please!'
--create an enum value here in the script,
--pass it back for a comparison to
--the enum.
local anotherEnumVal = p.AnEnum.Three
p:Compare(anotherEnumVal)
--outputs 'Match'
Having spent the last several days working on a project that required this exact functionality from LuaInterface, I stumbled across a piece of Lua code that turned out to be the perfect solution (see Reference 1). Whilst searching for this solution, I noticed this question and figured I'd drop my two cents in.
To apply this solution, I merely run the CLRPackage code while initializing my LuaInterface Lua object. However, the require statement works just as well.
The code provided in reference 1 allows the use of import statements, similar to C# using statements. Once an assembly is imported, its members are accessible in the global namespace. The import statement eliminates the need to use load_assembly or import_type (except in situations in which you need to use members of the same name from different assemblies. In this scenario, import_type would be used similar to C# using NewTypeName = Assembly.OldTypeName).
import "LuaTest"
planet = Planet("Earth")
planet:printName()
This package also works great with enums!
Further information regarding the use of this package may be found at Reference 2.
Hope this helps!
Reference 1: https://github.com/stevedonovan/MonoLuaInterface/blob/master/bin/lua/CLRPackage.lua
Reference 2: http://penlight.luaforge.net/project-pages/penlight/packages/LuaInterface/
I spent some time in binding C# dll to lua. Your posts were helpful but something was missing. The following solution should work:
(Make sure to change your compiler to .NET Framework 3.5 or lower!)
Planet.dll:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Planets
{
public class Planet
{
private string name;
public string Name
{
get { return name; }
set { this.name = value; }
}
private float diameter;
public float Diameter
{
get { return diameter; }
set { this.diameter = value; }
}
private int cntContinents;
public int CntContinents
{
get { return cntContinents; }
set { this.cntContinents = value; }
}
public Planet()
{
Console.WriteLine("Constructor 1");
this.name = "nameless";
this.diameter = 0;
this.cntContinents = 0;
}
public Planet(string n, float d, int k)
{
Console.WriteLine("Constructor 2");
this.name = n;
this.diameter = d;
this.cntContinents = k;
}
public void testMethod()
{
Console.WriteLine("This is a Test!");
}
}
}
Use the code above, paste it into your class library project and compile it with .NET smaller or equal 3.5.
The location of the generated DLL needs to be known by the lua enviroment. Paste it e.g at "clibs"-folder or another well known lua system path. Then try to use the following lua example. It should work.
Test1.lua: (Option 1 with "import" from CLRPackage)
require "luanet"
require "CLRPackage"
import "Planet"
local PlanetClass = luanet.import_type("Planets.Planet")
print(PlanetClass)
local PlanetObject1 = PlanetClass()
print(PlanetObject1)
local PlanetObject2 = PlanetClass("Earth",6371.00*2,7)
print(PlanetObject1.Name)
PlanetObject1.Name = 'Mars'
print(PlanetObject1.Name)
print( "Planet " ..
PlanetObject2.Name ..
" is my home planet. Its diameter is round about " ..
PlanetObject2.Diameter .. "km." ..
" Our neighour is " ..
PlanetObject1.Name)
Test2.lua: (Option 2 with "load_assembly")
require "luanet"
require "CLRPackage"
luanet.load_assembly("Planet")
local PlanetClass = luanet.import_type("Planets.Planet")
print(PlanetClass)
local PlanetObject1 = PlanetClass()
print(PlanetObject1)
local PlanetObject2 = PlanetClass("Earth",6371.00*2,7)
print(PlanetObject1.Name)
PlanetObject1.Name = 'Mars'
print(PlanetObject1.Name)
print( "Planet " ..
PlanetObject2.Name ..
" is my home planet. Its diameter is round about " ..
PlanetObject2.Diameter .. "km." ..
" Our neighour is " ..
PlanetObject1.Name)
In both cases the console output will look like this:
ProxyType(Planets.Planet): 18643596
Constructor 1
Planets.Planet: 33574638
Constructor 2
nameless
Mars
Planet Earth is my home planet. Its diameter is round about 12742km. Our neighbour is Mars
I hope its helps some of you.
Edit 1:
by the way, a method call from lua looks like this:
PlanetObject1:testMethod()
PlanetObject2:testMethod()
Edit 2:
I found different dll's whitch needed to be handled differently. One needed the "import"-function and another needed the "load_assembly"-function. Keep that maybe in mind!

Categories