I want to learn to use the c# build tools to build desktop applications from the command line.
I just downloaded the .Net SDK from here
and managed to run my first console application following the tutorial from here
However, if i want to build a wpf application, it says type or namespace "System.Windows" is not available and there is a reference to an assembly possibly missing.
My project file looks like this
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
My C# file looks like this:
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Ink;
public class Sketchpad : Application {
[STAThread]
public static void Main(){
var app = new Sketchpad();
Window root = new Window();
InkCanvas inkCanvas1 = new InkCanvas();
root.Title = "Skortchpard";
root.ResizeMode = ResizeMode.CanResizeWithGrip;
inkCanvas1.Background = Brushes.DarkSlateBlue;
inkCanvas1.DefaultDrawingAttributes.Color = Colors.SpringGreen;
inkCanvas1.DefaultDrawingAttributes.Height = 10;
inkCanvas1.DefaultDrawingAttributes.Width = 10;
root.Content = inkCanvas1;
root.Show();
app.MainWindow = root;
app.Run();
}
}
How do I need to change the project file to include the necessary assemblies?
How would it be for a Windows Forms-Application?
What tutorial should you read, in order to compile C# programs from the console?
You need to add the line
<UseWPF>True</UseWPF>
anywhere inside the <PropertyGroup> section of your .csproj file. That (implicitly) adds the System.Windows references to your project. (As such, this is kind of a special case, as most other external references would be added via <ProjectReference> entries).
Oh, and also change
<TargetFramework>net7.0</TargetFramework>
to
<TargetFramework>net7.0-windows</TargetFramework>
because WPF is windows-specific.
You can use command line to create a wpf project using dotnet new rather like that tutorial. Except of course with some parameters tell it you want a wpf app and what language.
https://learn.microsoft.com/en-us/dotnet/core/tools/dotnet-new
With .net 7 you can do:
dotnet new wpf --name "MyNewApp" -lang "C#"
That will create a folder called MyNewApp with a MyNewApp.csproj within whichever folder you're currently "in" with your command line.
The csproj has the correct settings for a wpf app.
This is what I get when I do that.
If I open in visual studio I can hit f5 and it spins up fine
Related
I have a test harness in a project that was created in VS2013 (Framework 4.5). To test things out for VS2019, I added a local function (from C# 7). The project still targets 4.5, yet it compiles and runs without any errors. This isn't good - I want people to be able to go and edit in VS2013 if that's the version they got. Tell me I'm missing something simple here.
static void Main(string[] args)
{
string LocalFunction()
{
return "yeah, im local, dude.";
}
Console.WriteLine(LocalFunction());
Console.ReadKey();
}
Do you want to force to use the same language features? In that case, set the LangVersion property in your csproj file (or build property file) that MSBuild will recognize. For example, this will limit the language feature to C# 6 (even for .NET 5 projects):
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<LangVersion>6</LangVersion>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
</Project>
Then, you will see the compile time error:
Refer to official doc for all values you could put there.
I need to start a web application, self hosted with Kestrel, from a console project. The web application is in a library.
I have a solution with two projects, i.e.:
--APP.Console.exe (a dotnet core 3.1 console application)
--APP.WebSite (a dotnet core 3.1 class library)
The App.Console, calls an APP.WebSite singleton method to start the web app.
The solution compiles, but when the website starts, I got over 50 errors like this scren shots:
If I modify the APP.WebSite into a console Application, it regulary starts with no errors.
Where I'm wrong?
EDIT1:
Start console app:
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
Test.Start.StartApp();
Console.ReadKey();
}
StartApp static method:
public static void StartApp()
{
var s = Directory.GetCurrentDirectory();
//activate web hosting here
var host = new WebHostBuilder()
.UseKestrel(o =>
{
o.AllowSynchronousIO = true;
o.ListenAnyIP(5000);
//o.ListenLocalhost(5000);
})
.UseWebRoot(s + "/Web/wwwroot")
//.UseContentRoot(s+"/Web/wwwroot")
.UseStartup<StartUpWeb>()
.Build();
host.Start();
}
In Web/wwwroot there all client files
EDIT2: Solution folders:
I was able to achieve what you want using .NET Core 3.1.1, but there is a few things I had to do.
First your folder structure is wrong.
The correct folder structure is this:
Notice I moved the wwwroot folder to a folder called Web... ONLY the wwwroot
Second The correct way to "convert" a asp.net core website to a class library is here:
So basically create a asp.net core web application project then right click properties and change the output type.
Third starting from a Class Library project
If you are starting from .NET Core Class Library Project then you can open the csproj file and change a few things :
This is how my csproj file looks like now:
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<ApplicationIcon />
<OutputType>Library</OutputType>
<StartupObject />
<EnableDefaultContentItems>true</EnableDefaultContentItems>
</PropertyGroup>
<ItemGroup>
<Content Include="Web\wwwroot\**">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
</Project>
So basically change the Sdk, the OutputType, EnableDefaultContentItems and add an ItemGroup to force copy all the content files for wwwroot.
Finally
Your code should look this:
public static void StartApp(string environment)//notice the new parameter
{
var s = Directory.GetCurrentDirectory();
//activate web hosting here
var host = new WebHostBuilder()
.UseEnvironment(environment)//set the environment for debugging mostly
.UseKestrel(o =>
{
o.AllowSynchronousIO = true;
o.ListenAnyIP(5000);
//o.ListenLocalhost(5000);
})
.UseWebRoot(s + "\\Web\\wwwroot")//notice the correct path to client files
//.UseContentRoot(s+"/Web/wwwroot")
.UseStartup<StartUpWeb>()
.Build();
host.Start();
}
And your entry point in your Console App:
static void Main(string[] args)
{
System.Console.WriteLine("Hello World!");
Test.Start.StartApp("Development");//pass the environment for debugging
System.Console.ReadKey();
}
I made a few changes to your code.
Specify the environment to debug and load configuration files etc....
Also specify the WebRoot to find stuff like client files and views(even though they are compiled it still needs a webroot).
Here is the result hooraay!!
You got it!
The very problem was this configuration line:
<Project Sdk="Microsoft.NET.Sdk.Web">
Thank you Jonathan
I know that all Dot Net Core projects get marked with a package version tag that appears in the CSProj file, like this:
<PropertyGroup>
<TargetFramework>netcoreapp2.0</TargetFramework>
<StartupObject>MY.Program</StartupObject>
<TypeScriptToolsVersion>2.5</TypeScriptToolsVersion>
<AssemblyName>MY.PCA</AssemblyName>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Version>1.2.0</Version>
</PropertyGroup>
Is there a way to get access to that Version number field at Runtime? Namely in the Startup routines found in Startup.cs?
Add Microsoft.Extensions.PlatformAbstractions package as dependency and then use ApplicationEnvironment.ApplicationVersion property to get the version:
// using using Microsoft.Extensions.PlatformAbstractions;
ApplicationEnvironment app = PlatformServices.Default.Application;
string version = app.ApplicationVersion;
Assembly.GetEntryAssembly().GetCustomAttribute<AssemblyInformationalVersionAttribute>().InformationalVersion;
This one is giving me such a headache. We used to put things in the project properties under [assembly: AssemblyVersion("1.0.0.0")] I am totally fine with change so I do not care where it is. I understand they are going to a new standard for versions as well, also totally fine.
Plenty of documents out there point to the project.json file which is clearly a waste as this is no longer a legit file. More recent say add the following to your .csproj file:
<PropertyGroup>
<VersionPrefix>1.2.3</VersionPrefix>
<VersionSuffix>alpha</VersionSuffix>
</PropertyGroup>
Also a total waste. Only because I can not seem to be able to read it. The following always gives me 1.0.0.0.
PlatformServices.Default.Application.ApplicationVersion
Not to mention when I right-click in File Explorer and click Properties, then Details tab also always says 1.0.0.0.
So, how I can set the version of each assembly within my solution AND then read them later at runtime?
On method is to set either of these values in your project file:
<PropertyGroup>
<Version>1.3.5.7</Version>
<FileVersion>2.4.6.8</FileVersion>
</PropertyGroup>
And read them like this:
var fileVersion = Assembly.GetEntryAssembly()
.GetCustomAttribute<AssemblyFileVersionAttribute>()
.Version;
var informationalVersion = Assembly.GetEntryAssembly()
.GetCustomAttribute<AssemblyInformationalVersionAttribute>()
.InformationalVersion;
It's worth noting that setting these value in the .csproj file does autogenerate (so don't try to edit it) a file similar to the legacy AssemblyInfo.cs containing something like this:
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Reflection;
//snip
[assembly: System.Reflection.AssemblyFileVersionAttribute("2.4.6.8")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.2.3")]
// Generated by the MSBuild WriteCodeFragment class.
Turns out this started working when .Net Core 2.0 came out. When you right-click on the Project and then click Properties there is a UI for it as seen below:
The Package Version, Assembly Version and Assembly File Version correspond to the Version, AssemblyVersion and FileVersion settings in the .csproj file respectively:
<PropertyGroup>
<Version>1.1.0</Version>
<AssemblyVersion>1.1.0.9</AssemblyVersion>
<FileVersion>1.1.0.9</FileVersion>
</PropertyGroup>
I then created a utility method in each project of my solution that does the following:
public static VersionInformationModel GetVersionInformation() {
var Result = new VersionInformationModel {
Version = Assembly.GetExecutingAssembly().GetName().Version.ToString(),
BuildDate = System.IO.File.GetLastWriteTime(Assembly.GetExecutingAssembly().Location),
Configuration = Assembly.GetExecutingAssembly().GetCustomAttribute<AssemblyConfigurationAttribute>().Configuration,
TargetFramework = Assembly.GetExecutingAssembly().GetCustomAttribute<System.Runtime.Versioning.TargetFrameworkAttribute>().FrameworkName,
};
return Result;
}
So on an admin page of my site, I can know when version and other particulars about each project as it stands on whatever server I am looking at.
I want to use novacode-docx in cs-script. how can I give correct reference to the assembly. I tried following but didn't work around the assembly reference missing.
//css_reference D:\lib\DocX.dll;
using System;
using System.Diagnostics;
using System.Windows.Forms;
class Script
{
[STAThread]
static public void Main(string[] args)
{
using (DocX doc = DocX.Create(#"C:\Users\name\Desktop\test.docx"))
{
doc.PageLayout.Orientation = Orientation.Landscape;
var table = doc.AddTable(12, 2);
doc.InsertTable(table);
doc.Save();
}
}
}
You cannot reference an explicit path like that for presumably security reasons. The assembly must be placed in one of the following locations and referenced as //css_reference DocX.dll;
File location The assembly to be loaded must be from one of the following locations (the order indicates the assembly search
priority):
the same directory where the script is
Default Script Library directory Script Library (%CSSCRIPT_DIR%\Lib)
Custom Script Library directory(s) (specified in the configuration console SearchDirs)
GAC
See here for more info: http://www.csscript.net/help/using_.net_assemblies.html
Drop the Docx.dll into the same folder as where the cs script is and try this:
//css_reference DocX.dll;
using System;
using System.Diagnostics;
using System.Windows.Forms;
using Novacode;
class Script
{
[STAThread]
static public void Main(string[] args)
{
using (DocX doc = DocX.Create(#"C:\Users\name\Desktop\test.docx"))
{
doc.PageLayout.Orientation = Orientation.Landscape;
var table = doc.AddTable(12, 2);
doc.InsertTable(table);
doc.Save();
}
}
}
DocX seems to be available on NuGet, so I would heavily recommend fetching the dependency from there rather than having it in a file on your local system. (This helps ensuring repeatable builds, should you share this code with others, with packaging your application, and it will also make it easier to upgrade DocX if a new version is released.)
If you're using Visual Studio, you can right-click the project in Solution Explorer and choose "Manage NuGet Packages..." to open a dialog that helps you install the package, or you can open Package Manager Console and enter Install-Package DocX.
If you're building on .NET Core without Visual Studio, just add "DocX": "1.0.0.19" to the dependencies node of your project.json.
When the package is installed, you can just do using DocX; like with any other namespace import.
Have you read this link
To add a reference in Visual C#
In Solution Explorer, right-click the project node and click Add Reference.
In the Add Reference dialog box, select the tab indicating the type of component you want to reference.
Select the components you want to reference, and then click OK.
Without VS:
Go to the csproj file there is a <ItemGroup> where references can be added:
<ItemGroup>
<Content Include="libs\...">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
...
There you can add libs.
both required in order to use docx.
//css_reference DocX.dll;
using Novacode;
You can also give reference to any place like
//css_reference D:\lib\DocX.dll;
using Novacode;