Command Line Parser NUGet Package getting simple example program to work - c#

I'm finding this very challenging and I appreciate any help you are willing of offer me.
Currently I'm trying to implement Command Line Parser (https://github.com/commandlineparser/commandline).
I just want to get a basic example application working and I am stuck.
Ultimately I want the following pattern
MyProgram -soureid 1231 -domain alpha
Where I get sourceid and domain as valid variables. sourceid would have the value of 1231 and domain would have the value of "alpha".
This is a C# .net core application (2.3) and I'm running Visual Studio 2017.
Here is the code that I have so far...
using System;
using CommandLine;
namespace Program
{
class Program
{
public static void Main(String[] args)
{
var options = new SomeOptions();
CommandLine.Parser.Default.ParseArguments(args, typeof(SomeOptions));
Console.WriteLine(options.Age);
Console.ReadLine();
}
}
class SomeOptions
{
[Option('n', "name", Required = true)]
public string Name { get; set; }
[Option('a', "age")]
public int Age { get; set; }
}
}
This code does not work. When I pass -n Jason I get this..
CommandLineArgumentParsing 1.0.0
Copyright (C) 2019 CommandLineArgumentParsing
ERROR(S):
Verb '-n' is not recognized.
--help Display this help screen.
--version Display version information.
0
I believe this issue is with this line..
CommandLine.Parser.Default.ParseArguments(args, typeof(SomeOptions));
It seems like this line should be this..
CommandLine.Parser.Default.ParseArguments(args, typeof(options));
However the compiler is complaining that "'options' is a variable but is used like a type"
What am I doing wrong?

I figured this out about two seconds after I asked the question..
Replace..
CommandLine.Parser.Default.ParseArguments(args, typeof(SomeOptions));
With...
Parser.Default.ParseArguments<SomeOptions>(args).WithParsed(parsed => options = parsed);

Related

CS0246 error with OdbcConnection line in C#

Ive been chasing this CS0246 error for a couple hours and am not sure how to resolve it. Given this simple C# code:
using System;
// using Microsoft.Data.Odbc;
using System.Data.Odbc;
namespace dotnetdb
{
class Program
{
static private void SelectRows(string[] args)
{
string passWord = "PWD=password";
string uName = "UID=username";
string dbServer = "SERVER=server";
string dbName = "DATABASE=db";
string driver = "DRIVER={ODBC Driver 13 for SQL Server}"
string connString = // assembled from above
string sql = // sql;
OdbcConnection conn = new OdbcConnection(connString);
conn.Open();
OdbcCommand cmd = new OdbcCommand(sql, conn);
// work with cmd
Console.WriteLine("Didnt kick the bucket!");
}
}
}
The Microsoft stanza on line 2 yields a CS0234 error. The stanza on line 3 (from the Microsoft docs) gives me the CS0246:
Program.cs(20,13): error CS0246: The type or namespace name 'OdbcConnection' could not be found
I use this ODBC connection in go and python all the time but this is my first attempt at using it with C#. Also my first ever C# program. The code above is scraped almost directly from the MS docs - what am I missing? How do I get access to System.Data.Odbc?
Am I trying to run before I learn how to walk with C#?
Note that applications created with dotnet build [console|webapi] build and run just fine.
Thanks!
You need to add it as a reference. Refer to this question on how to add a reference in Visual Studio Code. I also noticed that your program doesn't have a Main() and that'll prevent it from compiling also.
Change this:
static private void SelectRows(string[] args)
to
static void Main(string[] args)
Or call it from Main() like this:
static void Main(string[] args)
{
SelectRows(args);
}
private static void SelectRows(String[] args)
{
...
}
In general references are a piece of compiled code, mostly in .DLL format which you can include in your own project so you can use the methods/code that the reference provides.
For example,
Let's say I have MyMath.dll which was created by somebody and I want to use this method in it.
int Add(int a, int b) {
return a + b;
}
I have to include that MyMath.dll that somebody else created in order to use that Add() method. So when I want to use it, I use something like this.
using MyMath; // MyMath.dll
static void Main(string[] args)
{
MyMath calculator = new MyMath();
int result = calculator.Add(1, 2);
}
If you don't know, Visual Studio has a free community version that's pretty powerful too.

