xsd to class (C#) in visual studio 2019 - c#

I am following a tutorial, in one step it opens "VS2012 arm cross tools command prompt" and executes
xsd file.xsd /classes
I can't find "VS2012 arm cross tools command prompt" on my computer (my guess it's because I'm using VS2019) so I open the "Developer command prompt for VS 2019" instead, but when I run the command, I get an error:
"xsd" is not recognized as an internal or external command, program or executable batch file
Can someone tell me how I can create a class from an xsd file in VS 2019? Thank you for your time.

Once you have installed the Windows SDK. The following could be of help to you...it is .NET Core. Browse to the xsd.exe and add a reference to it in VS 2019.
class Program
{
static void Main(string[] args)
{
var rgs = new string[]
{
#"PathToYourDLL\My.dll",
"/type:ClassNameToGen"
};
AppDomain.CurrentDomain.FirstChanceException += (s, e) =>
{
string error = e.Exception.ToString();
var typeLoadException = e.Exception as ReflectionTypeLoadException;
if (typeLoadException != null)
{
foreach (var exception in typeLoadException.LoaderExceptions)
{
error += Environment.NewLine + Environment.NewLine + exception.ToString();
}
}
Console.WriteLine(error);
};
XsdTool.Xsd.Main(rgs);
Console.ReadLine();
}
}

Related

got unexpected named argument error when running csharp code on visual studio

I tried to run the csharp code in Visual Studio Code for Mac, I have scripts installed and added to PATH.
It gives me below error and code cannot run.
[Running] scriptcs "/var/folders/sr/5jzw91rn4g3cc2b0xyhw0j100000gq/T/tempCodeRunnerFile.csharp"
Unexpected named argument: var/folders/sr/5jzw91rn4g3cc2b0xyhw0j100000gq/T/tempCodeRunnerFile.csharp
This is the question linked: Getting error: /bin/sh scriptcs: command not found
The OS version is 10.14.6(18G87) Please see attached screenshot.
The Visual Studio Code version is below:
Version: 1.38.1
Commit: b37e54c98e1a74ba89e03073e5a3761284e3ffb0
Date: 2019-09-11T13:31:32.854Z
Electron: 4.2.10
Chrome: 69.0.3497.128
Node.js: 10.11.0
V8: 6.9.427.31-electron.0
OS: Darwin x64 18.7.0
minimal reproducible example:
Open Visual Studio Code and create a new File with below code:
using System;
using System.Collections.Generic;
class Test
{
static void Main()
{
foreach (int fib in Fibs(6))
Console.Write (fib + " ");
}
static IEnumerable<int> Fibs (int fibCount)
{
for (int i = 0, prevFib = 1, curFib = 1; i < fibCount; i++)
{
yield return prevFib;
int newFib = prevFib+curFib;
prevFib = curFib;
curFib = newFib;
}
}
}
and then click Run Code on top right in Visual Studio Code.
This is a bug in PowerArgs, it recognizes an argument started with slash as an option, so you need split the command into two steps.
cd "/var/folders/sr/5jzw91rn4g3cc2b0xyhw0j100000gq/T"
scriptcs "tempCodeRunnerFile.csharp"
[Update]
scriptcs is a csharp code runner, to make it work, at least you need one line to call the entry method.
...
class Test
{
public static void Main() // Public
{
...
}
}
Test.Main(); // Run it

'System.Data.SqlServerCe.RepairOption' does not contain a definition for 'RecoverAllPossibleRows'

I am building a windows app using nant and when runing rebuild command to clean current build and create new assembly files I get the following error in the command prompt:
Here's a section of LxSqlCeOprn.cs containing line 85 where error occurs:
using System.Data.SqlServerCe;
public static void RepairDb (string fileSpec, bool delCorruptRows)
{
RepairOption opt = delCorruptRows ? RepairOption.DeleteCorruptedRows : RepairOption.RecoverAllPossibleRows;
//System.Data.SqlServerCe.RepairOption opt = new System.Data.SqlServerCe.RepairOption();
//opt = delCorruptRows ? RepairOption.DeleteCorruptedRows : RepairOption.RecoverAllPossibleRows;
try
{
LxNformTools.StopService ();
char[] delimiter = {'.'};
string[] temp = fileSpec.Split(delimiter);
string fileBackup = temp[0] + "tempBak." + temp[1];
File.Copy(fileSpec, fileBackup, true);
SqlCeEngine engine = GetEngine (fileBackup);
LxSystemLogger.Log ("Repairing SQL CE database: " +
engine.LocalConnectionString +
"RepairOption=" + opt,
LxSeverity.Info, "LxSqlCeOprn.RepairDb");
//Attmpt to repair file only if Verify fails
if(!engine.Verify(VerifyOption.Enhanced))
{
engine.Repair (null, opt);
if(engine.Verify(VerifyOption.Enhanced))
{
File.Copy(fileBackup, fileSpec, true);
}
}
File.Delete(fileBackup);
LxSystemLogger.Log ("Repair complete.",
LxSeverity.Success, "LxSqlCeOprn.RepairDb");
}
catch (Exception e)
{
LxSystemLogger.Log ("Error in database operation", e,
"LxSqlCeOprn.RepairDb");
if (LxBaseException.IsCriticalException(e)) throw;
}
return;
} // end RepairDb
I am using visual studio professional 2013, the reference to System.Data.SqlServerCe.dll has been added to the project and Visual Studio does not complain about any missing definitions. I was thinking this could be related to environment setup, any hints will be appreciated.

Interfacing Microsoft .NET ( C# / F# ) with SWI-Prolog

I have problem with connecting Prolog to C#.
Visual Studio gives this following error :
"An unhandled exception of type 'System.IO.FileNotFoundException'
occurred in SwiPlCs.dll"
and I really don't know how to handle this.
I think it came from the path I gave in the code :
using System;
using SbsSW.SwiPlCs;
namespace ptest
{
class Program
{
static void Main(string[] args)
{
//Environment.SetEnvironmentVariable(#"C:\Program Files\swipl", #"C:\Program Files\swipl\boot64.prc"); // or boot64.prc
var curPath = Environment.GetEnvironmentVariable("C:\\Program Files\\swipl\\bin");
Environment.SetEnvironmentVariable(#"C:\Program Files\swipl\bin", #"C:\Program Files\swipl\boot;C:\Program Files\swipl;" + curPath);
if (!PlEngine.IsInitialized)
{
String[] param = { "-q" }; // suppressing informational and banner messages
PlEngine.Initialize(param);
PlQuery.PlCall("assert(father(martin, inka))");
PlQuery.PlCall("assert(father(uwe, gloria))");
PlQuery.PlCall("assert(father(uwe, melanie))");
PlQuery.PlCall("assert(father(uwe, ayala))");
using (var q = new PlQuery("father(P, C), atomic_list_concat([P,' is_father_of ',C], L)"))
{
foreach (PlQueryVariables v in q.SolutionVariables)
Console.WriteLine(v["L"].ToString());
Console.WriteLine("all children from uwe:");
q.Variables["P"].Unify("uwe");
foreach (PlQueryVariables v in q.SolutionVariables)
Console.WriteLine(v["C"].ToString());
}
PlEngine.PlCleanup();
Console.WriteLine("finshed!");
}
}
}
}
Please Help me. Thank you very much.
I think its a problem with latest versions of SWI_Prolog. Try installing older version of SWI-Prolog 6.6.1 for Microsoft Windows (32 bit) in C:/Program Files (x86) and use SwiPlCs_1.1.60301.0.zip. Add reference to SwiPlCs.dll in Visual Studio. It will work IA :)

resharper code analysis using Command line tool (inspectcode.exe)

In My C# language sln file contains two projects. first project has the actual code & second project has the unittest cases for the first project. but while am doing the resharper code analysis using Command line tool (inspectcode.exe).
for both project resharper doing the inspection in the unit test project only, not on the Actual code file.
'
package org.sonar.plugins.resharper;
import java.io.File;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.api.utils.command.Command;
import org.sonar.api.utils.command.CommandException;
import org.sonar.api.utils.command.CommandExecutor;
public class ReSharperExecutor
{
private static final Logger LOG = LoggerFactory.getLogger(ReSharperExecutor.class);
public void execute(String executable, String project, String solutionFile, File rulesetFile, File reportFile, int timeout)
{
Command cmd = Command.create(getExecutable(executable)).addArgument("/output=" + reportFile.getAbsolutePath()).addArgument("/no-swea").addArgument("/project=" + project).addArgument("/profile=" + rulesetFile.getAbsolutePath()).addArgument("/no-buildin-settings").addArgument(solutionFile);
int exitCode = CommandExecutor.create().execute(cmd, TimeUnit.MINUTES.toMillis(timeout));
if (exitCode != 0) {
throw new CommandException(cmd, "ReSharper execution failed with exit code: " + exitCode, null);
}
}
private static String getExecutable(String propertyValue)
{
String execName = "inspectcode.exe";
if (!propertyValue.endsWith(execName)) {
return new File(propertyValue, execName).getAbsolutePath();
}
return propertyValue;
}
}'
Where I need to do the change to do the Resharper analysis for the Actual code.
Executing command: cd:/inspectcode.exe /output=cd:\resharper-report.xml /no-swea /project=* /profile=cd:.sonar\resharper-sonarqube.DotSettings /no-buildin-settings cd:\XXXX.sln
The above issue was caused bcoz the VS build version different in the
1.project built machine(VS2015) &
2.project analysis happening machine(VS2013),
so its not show any error details in log of the machine 2.
After testing the analysis in the built machine i got the root cause of the issue(Few of the dependency library of the project was missed which should be availble under MSBuild folder{Msbuildfolder->Microsoft->visualstudio->version}) & fixed it(by replacing the missing dll's).
Now Analysis running successfully.

Using Microsoft.Build.Evaluation to publish a database project (.sqlproj)

I need to be able to publish an SSDT project programmatically. I am looking at using Microsoft.Build to do so but can not find any documentation. It seems pretty simple to create the .dacpac, but how would I either publish to an existing database or at the very least to a .sql file. The idea is to have it do what it does when I right click on the project and select publish. It should compare with a selected database and generate an upgrade script.
This is what I have so far to create the .dacpac:
partial class DBDeploy
{
Project project;
internal void publishChanges()
{
Console.WriteLine("Building project " + ProjectPath);
Stopwatch sw = new Stopwatch();
sw.Start();
project = ProjectCollection.GlobalProjectCollection.LoadProject(ProjectPath);
project.Build();
//at this point the .dacpac is built and put in the debug folder for the project
sw.Stop();
Console.WriteLine("Project build Complete. Total time: {0}", sw.Elapsed.ToString());
}
}
Essentially I am trying to do what this MSBuild Example shows but in code.
Sorry that this is all I have. The doecumentation on the Build classes is very poor. Any help would be appreciated.
Thanks.
I had to do something similar to this because VSDBCMD which we previously used does not deploy to SQL Server 2012 and we needed to support it. What I found was the Microsoft.SqlServer.Dac assembly which seems to come as part of the SQL Server data tools (http://msdn.microsoft.com/en-us/data/tools.aspx)
When you run this on the client machine you will need the full version of the .NET 4 framework and the SQL CLR types and SQL T-SQL ScriptDOM pack found here: http://www.microsoft.com/en-us/download/details.aspx?id=29065
Code below is from a mockup I made for testing the new deployment method and deploys a given .dacpac file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SqlServer.Dac;
using System.IO;
namespace ConsoleApplication3
{
class Program
{
private static TextWriter output = new StreamWriter("output.txt", false);
static void Main(string[] args)
{
Console.Write("Connection String:");
//Class responsible for the deployment. (Connection string supplied by console input for now)
DacServices dbServices = new DacServices(Console.ReadLine());
//Wire up events for Deploy messages and for task progress (For less verbose output, don't subscribe to Message Event (handy for debugging perhaps?)
dbServices.Message += new EventHandler<DacMessageEventArgs>(dbServices_Message);
dbServices.ProgressChanged += new EventHandler<DacProgressEventArgs>(dbServices_ProgressChanged);
//This Snapshot should be created by our build process using MSDeploy
Console.WriteLine("Snapshot Path:");
DacPackage dbPackage = DacPackage.Load(Console.ReadLine());
DacDeployOptions dbDeployOptions = new DacDeployOptions();
//Cut out a lot of options here for configuring deployment, but are all part of DacDeployOptions
dbDeployOptions.SqlCommandVariableValues.Add("debug", "false");
dbServices.Deploy(dbPackage, "trunk", true, dbDeployOptions);
output.Close();
}
static void dbServices_Message(object sender, DacMessageEventArgs e)
{
output.WriteLine("DAC Message: {0}", e.Message);
}
static void dbServices_ProgressChanged(object sender, DacProgressEventArgs e)
{
output.WriteLine(e.Status + ": " + e.Message);
}
}
}
This seems to work on all versions of SQL Server from 2005 and up. There is a similar set of objects available in Microsoft.SqlServer.Management.Dac, however I believe this is in the previous version of DACFx and is not included in the latest version. So use the latest version if you can.
We need a way tell msbuild how and where to publish. Open your project in Visual Studio and begin to Publish it. Enter all needed info in the dialog, including your DB connection info and any custom SQLCMD variable values. Save Profile As... to a file, e.g. Northwind.publish.xml. (You may then Cancel.) Now we can use this and the project file to build and publish:
// Create a logger.
FileLogger logger = new FileLogger();
logger.Parameters = #"logfile=Northwind.msbuild.log";
// Set up properties.
var projects = ProjectCollection.GlobalProjectCollection;
projects.SetGlobalProperty("Configuration", "Debug");
projects.SetGlobalProperty("SqlPublishProfilePath", #"Northwind.publish.xml");
// Load and build project.
var dbProject = ProjectCollection.GlobalProjectCollection.LoadProject(#"Northwind.sqlproj");
dbProject.Build(new[]{"Build", "Publish"}, new[]{logger});
This can take awhile and may appear to get stuck. Be patient. :)
You should use SqlPackage.exe to publish your dacpac.
SqlPackage.exe
/Action:Publish
/SourceFile:C:/file.dacpac
/TargetConnectionString:[Connection string]
Also instead of passing too many parameters you could save your settings into DAC Publish Profile (this can be done from visual studio)
I wanted to build and publish a database based on a sqlproj file and log helpful information to console. Here's what I arrived at:
using Microsoft.Build.Framework;
using Microsoft.Build.Execution;
public void UpdateSchema() {
var props = new Dictionary<string, string> {
{ "UpdateDatabase", "True" },
{ "PublishScriptFileName", "schema-update.sql" },
{ "SqlPublishProfilePath", "path/to/publish.xml") }
};
var projPath = "path/to/database.sqlproj";
var result = BuildManager.DefaultBuildManager.Build(
new BuildParameters { Loggers = new[] { new ConsoleLogger() } },
new BuildRequestData(new ProjectInstance(projPath, props, null), new[] { "Publish" }));
if (result.OverallResult == BuildResultCode.Success) {
Console.WriteLine("Schema update succeeded!");
}
else {
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Schema update failed!");
Console.ResetColor();
}
}
private class ConsoleLogger : ILogger
{
public void Initialize(IEventSource eventSource) {
eventSource.ErrorRaised += (sender, e) => {
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(e.Message);
Console.ResetColor();
};
eventSource.MessageRaised += (sender, e) => {
if (e.Importance != MessageImportance.Low)
Console.WriteLine(e.Message);
};
}
public void Shutdown() { }
public LoggerVerbosity Verbosity { get; set; }
public string Parameters { get; set; }
}
This is for .NET 4 and above. Be sure and include assembly references to Microsoft.Build and Microsoft.Build.Framework.

Categories