How to load .NET 6 project in a .NET 6 console application - msbuild

I am attempting to load a .NET 6 project (SDK Style) in a .NET 6 console application. My entire project is fairly simple - it actually attempts to load its own .csproj file when it runs from the default output folder:
using Microsoft.Build.Evaluation;
namespace ProjLoading
{
internal class Program
{
static void Main(string[] args)
{
var projectLocation = "../../../ProjLoading.csproj";
var project = new Project(projectLocation, null, null, new ProjectCollection());
}
}
}
I am using the following nuget packages:
Microsoft.Build (17.2.0)
Microsoft.Build.Utilities.Core (17.2.0)
When I run the code, I get the following exception:
Microsoft.Build.Exceptions.InvalidProjectFileException: 'The SDK 'Microsoft.NET.Sdk' specified could not be found. C:\Users\vchel\source\repos\ProjLoading\ProjLoading\ProjLoading.csproj'
This exception was originally thrown at this call stack:
Microsoft.Build.Shared.ProjectErrorUtilities.ThrowInvalidProject(string, Microsoft.Build.Shared.IElementLocation, string, object[])
Microsoft.Build.Evaluation.Evaluator<P, I, M, D>.ExpandAndLoadImportsFromUnescapedImportExpressionConditioned(string, Microsoft.Build.Construction.ProjectImportElement, out System.Collections.Generic.List<Microsoft.Build.Construction.ProjectRootElement>, out Microsoft.Build.BackEnd.SdkResolution.SdkResult, bool)
Microsoft.Build.Evaluation.Evaluator<P, I, M, D>.ExpandAndLoadImports(string, Microsoft.Build.Construction.ProjectImportElement, out Microsoft.Build.BackEnd.SdkResolution.SdkResult)
Microsoft.Build.Evaluation.Evaluator<P, I, M, D>.EvaluateImportElement(string, Microsoft.Build.Construction.ProjectImportElement)
Microsoft.Build.Evaluation.Evaluator<P, I, M, D>.PerformDepthFirstPass(Microsoft.Build.Construction.ProjectRootElement)
Microsoft.Build.Evaluation.Evaluator<P, I, M, D>.Evaluate()
Microsoft.Build.Evaluation.Project.ProjectImpl.Reevaluate(Microsoft.Build.BackEnd.Logging.ILoggingService, Microsoft.Build.Evaluation.ProjectLoadSettings, Microsoft.Build.Evaluation.Context.EvaluationContext)
Microsoft.Build.Evaluation.Project.ProjectImpl.ReevaluateIfNecessary(Microsoft.Build.BackEnd.Logging.ILoggingService, Microsoft.Build.Evaluation.ProjectLoadSettings, Microsoft.Build.Evaluation.Context.EvaluationContext)
Microsoft.Build.Evaluation.Project.ProjectImpl.Initialize(System.Collections.Generic.IDictionary<string, string>, string, string, Microsoft.Build.Evaluation.ProjectLoadSettings, Microsoft.Build.Evaluation.Context.EvaluationContext)
Microsoft.Build.Evaluation.Project.Project(string, System.Collections.Generic.IDictionary<string, string>, string, string, Microsoft.Build.Evaluation.ProjectCollection, Microsoft.Build.Evaluation.ProjectLoadSettings, Microsoft.Build.Evaluation.Context.EvaluationContext, Microsoft.Build.FileSystem.IDirectoryCacheFactory)
...
[Call Stack Truncated]
I am building/running this console application from Visual Studio 2022 (17.2.2).
How can I solve this problem?

I don't understand why, but I ran across this solution and it has solved the problem:
https://blog.rsuter.com/missing-sdk-when-using-the-microsoft-build-package-in-net-core/
In case the link dies in the future, my full project now sets the environment variable MSBUILD_EXE_PATH to the latest version of msbuild as shown in the following code:
using Microsoft.Build.Evaluation;
using System.Diagnostics;
using System.Text.RegularExpressions;
namespace ProjLoading
{
internal class Program
{
static void Main(string[] args)
{
var startInfo = new ProcessStartInfo("dotnet", "--list-sdks")
{
RedirectStandardOutput = true
};
var process = Process.Start(startInfo);
process.WaitForExit(1000);
var output = process.StandardOutput.ReadToEnd();
var sdkPaths = Regex.Matches(output, "([0-9]+.[0-9]+.[0-9]+) \\[(.*)\\]")
.OfType<Match>()
.Select(m => System.IO.Path.Combine(m.Groups[2].Value, m.Groups[1].Value, "MSBuild.dll"));
var sdkPath = sdkPaths.Last();
Environment.SetEnvironmentVariable("MSBUILD_EXE_PATH", sdkPath);
var projectLocation = "../../../ProjLoading.csproj";
var project = new Project(projectLocation, null, null, new ProjectCollection());
}
}
}

Related

Klint and spotless: com.pinterest.ktlint.core.ParseException: Expecting a parameter declaration