Nunit 3.6.1 testcase with category: category not available in testcontext

I have noticed that when using a testcase instead of a test, the category of the test is not available through the testcontext. So lets view some code:
[TestFixture]
public class FormTests : BrowserTests
{
[TestCase("/some-url/", FormType.ContactForm), Category("form")]
[TestCase("/some-other-url/", FormType.ContactForm), Category("form")]
public void AssertFormIsSubmittable(string url, FormType formType)
{
Browser.OpenPage($"{BaseUrl}{url}", true);
Browser.Action(FormActions.EnterFormFields(formType));
Browser.Action(FormActions.Submit());
var isSuccesfullySubmitted = Browser.Verify(FormState.IsSubmitted());
Assert.IsTrue(isSuccesfullySubmitted);
}
[Test, Category("form")]
public void FunctionToTestIfCategoryIsWorking()
{
Browser.OpenPage($"{BaseUrl}", true);
Browser.Action(FormActions.EnterFormFields(FormType.ContactForm));
Browser.Action(FormActions.Submit());
var isSuccesfullySubmitted = Browser.Verify(FormState.IsSubmitted());
Assert.IsTrue(isSuccesfullySubmitted);
}
}
When running the AssertFormIsSubmittable (with the testcases), within the BrowserTests base class, when I execute:var category = TestContext.CurrentContext.Test.Properties.Get("Category"); the result is null.
When i execute FunctionToTestIfCategoryIsWorking, the same line of code has "form" as a result. That's the expected result. Somehow, when using a TestCase, it doesn't work anymore.
I tried to change the attributes to:
[TestCase("/some-url/", FormType.ContactForm)]
[TestCase("/some-other-url/", FormType.ContactForm)]
[Category("form")]
And:
[Category("form")]
[TestCase("/some-url/", FormType.ContactForm)]
[TestCase("/some-other-url/", FormType.ContactForm)]
And:
[Test, Category("form")]
[TestCase("/some-url/", FormType.ContactForm)]
[TestCase("/some-other-url/", FormType.ContactForm)]
All with the same result. I looked for people experiencing the same issue, but i found no loads. And i looked for known-issues and bugs on https://github.com/nunit/nunit but found nothing that seemed relevant.
I am using Visual Studio 2015 Community, Update 3 on a Windows 7 Enterprise machine. I have the Nunit 3 Test Adapter Visual Studio extension installed.
Is there anything I am missing? Any help is greatly appreciated of course :)

c# compiler issue only supports language versions up to C# 5 [duplicate]

