How to convert between TFM (Target framework moniker) and FrameworkName? - c#

E.g.
netstandard2.0 (from Supported target frameworks) which is used as <TargetFramework> in *.csproj files or as folder name in NuGet packages internal structure,
and
.NETStandard,Version=v2.0 which is accepted by System.Runtime.Versioning.FrameworkName class's constructor or can be a value of TargetFrameworkAttribute.FrameworkName.
How to convert those strings from one form to another? At least one (any) direction.

You can use the source code of NuGet.Frameworks:
Here is the method that converts TFM to FrameworkName:
https://github.com/NuGet/NuGet.Client/blob/dev/src/NuGet.Core/NuGet.Frameworks/NuGetFrameworkFactory.cs#L575
(e.g. netstandard2.0 to .NETStandard,Version=v2.0)
UPDATE #1
The good news is that it is available as a NuGet package:
https://www.nuget.org/packages/NuGet.Frameworks/
Here is a .NET 6 Console Application:
using NuGet.Frameworks;
using System.Runtime.Versioning;
var tfmNetstandard20 = NuGetFramework.ParseFolder("netstandard20");
var fwNetstandard20 = new FrameworkName(tfmNetstandard20.DotNetFrameworkName);
Console.WriteLine(tfmNetstandard20);
Console.WriteLine(fwNetstandard20);
The output will be:
.NETStandard,Version=v2.0
.NETStandard,Version=v2.0

Related

Not able to get this AdaptiveCard.FromJson [duplicate]

I have tried creating an adaptive card, parsing it from json. As mentioned in https://learn.microsoft.com/en-us/adaptive-cards/create/libraries/net#example-parse-from-json, I have installed AdaptiveCards package and tried using that function, but it throws a error like 'AdaptiveCard' does not contain a definition for 'FromJson'.
As there is a Breaking changes from v0.5:
Package renamed from Microsoft.AdaptiveCards to AdaptiveCards
It seems that you have installed Microsoft.AdaptiveCards but AdaptiveCards.
To install AdaptiveCards, please mark Include prerelease checkbox in NuGet package manager:
Apparently the documentation is outdated. The class is named AdaptiveCard now, without the last 's'.
So instead of:
var parseResult = AdaptiveCards.FromJson(card);
Use:
var parseResult = AdaptiveCard.FromJson(card);

EntityFrameworkCore.PostgreSQL Transform point