I'm getting weird exception when trying to run ./gradlew spotlessApply on my project in Kotlin.
Class causing the problem:
import io.realm.RealmObject
import io.realm.annotations.PrimaryKey
open class CurrentFluttering(
#PrimaryKey var id: Long = 0,
var currentCoinsHeap: Int = 0,
var currentEarnedCoins: Int = 0,
var startTime: Long = 0,
var pauseTime: Long = 0,
var time: Long = 0,
var firstCycle: Boolean = true,
var inBackground: Boolean = false,
var currentMissedCoins: Int = 0,
var isPaused: Boolean = false,
) : RealmObject()
Stack trace:
> Task :spotlessKotlin FAILED
Step 'ktlint' found problem in 'app/src/main/java/com/cfhero/android/model/state/CurrentFluttering.kt':
Expecting a parameter declaration
com.pinterest.ktlint.core.ParseException: Expecting a parameter declaration
at com.pinterest.ktlint.core.KtLint.format(KtLint.kt:357)
at sun.reflect.GeneratedMethodAccessor35.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.diffplug.spotless.kotlin.KtLintStep$State.lambda$createFormat$1(KtLintStep.java:173)
at com.diffplug.spotless.FormatterFunc.apply(FormatterFunc.java:31)
at com.diffplug.spotless.FormatterStepImpl$Standard.format(FormatterStepImpl.java:78)
at com.diffplug.spotless.FormatterStep$Strict.format(FormatterStep.java:76)
at com.diffplug.spotless.Formatter.compute(Formatter.java:230)
at com.diffplug.spotless.Formatter.applyToAndReturnResultIfDirty(Formatter.java:192)
at com.di
Have anybody experienced same or similar problem?
I found it. The problem was dangling ',' after last parameter in constructor (which Kotlin allows ).
var isPaused: Boolean = false, <- here ლ(ಠ益ಠლ)
) : RealmObject()
This is caused due to the default ktlint version used by the plugin. As of this time it's private static final String DEFAULT_VERSION = "0.35.0" which does not support trailing commas, although kotlin 1.4 does. In fact they had updated it to 0.40.0 at some point but got some formatting issues whiplash and eventually reverted the changes.
If you want though you can manually point to the latest version with something like
spotless {
kotlin {
target '**/*.kt'
ktlint("0.40.0")
}
}

Migrate CRUD Plugin from Play 1.2.4 to 2.5.x : views compilation errors

i'm new on Playframework and i need to migrate the CRUD Plugin from Play-1.2.4 to a module on Play-2.5.x. I'm facing some strange problems with the views. For example the form.scala.html component have the following errors :
app\views\tags\crud\form.scala.html:28: not found: type fieldName
app\views\tags\crud\form.scala.html:28: variable fieldsHandler of type Array[String] does not take type parameters.
app\views\tags\crud\form.scala.html:31: not found: value field
Here is a piece of code of the form file :
#(fields: List[String], obj: Object, typ: controllers.CRUD.ObjectType)(body: Html)
#import scala.Predef; var currentObject: Object = null; var currentType: controllers.CRUD.ObjectType = null; var fieldsHandler = new Array[String](10);
#for(fieldName <- fields) {
var am : String = "";
var field = #currentType.getField(fieldName);
#if(field == null){
throw new play.exceptions.TagInternalException("Field not found -> " + #fieldName)
}
#if(field.typ == "text") {
#tags.crud.textField(fieldName, currentObject[fieldName])
}
#if(field.typ == "password") {
#tags.crud.passwordField(fieldName, currentObject[fieldName])
}
#if(field.typ == "binary"){
#tags.crud.fileField(fieldName, currentObject[fieldName], currentObject.id )
}
}
--> 80% of the compile errors are related to variable recognition !
A piece from build.sbt file:
scalaVersion := "2.11.7"
lazy val root = (project in file(".")).enablePlugins(PlayJava, PlayEbean, SbtTwirl)
fork in run := true
Any idea ? Your help will be appreciated. Thanks.
I understood that the principle of the crud plugin is in contradiction with the new logic of compiling scala templates. So I started on a new generic implementation of crud.
Thank you

Why NoPointerExcepeion when decompression by apache compress?

click and see The NoPointerExcepeion
I generate tar.gz files and send 2 others 4 decompress, but their progrem has error above(their progrem was not created by me), only one file has that error.
But when using command 'tar -xzvf ***' on my computer and their computer, no problem occured...
So I want 2 know what was wrong in my progrem below:
public static void archive(ArrayList<File> files, File destFile) throws Exception {
TarArchiveOutputStream taos = new TarArchiveOutputStream(new FileOutputStream(destFile));
taos.setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX);
for (File file : files) {
//LOG.info("file Name: "+file.getName());
archiveFile(file, taos, "");
}
}
private static void archiveFile(File file, TarArchiveOutputStream taos, String dir) throws Exception {
TarArchiveEntry entry = new TarArchiveEntry(dir + file.getName());
entry.setSize(file.length());
taos.putArchiveEntry(entry);
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
int count;
byte data[] = new byte[BUFFER];
while ((count = bis.read(data, 0, BUFFER)) != -1) {
taos.write(data, 0, count);
}
bis.close();
taos.closeArchiveEntry();
}
The stack trace looks like a bug in Apache Commons Compress https://issues.apache.org/jira/browse/COMPRESS-223 that has been fixed with version 1.7 (released almost three years ago).