After installing VS 2015, running csc.exe from command line causes this message to be displayed to console:
This compiler is provided as part of the Microsoft (R) .NET Framework,
but only supports language versions up to C# 5, which is no longer the
latest version. For compilers that support newer versions of the C#
programming language, see
http://go.microsoft.com/fwlink/?LinkID=533240
The link redirects to Roslyn's repository at GitHub.
So, is the a way to run "compilers that support newer versions" (Roslyn) from command line?
It sounds like your path is inappropriate, basically. If you open the "Developer Command Prompt for VS2015" you should have $ProgramFiles(x86)$\MSBuild\14.0\bin early in your path - and the csc.exe in there is Roslyn.
I suspect you're running the version in c:\Windows\Microsoft.NET\Framework\4.0.30319 or similar - which is the legacy one, basically.
Roslyn from command line('cmd'), Windows 10 scenario example:
( Note: No need Visual Studio installed, but only the .NET core )
Open 'cmd' and create folder "dotnet-csharp-tools":
D:>mkdir "dotnet-csharp-tools"
Navigate to folder "dotnet-csharp-tools":
D:>cd "dotnet-csharp-tools"
In folder "dotnet-csharp-tools" download 'nuget.exe' latest version from:
https://www.nuget.org/downloads
Check name of the last version of 'Microsoft.CodeDom.Providers.DotNetCompilerPlatform' from:
https://www.nuget.org/packages/Microsoft.CodeDom.Providers.DotNetCompilerPlatform/
For example: 'Microsoft.CodeDom.Providers.DotNetCompilerPlatform -Version 3.6.0'
From 'cmd'(opened folder "dotnet-csharp-tools"), run command:
D:\dotnet-csharp-tools>nuget install Microsoft.CodeDom.Providers.DotNetCompilerPlatform -Version 3.6.0
From 'cmd' navigate to 'D:\dotnet-csharp-tools\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.3.6.0\tools\Roslyn472'(warning : folder name 'Roslyn472' may be different, if is other version)
D:\dotnet-csharp-tools>cd Microsoft.CodeDom.Providers.DotNetCompilerPlatform.3.6.0\tools\Roslyn472
From 'File explorer' find 'csc.exe'(in the current folder 'Roslyn472').
Make copy of 'csc.exe' with name 'csc-roslyn.exe'(name can be whatever).
For 'Windows 10', open:
'Edit system environment variables' -> 'System variables' ->
'path' -> 'Edit' -> 'New' ->
D:\dotnet-csharp-tools\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.3.6.0\tools\Roslyn472
Close and open again 'cmd'(the command prompt).
This 'cmd' restart needed, because 'system environment variables' are edited.
Check if 'csc-roslyn' is recognized by 'cmd' by run command:
csc-roslyn
Create folder 'D:\csharp-projects'(folder name can be whatever)
and create in 'D:\csharp-projects' C# source files, for example:
Vehicle.cs
class Vehicle
{
private string name = "unknown";
private int producedYear = -1;
public Vehicle(string name, int producedYear)
{
this.Name = name;
this.ProducedYear = producedYear;
}
public string Name
{
get { return this.name; }
set { this.name = value; }
}
public int ProducedYear
{
get { return this.producedYear; }
set { this.producedYear = value; }
}
}
Car.cs
class Car : Vehicle
{
private string maker = "unknown";
public Car(string name, int age, string maker)
: base(name, age)
{
this.Maker = maker;
}
public string Maker
{
get { return this.maker; }
set { this.maker = value; }
}
public override string ToString()
{
return $"{this.Name}, {this.ProducedYear}, {this.Maker}";
}
}
Autoservice.cs
using System;
class Autoservice
{
public static void Main()
{
Car car1 = new Car("Ford Taunus", 1971, "Ford");
Car car2 = new Car("Opel Ascona", 1978, "Opel");
Car car3 = new Car("Saab 900", 1984, "Saab");
Console.WriteLine(car1);
Console.WriteLine(car2);
Console.WriteLine(car3);
}
}
Open 'D:\csharp-projects' from 'cmd'(the command prompt) and run command:
csc-roslyn /target:exe /out:Autoservice.exe Vehicle.cs Car.cs Autoservice.cs
Run from 'cmd':
Autoservice.exe
Result should be:
Ford Taunus, 1971, Ford
Opel Ascona, 1978, Opel
Saab 900, 1984, Saab
I suspect the location of the Roslyn compiler moves around a lot based on the Visual Studio you're running.
I was able to find mine by performing a search like this:
cd "\Program Files (x86)"
dir /s csc*.* | findstr Roslyn
My particular csc.exe was located in:
C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin\Roslyn\csc.exe

How can I export my c# code logic (if-else-loops) in to text files (e.g XML) and later import it back and run?