Is there a way to Transform a point to another SRID using EntityFrameworkCore?
previously I used ST_Transform(ST_GeomFromText(#coord,4326),32661)
My current code looks like this
var postgisGeometry = new PostgisPoint(lon, lat) {SRID = 4326};
The SRID of the coord is 4326 and needs to become 32661
This is done for backwards compatibility reasons and there is no option converting the database to another SRID
Is there a geometry library or a PostGIS EntityFrameworkCore method to transform a point to another SRID
The release version Npgsql.EntityFrameworkCore.PostgreSQL Entity Framework Core provider for PostgreSQL does not support spatial types.
The good news is that spatial types support and support for some spatial operations SQL translations are already available as a pre-release candidate.
If you want to use these libraries, you need to also use the pre-realease candidate version of Entify Framework Core.
First, uninstall your existing entity framework or npgsql packages.
One of the packages needed (GeoAPI) is not available in the standard NuGet source so we are gonna use the myget.org source.
To use it, you need to add a new NuGet source in Visual Studio by going to Tools -> Options -> NuGet Package Manager -> Packages Sources
Create a new source and name it myget.org and use the following URL in the source text field:
https://www.myget.org/F/imageprocessor/api/v3/index.json
Remember to click on update to save the changes, otherwise they are not saved (weird, I know).
To add the required packages, use the Package Manager Console (View -> Other Windows -> Package Manager Console) and select myget.org from the Package Source drop down, then, execute the following commands:
Install-Package Microsoft.EntityFrameworkCore -Version 2.1.0-rc1-final
Install-Package GeoAPI -Version 1.7.5-pre024
Install-Package Npgsql -Version 4.0.0-rc1
Install-Package Npgsql.EntityFrameworkCore.PostgreSQL -Version 2.1.0-rc1
Install-Package Npgsql.EntityFrameworkCore.PostgreSQL.NetTopologySuite -Version 2.1.0-rc1
Once your packages are installed, in your DbContext class, override OnConfiguring to add the UseNetTopologySuite option:
protected override void OnConfiguring(DbContextOptionsBuilder builder)
{
builder.UseNpgsql("Host=localhost;Database=your_database;
Username=your_user;Password=your_password",
o => o.UseNetTopologySuite());
}
To make sure that the extension is supported by your database add the following to your DbContext:
protected override void OnModelCreating(ModelBuilder builder)
{
builder.HasPostgresExtension("postgis");
}
Now you should be able to use PostgreSql spatial types and translate some operations to SQL, (e.g. ST_Area, ST_Contains, ST_As_Text, etc.).
The whole list of supported operations and how to use them in your EF queries is available here: http://www.npgsql.org/efcore/mapping/nts.html#operation-translation
Unfortunately ST_Transform or ST_Project do not seem to be supported as of now, but there is a link in the Website above where you can contact the developers and request them to be added.
In the meantime, you can use GDAL to transform the projection of your coordinates.
Install the package:
Install-Package Gdal.Core -Version 1.0.0
This package provides a multi-platform wrapper for GDAL for .NET core so you need to install the libraries and they should be accessible by your program.
You can find binaries for Windows and Linux here: https://trac.osgeo.org/gdal/wiki/DownloadingGdalBinaries
If you are using Windows you can use the following installer: http://download.osgeo.org/osgeo4w/osgeo4w-setup-x86_64.exe
Just select "Express Desktop Install" and GDAL in the "Select Packages" window.
By default the needed libraries are installed in C:\OSGeo4W64\bin.
You need to add this folder to your system path and restart Visual Studio.
By the way, to convert the coordinates, from all the libraries in C:\OSGeo4W64\bin I think you only need proj.dll so may be you can include this in your project (make sure it is copied to the output of your project) and then it should work and you don't need to install GDAL.
Here is an example of how to use it for the coordinate systems provided in your question:
using System;
using NetTopologySuite.Geometries;
using OSGeo.OSR;
using OSGeo.OGR;
namespace YourNamespace
{
public class SomeLocation
{
public int Id { get; set; }
public string Name { get; set; }
public Point Location { get; } = new Point(40.1234, 1.4321) { SRID = 4326 };
public Point LocationUpsNorth { get { return Wgs84ToWgs84UpsNorth(Location); } }
private static NetTopologySuite.Geometries.Point Wgs84ToWgs84UpsNorth(Point location)
{
if (location.SRID != 4326)
throw new Exception("Unsupported coordinate system: " + location.SRID);
OSGeo.OSR.SpatialReference wgs84Src = new OSGeo.OSR.SpatialReference("");
wgs84Src.ImportFromProj4("+proj=longlat +datum=WGS84 +no_defs");
OSGeo.OSR.SpatialReference stereoNorthPoleDest = new OSGeo.OSR.SpatialReference("");
stereoNorthPoleDest.ImportFromProj4("+proj=stere +lat_0=90 +lat_ts=90 +lon_0=0 +k=0.994 +x_0=2000000 +y_0=2000000 +datum=WGS84 +units=m +no_defs");
OSGeo.OSR.CoordinateTransformation ct = new OSGeo.OSR.CoordinateTransformation(wgs84Src, stereoNorthPoleDest);
double[] point = new double[3];
point[0] = location.X;
point[1] = location.Y;
point[2] = location.Z;
ct.TransformPoint(point);
return new Point(point[0], point[1]);
}
}
}
Result
Input: POINT (40.1234 1.4321)
Output: POINT (9944217.1796359234 -7426244.9918885585)
References:
http://www.npgsql.org/efcore/mapping/nts.html
http://spatialreference.org/ref/epsg/32661/
https://github.com/NetTopologySuite/
https://github.com/NetTopologySuite/ProjNet4GeoAPI/blob/develop/ProjNet.Tests/CoordinateTransformTests.cs
https://gis.stackexchange.com/questions/61541/searching-for-c-code-to-convert-from-utm-to-wgs1984-and-back#61574

Cake Build set full version with DotNetCoreBuild alias

I'm using the ParseReleaseNotes alias in Cake to manage my versioning, worked fine with a project where I patch the assembly info with CreateAssemblyInfo alias.
Now with project not using csproj but project.json I want to achieve the same and assembly info isn't an real option with project.json.
Checking out the DotNetCoreBuild(string, ​DotNetCoreBuildSettings)​ and it's DotNetCoreBuildSettings there only seems to be a way to set parts of the version via it's VersionSuffix property.
Is there an Cake alias / setting to achieve this or is it possible to patch the project.json from Cake?
There is no built in Cake Alias to provide this functionality, but you can make use of a 3rd Party Addin for the MagicChunks project. You can add this into your Cake script by simply doing:
#addin "MagicChunks"
And from there, you can do something like:
var projectToPackagePackageJson = $"{projectToPackage}/project.json";
Information("Updating {0} version -> {1}", projectToPackagePackageJson, nugetVersion);
TransformConfig(projectToPackagePackageJson, projectToPackagePackageJson, new TransformationCollection {
{ "version", nugetVersion }
});
Where TransformConfig is the Method Alias that is added by the MagicChunks addin.
NOTE: This sample was taken from the following project.
There's no built in alias to patch project.json version or parameter for dotnet build to set full version that I know of.
That said as project.json is just "JSON" it's fully possible to patch project.json using a JSON serializer i.e. JSON.Net.
Below I've created an example that references JSON.Net as an addin and then created an UpdateProjectJsonVersion utility function that I can use to patch my project.json using parsed the ReleaseNotes (in this case I've hard coded it for simplicity).
#addin "Newtonsoft.Json"
// fake a release note
ReleaseNotes releaseNotes = new ReleaseNotes(
new Version("3.0.0"),
new [] {"3rd release"},
"3.0.-beta"
);
// project.json to patch
FilePath filePaths = File("./project.json");
// patch project.json
UpdateProjectJsonVersion(releaseNotes.RawVersionLine, filePaths);
// utility function that patches project.json using json.net
public static void UpdateProjectJsonVersion(string version, FilePath projectPath)
{
var project = Newtonsoft.Json.Linq.JObject.Parse(
System.IO.File.ReadAllText(projectPath.FullPath, Encoding.UTF8));
project["version"].Replace(version);
System.IO.File.WriteAllText(projectPath.FullPath, project.ToString(), Encoding.UTF8);
}
So basically just call UpdateProjectJsonVersion before you call the DotNetCoreBuild alias and it'll result in same version as your release notes.

Auto-Include Version # in Label

I am currently including the version number of my publish/release in a label on my application, but have been unable to figure out how to add it so that it auto-updates for every publish. Currently, I am just using a simple text:
//VERSION LABEL
string version = "1.0.0.15 - BETA";
versionLabel.Text = "v" + version;
Is there a way to auto-update the version with each publish?
How about using the assembly version? Depending if you let it auto-uprev, this could save you some time.
var appVersion = Assembly.GetExecutingAssembly().GetName().Version;
versionLabel.Text = String.Format("v{0}", appVersion);
This would be based on the AssemblyInfo's version.
To elaborate on what I mean, if you look at AssemblyInfo.cs, you'll see something like the following:
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
That's essentially saying that if you make it 1.0.* or 1.0.0.* that VS will assign a revision or build and revision, respectfully, for you with every compilation.

Automatically update version number

I would like the version property of my application to be incremented for each build but I'm not sure on how to enable this functionality in Visual Studio (2005/2008). I have tried to specify the AssemblyVersion as 1.0.* but it doesn't get me exactly what I want.
I'm also using a settings file and in earlier attempts when the assembly version changed my settings got reset to the default since the application looked for the settings file in another directory.
I would like to be able to display a version number in the form of 1.1.38 so when a user finds a problem I can log the version they are using as well as tell them to upgrade if they have an old release.
A short explanation of how the versioning works would also be appreciated. When does the build and revision number get incremented?
With the "Built in" stuff, you can't, as using 1.0.* or 1.0.0.* will replace the revision and build numbers with a coded date/timestamp, which is usually also a good way.
For more info, see the Assembly Linker Documentation in the /v tag.
As for automatically incrementing numbers, use the AssemblyInfo Task:
AssemblyInfo Task
This can be configured to automatically increment the build number.
There are 2 Gotchas:
Each of the 4 numbers in the Version string is limited to 65535. This is a Windows Limitation and unlikely to get fixed.
Why are build numbers limited to 65535?
Using with with Subversion requires a small change:
Using MSBuild to generate assembly version info at build time (including SubVersion fix)
Retrieving the Version number is then quite easy:
Version v = Assembly.GetExecutingAssembly().GetName().Version;
string About = string.Format(CultureInfo.InvariantCulture, #"YourApp Version {0}.{1}.{2} (r{3})", v.Major, v.Minor, v.Build, v.Revision);
And, to clarify: In .net or at least in C#, the build is actually the THIRD number, not the fourth one as some people (for example Delphi Developers who are used to Major.Minor.Release.Build) might expect.
In .net, it's Major.Minor.Build.Revision.
VS.NET defaults the Assembly version to 1.0.* and uses the following logic when auto-incrementing: it sets the build part to the number of days since January 1st, 2000, and sets the revision part to the number of seconds since midnight, local time, divided by two. See this MSDN article.
Assembly version is located in an assemblyinfo.vb or assemblyinfo.cs file. From the file:
' Version information for an assembly consists of the following four values:
'
' Major Version
' Minor Version
' Build Number
' Revision
'
' You can specify all the values or you can default the Build and Revision Numbers
' by using the '*' as shown below:
' <Assembly: AssemblyVersion("1.0.*")>
<Assembly: AssemblyVersion("1.0.0.0")>
<Assembly: AssemblyFileVersion("1.0.0.0")>
I have found that it works well to simply display the date of the last build using the following wherever a product version is needed:
System.IO.File.GetLastWriteTime(System.Reflection.Assembly.GetExecutingAssembly().Location).ToString("yyyy.MM.dd.HH.mm.ss")
Rather than attempting to get the version from something like the following:
System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
object[] attributes = assembly.GetCustomAttributes(typeof(System.Reflection.AssemblyFileVersionAttribute), false);
object attribute = null;
if (attributes.Length > 0)
{
attribute = attributes[0] as System.Reflection.AssemblyFileVersionAttribute;
}
[Visual Studio 2017, .csproj properties]
To automatically update your PackageVersion/Version/AssemblyVersion property (or any other property), first, create a new Microsoft.Build.Utilities.Task class that will get your current build number and send back the updated number (I recommend to create a separate project just for that class).
I manually update the major.minor numbers, but let MSBuild to automatically update the build number (1.1.1, 1.1.2, 1.1.3, etc. :)
using Microsoft.Build.Framework;
using System;
using System.Collections.Generic;
using System.Text;
public class RefreshVersion : Microsoft.Build.Utilities.Task
{
[Output]
public string NewVersionString { get; set; }
public string CurrentVersionString { get; set; }
public override bool Execute()
{
Version currentVersion = new Version(CurrentVersionString ?? "1.0.0");
DateTime d = DateTime.Now;
NewVersionString = new Version(currentVersion.Major,
currentVersion.Minor, currentVersion.Build+1).ToString();
return true;
}
}
Then call your recently created Task on MSBuild process adding the next code on your .csproj file:
<Project Sdk="Microsoft.NET.Sdk">
...
<UsingTask TaskName="RefreshVersion" AssemblyFile="$(MSBuildThisFileFullPath)\..\..\<dll path>\BuildTasks.dll" />
<Target Name="RefreshVersionBuildTask" BeforeTargets="Pack" Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
<RefreshVersion CurrentVersionString="$(PackageVersion)">
<Output TaskParameter="NewVersionString" PropertyName="NewVersionString" />
</RefreshVersion>
<Message Text="Updating package version number to $(NewVersionString)..." Importance="high" />
<XmlPoke XmlInputPath="$(MSBuildProjectDirectory)\mustache.website.sdk.dotNET.csproj" Query="/Project/PropertyGroup/PackageVersion" Value="$(NewVersionString)" />
</Target>
...
<PropertyGroup>
..
<PackageVersion>1.1.4</PackageVersion>
..
When picking Visual Studio Pack project option (just change to BeforeTargets="Build" for executing the task before Build) the RefreshVersion code will be triggered to calculate the new version number, and XmlPoke task will update your .csproj property accordingly (yes, it will modify the file).
When working with NuGet libraries, I also send the package to NuGet repository by just adding the next build task to the previous example.
<Message Text="Uploading package to NuGet..." Importance="high" />
<Exec WorkingDirectory="$(MSBuildProjectDirectory)\bin\release" Command="c:\nuget\nuget push *.nupkg -Source https://www.nuget.org/api/v2/package" IgnoreExitCode="true" />
c:\nuget\nuget is where I have the NuGet client (remember to save your NuGet API key by calling nuget SetApiKey <my-api-key> or to include the key on the NuGet push call).
Just in case it helps someone ^_^.
What source control system are you using?
Almost all of them have some form of $ Id $ tag that gets expanded when the file is checked in.
I usually use some form of hackery to display this as the version number.
The other alternative is use to use the date as the build number: 080803-1448
Some time ago I wrote a quick and dirty exe that would update the version #'s in an assemblyinfo.{cs/vb} - I also have used rxfind.exe (a simple and powerful regex-based search replace tool) to do the update from a command line as part of the build process. A couple of other helpfule hints:
separate the assemblyinfo into product parts (company name, version, etc.) and assembly specific parts (assembly name etc.). See here
Also - i use subversion, so I found it helpful to set the build number to subversion revision number thereby making it really easy to always get back to the codebase that generated the assembly (e.g. 1.4.100.1502 was built from revision 1502).
If you want an auto incrementing number that updates each time a compilation is done, you can use VersionUpdater from a pre-build event. Your pre-build event can check the build configuration if you prefer so that the version number will only increment for a Release build (for example).
Here is a handcranked alternative option: This is a quick-and-dirty PowerShell snippet I wrote that gets called from a pre-build step on our Jenkins build system.
It sets the last digit of the AssemblyVersion and AssemblyFileVersion to the value of the BUILD_NUMBER environment variable which is automatically set by the build system.
if (Test-Path env:BUILD_NUMBER) {
Write-Host "Updating AssemblyVersion to $env:BUILD_NUMBER"
# Get the AssemblyInfo.cs
$assemblyInfo = Get-Content -Path .\MyShinyApplication\Properties\AssemblyInfo.cs
# Replace last digit of AssemblyVersion
$assemblyInfo = $assemblyInfo -replace
"^\[assembly: AssemblyVersion\(`"([0-9]+)\.([0-9]+)\.([0-9]+)\.[0-9]+`"\)]",
('[assembly: AssemblyVersion("$1.$2.$3.' + $env:BUILD_NUMBER + '")]')
Write-Host ($assemblyInfo -match '^\[assembly: AssemblyVersion')
# Replace last digit of AssemblyFileVersion
$assemblyInfo = $assemblyInfo -replace
"^\[assembly: AssemblyFileVersion\(`"([0-9]+)\.([0-9]+)\.([0-9]+)\.[0-9]+`"\)]",
('[assembly: AssemblyFileVersion("$1.$2.$3.' + $env:BUILD_NUMBER + '")]')
Write-Host ($assemblyInfo -match '^\[assembly: AssemblyFileVersion')
$assemblyInfo | Set-Content -Path .\MyShinyApplication\Properties\AssemblyInfo.cs -Encoding UTF8
} else {
Write-Warning "BUILD_NUMBER is not set."
}

Categories

Resources