How to flush invalid SPWebConfigModifications

How do I flush out invalid SPWebConfigModifications?
I tried to execute some invalid modifications as part of a solution and now I cannt get rid of them, everytime I run ApplyWebConfigModifications it tries to execute the invalid modifications.
How do flush them out of the system?
For future reference (after banging my head on the wall for 3 days):
You can use this tool:
http://ianankers.wordpress.com/2011/07/14/web-config-modification-manager-for-sharepoint-2010/
It will list all the mods for every WebApp installed in your farm, you can add new ones and remove old ones.
The tool will only list modifications at webapp level, if you installed mods at the farm level you need to run a script like:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Navigation;
using Microsoft.SharePoint.Administration;
namespace ModTool
{
class Program
{
static void Main(string[] args)
{
SPSite site = new SPSite(args[0]);
SPWebService service = site.WebApplication.Farm.Services.GetValue<SPWebService>();
if (args.Length == 1 || string.IsNullOrEmpty(args[1]))
{
Console.Out.WriteLine("Listing all Mods and Owners");
foreach (SPWebConfigModification mod in service.WebConfigModifications)
{
Console.Out.WriteLine("Mod:" + mod.Name + ", Owner:" + mod.Owner);
}
}
else
{
Console.Out.WriteLine("Removing all mods owner:" + args[1] + ", reference site:" + args[0]);
List<SPWebConfigModification> toDelete = new List<SPWebConfigModification>();
foreach (SPWebConfigModification mod in service.WebConfigModifications)
{
if (mod.Owner == args[1])
{
toDelete.Add(mod);
}
}
Console.Out.WriteLine("Found " + toDelete.Count + "Mods");
foreach (SPWebConfigModification mod in toDelete)
{
service.WebConfigModifications.Remove(mod);
}
service.Update();
SPWebService.ContentService.ApplyWebConfigModifications();
Console.Out.WriteLine("Done!!");
}
}
}
}
Usage:
ModTool http://site - List all the mods for the farm, site is just an entry point
ModTool http://site owner -Deletes all the mods for the far wich owner is "owner"

SharpArch.Data.NHibernate.Repository.SaveOrUpdate() don't save

I have this code for filling DB, but after finish, DB is still empty. Only number in hibernate_unique_key table is higher.
The next thing which is interesting is, that during debugging instances has id, after save, but not like 1,2,3... but very high like 60083, 60084, ... etc. (It not seems normal, because there is only several rows for save).
Before that, there was some problems with references and so on, but now there is no error message or exception.
code is there:
using System;
using NHibernate.Cfg;
using SharpArch.Data.NHibernate;
using LaboratorniMetody.Data.NHibernateMaps;
using SharpArch.Core.PersistenceSupport;
using LaboratorniMetody.Core;
namespace LaboratorniMetody.FillSchema
{
class Program
{
private static Configuration configuration;
static void Main(string[] args)
{
configuration = NHibernateSession.Init(new SimpleSessionStorage(), new String[] { "LaboratorniMetody.Data" },
new AutoPersistenceModelGenerator().Generate(),
"../../../../app/LaboratorniMetody.Web/NHibernate.config");
IRepository<Laboratory> LaboratoryRepository = new Repository<Laboratory>();
Laboratory Laboratory1 = new Laboratory() { Name = "Hematologie" };//Method
Laboratory l = LaboratoryRepository.SaveOrUpdate(Laboratory1);
Laboratory Laboratory2 = new Laboratory() { Name = "Patologie" };//Method
LaboratoryRepository.SaveOrUpdate(Laboratory2);
Laboratory Laboratory3 = new Laboratory() { Name = "Laboratoře" };//Method
LaboratoryRepository.SaveOrUpdate(Laboratory3);
}
}
}
I use DB schema genereted by NUnit from Project.Core classes.
Do you have any ideas where i should find problem? I have 2 very similar project which working with no problem. I Copyed this code from one of them and there is practicly no differents (except DB model and so on.)
You need to do your changes in a transaction and commit the transaction afterwards.
using(var tx = NHibernateSession.Current.BeginTransaction())
{
IRepository<Laboratory> LaboratoryRepository = new Repository<Laboratory>();
Laboratory Laboratory1 = new Laboratory() { Name = "Hematologie" };//Method
Laboratory l = LaboratoryRepository.SaveOrUpdate(Laboratory1);
Laboratory Laboratory2 = new Laboratory() { Name = "Patologie" };//Method
LaboratoryRepository.SaveOrUpdate(Laboratory2);
Laboratory Laboratory3 = new Laboratory() { Name = "Laboratoře" };//Method
LaboratoryRepository.SaveOrUpdate(Laboratory3);
tx.Commit();
}
I advise to look at the SharpArchContrib project wiki, which has some samples on using SharpArch in a windows app/service and how to use Transaction attributes from there.
https://github.com/sharparchitecture/Sharp-Architecture-Contrib/wiki/