I have these requirements coming from client every week for some new logic or verification. For which I have to code new logic (basically some if-else and loops) and launch a new build for him. I want to avoid it by simply coding my logic in visual studio then writing a utility to export it to XML or something and send it to client via e-mail. He just have to place this file in some appropriate folder and the application will behave considering this logic.
Please suggest some solutions. My platform is C# Asp.Net.
Thanks
Using .NET 4.6 and the NuGetPackage Microsoft.CodeAnalysis.Scripting you could implement a scripting engine to run your c# code residing in a textfile without building an assembly.
Install NuGet Package:
Install-Package Microsoft.CodeAnalysis.Scripting.CSharp
Implement TestClass with some basic C#-Code-Content:
class Program
{
static void Main(string[] args)
{
TestScript();
}
private static async void TestScript()
{
// Code snippet: a class with one string-property.
string codeContent = #" using System;
public class ScriptedClass
{
public string HelloWorld { get; set; }
public ScriptedClass()
{
HelloWorld = ""Hello Roslyn!"";
}
}
new ScriptedClass().HelloWorld";
// Instanciate CSharpScriptEngine
var engine = new CSharpScriptEngine();
// Execute code and return string property (HelloWorld)
var scriptingState = await engine.ExecuteAsync(codeContent);
// Print return value from CSharpScript
Console.WriteLine("Returned from CSharpScript: {0}", scriptingState.ReturnValue);
Console.WriteLine("Press any key to continue.");
Console.ReadKey();
}
}
Implement a ScriptingEngine:
internal sealed class CSharpScriptEngine
{
public async Task<ScriptState<object>> ExecuteAsync(string codeContent)
{
// Add references from calling assembly
ScriptOptions options = ScriptOptions.Default.AddReferences(Assembly.GetExecutingAssembly());
// Run codeContent with given options
return await CSharpScript.RunAsync(codeContent, options);
}
}
Read ScriptCode from textfile:
So basically you could read some csharpcode from a textfile of your choice and run them on the fly:
private static async void TestScript()
{
// Read in script file
string codeContent = File.ReadAllText(#"C:\Temp\CSharpScriptTest.cs");
var engine = new CSharpScriptEngine();
// Run script
var scriptingState = await engine.ExecuteAsync(codeContent);
Console.WriteLine("Returned from CSharpScript: {0}", scriptingState.ReturnValue);
Console.WriteLine("Press any key to continue.");
Console.ReadKey();
}
In case you are wondering how all of this works under the hood, Roslyn will create a so called submission from your script code. A submission is an in memory assembly containing the types generated around your script code, which can be identified among the assemblies in the current AppDomain by a ℛ prefix in the name.
The precise implementation details are not important here (though, for example, scriptcs heavily relies on understanding in detail how Roslyn works to provide its extra features), but it's important to know that submissions can be chained together. When they are chained, variables, methods or classes defined in an earlier submission are available to use in subsequent submissions, creating a feature of a C# REPL (read-evaluate-print loop).
C# and Visual Basic - Use Roslyn to Write a Live Code Analyzer for Your API
Hope it helps

Nancy Self Host doesn't call Module?

I am working on adding Nancy Framework to my C# console application (followed the very short tutorial here and it loads a blank page when I go to http://localhost:1234 so I know it is starting, but it doesn't show my text properly. I have gone over my code various times, but don't see any issues.
I have added both Nancy and Nancy.Hosting.Self to my project.
static void Main(string[] args)
{
var nancyHost = new Nancy.Hosting.Self.NancyHost(new Uri("http://localhost:1234"));
nancyHost.Start();
Console.ReadLine();
nancyHost.Stop();
}
namespace DaemonApp
{
class MainModule : Nancy.NancyModule
{
public MainModule()
{
Get["/"] = parameters =>
{
return "Hello world!";
};
}
}
}
I added some print lines, and it never calls the module when I visit the page. Does anyone have any clue what the issue is?
I didn't make the Module class public, that fixed it instantly =/

Categories

Resources