Unable to Run Program Using CommandLineParser Package - c#

I am trying to add some command line arguments to my application using CommandLineParser:
using CommandLine;
using System;
namespace ConsoleApplication1
{
class Options
{
[Option('s', "site", Required = true,
HelpText = "The site to connect to. Please include http://")]
public string sitename { get; set; }
[Option('l', "list", Required = true,
HelpText = "The list to connect to.")]
public string listname { get; set; }
}
class Program
{
static void Main(string[] args)
{
var options = new Options();
Parser.Default.ParseArguments(args, options);
Console.WriteLine(options.sitename);
Console.WriteLine("\n");
Console.WriteLine(options.listname);
}
}
}
However, when I try calling this from CMD:
test -s sitename -l listname
I am getting this error:
Unhandled Exception: System.IO.FieNotFoundEsxcepion: Could not load file or assembly 'CommandLine, Version=1.9.71.2, Culture=neutral, PublicKeytoken=de6f01bd326f8c32', or one of its dependancies. The system cannot find the file specified. at ConsoleApplication1.Program.Main(String[] args)
I have installed the CommandLineParser package and I can see it in my references list. When I navigate to this folder: \\file\IT\SK\Visual Studio Projects\ConsoleApplication1\packages\CommandLineParser.1.9.71\lib\net40 I can see that there is a CommanLine.dll and a CommandLine.xml.
Can someone please explain to me what is going on here?
Update
I am able to run this with command lines in Visual Studio if I DISABLE ClickOnce Security settings, and it works fine. However, when I publish the application, this is automatically selected and the problem persists.
When debugging with command line arguments and ClickOnce Security enabled, args[] is null ...

It's a security feature. Your executable resides on the network and is not trusted to access other network resources.
I bet it works if you copy everything to a local folder.

Is the dll also in the bin output folder? If not, check the properties of the reference and check that "copy local" is true.

Related

.net C# jdbc driver connector exception

I'm trying to connect to a hyperSQL database (HSQLDB) on my local machine from a c# application in visual studio.
I've ran through the steps to create the .net JDBC driver to build the dll, and also downloading the demo console application in the "download" section from the following url: http://nikolaiklimov.de/query-java-HyperSQL-database-with-csharp/
The demo application works!! i can connect to the database and query its contents . Next I have converted the console app into a class library then call the class library to query the DB but this is where it falls over and I get initialization errors of System.TypeInitializationException. any idea why the project falls over after converting to a class library. (if i convert the class library straight back a console app it works again).
The code and connection string are:
namespace HyperSQL
{
public static class sqlconnector
{
readonly static string CONNECTION_STRING =
ConfigurationManager.ConnectionStrings["HyperSQL"].ConnectionString;
const string SQL = "SELECT * FROM meeting";
public static void getdata()
{
try
{
java.sql.DriverManager.registerDriver(new org.hsqldb.jdbcDriver());
using (java.sql.Connection conn = java.sql.DriverManager.getConnection(CONNECTION_STRING))
{
java.sql.PreparedStatement ps = conn.prepareStatement(SQL);
using (java.sql.ResultSet rs = ps.executeQuery())
{
while (rs.next())
{
Console.WriteLine($"MEETING_NO={rs.getInt("MEETING_NO")}");
Console.WriteLine("------------------");
}
}
}
}
catch (Exception ex)
{
}
Console.ReadLine();
}
}
}
jdbc:hsqldb:hsql://localhost:3458/elitedb;crypt_key=DADADADADAADDADAD;crypt_type=AES;shutdown=true;write_delay=false;user=****;password=****
Ive added a console app to my solution after the conversion to a class libary. The console app code is below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
try
{
HyperSQL.sqlconnector.getdata();
}
catch (Exception ex)
{
}
}
}
}
Here is a link to download my solution created in visual studio. It contains a console application that calls a function in a class library. The class library (HyperSQL) itself is simply converted from a console application and can be converted back. You will need a running instance of HyperSQL on your machine to be able to connect successfully.
http://eliteservicedev.azurewebsites.net/DemoHyperSQL.zip
Have you seen the error listed in the original site you posted?
If your forget to add runtime dependencies to the build folder of your
project then you can get these errors: Could not load file or
assembly 'IKVM.OpenJDK.Util, Version=8.1.5717.0, Culture=neutral,
PublicKeyToken=13235d27fcbfff58' or one of its dependencies. The
system cannot find the file specified. TypeInitializationException:
The type initializer for 'org.hsqldb.jdbc.JDBCDriver' threw an
exception: FileNotFoundException: Could not load file or assembly
'IKVM.Runtime, Version=8.1.5717.0, Culture=neutral,
PublicKeyToken=13235d27fcbfff58' or one of its dependencies. 'The
type initializer for 'sun.util.locale.provider.LocaleProviderAdapter'
threw an exception.' FileNotFoundException: Could not load file or
assembly 'IKVM.OpenJDK.Text, Version=8.1.5717.0, Culture=neutral,
PublicKeyToken=13235d27fcbfff58' or one of its dependencies. 'The
type initializer for 'org.hsqldb.HsqlDateTime' threw an exception.'
InvalidCastException: Unable to cast object of type
'java.util.PropertyResourceBundle' to type
'sun.util.resources.OpenListResourceBundle'.
***** UPDATE
With the source project i see an error, looking in the bin\debug folder i see that non all the referenced file are copied to ConsoleApp1.exe bin folder: this is the compare result:
Confronto in corso dei file consoleapp1.txt e DEMOCSHARPTHYPERSQL.TXT
***** consoleapp1.txt
ConsoleApp1.exe
ConsoleApp1.exe.config
ConsoleApp1.pdb
hsqldb.dll
HyperSQL.dll
***** DEMOCSHARPTHYPERSQL.TXT
hsqldb.dll
HyperSQL.dll
*****
***** consoleapp1.txt
IKVM.OpenJDK.Jdbc.dll
IKVM.OpenJDK.Text.dll
***** DEMOCSHARPTHYPERSQL.TXT
IKVM.OpenJDK.Jdbc.dll
IKVM.OpenJDK.Localedata.dll --> Missing in ConsoleApp1.exe folder
IKVM.OpenJDK.Text.dll
*****
If i manually copy the missing dll on ConsoleApp1.exe folder the program run correctly. I think that is a visual studio bug
Seems VS is not copying all IKVM DLLs to output folder due to not resolving they are needed. Please see this SourceForge issue and this GitHub issue, the later one with my comments.

c# Register custom dll as processor to Printer++ Config file

I am trying to create a custom printer driver to generate images. For this, I have installed Printer++ which converts print files to postscripts. To convert postscript file to image, I am using ghostscript. Independently both the processes are running fine and I am able to achieve what is required.
But, I need a custom process to generate images in one go. I followed through the Printer++ tutorial but it didn't work.
This is what I have done:
I installed Printer++ and gave the name of the printer driver as- Septane.
In Visual Studio, I created a project- Test.
And the following code in Processor.cs class:
using System;
using System.Net.Mail;
using PrinterPlusPlusSDK;
namespace Test
{
public class Processor : PrinterPlusPlusSDK.IProcessor
{
public PrinterPlusPlusSDK.ProcessResult Process(string key, string psFilename)
{
//Convert PS to Png
psFilename = "b.ps";
MessageBox.Show("Rahul");
ConvertPsToTxt(psFilename);
}
public static string ConvertPsToTxt(string psFilename, string txtFilename)
{
var retVal = string.Empty;
var errorMessage = string.Empty;
var command = "C:\\PrinterPlusPlus\\gs\\gswin64.exe";
var args = string.Format("-dNOPAUSE -dBATCH -dFirstPage=1 -q -r300 -sDEVICE=png256 -sOutputFile=", psFilename, txtFilename);
retVal = Shell.ExecuteShellCommand(command, args, ref errorMessage);
return retVal;
}
}
}
This class inherits from PrinterPlusPlusSDK.IProcessor and implements the PrinterPlusPlusSDK.ProcessResult Process function. I have tested the standalone console project (without using PrinterPlusPlusSDK processor) and that converts ps to png successfully.
Now, as per the tutorial, the dll needs to be deployed to printer++ and registered as a processor. I copied Test.dll to Printer++ installation folder and added an entry to PrinterPlusPlus.exe.config file.
The config entry looks like:
<processors>
<add key="Test"
value="Test.Processor, Septane, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
</processors>
That's it. Now, when I print a file, it gives an error:
Proccessor not found for: Septane
What am I doing wrong?
If anyone has better idea for achieving the same, please let me know. Actually, mine is a commercial product so can't use CutePDF/VerPDf kind options.
Edit: I now know why I was getting error- Processor not found. I renamed my printer to Test and the error disappeared. I have edited my code as well.
For testing, I have added a message box. I expected to get a popup once I give print command. But that is not the case. The ps file is getting generated without an error and that's it. I can't view pop-up message and there is no png converted file. Can someone please help me resolve this issue at least? It doesn't seem to be picking up the dll at all.
Thanks.
Remember The Printer name must be same as the you dll name
If your printer driver name is Septane. Then you must have to create a project name with "Septane". In that case project name "Test" will not work.

Can't step Into and debug the serviced component source code

I have developed a COM+ Component in C# be inheriting ServicedComponent.
Here is how it looks like:
[Transaction(TransactionOption.Required)]
[ClassInterface(ClassInterfaceType.AutoDual)]
[EventTrackingEnabledAttribute(true)]
[JustInTimeActivation]
[ObjectPooling(Enabled = true, MinPoolSize = 10, MaxPoolSize = 30, CreationTimeout = 15000)]
[Synchronization]
class MyComponent: System.EnterpriseServices.ServicedComponent
{
[AutoComplete(true)]
public string getHello()
{//2nd breakpoint
ContextUtil.SetComplete();
return "HelloWorld";
}
}
I have another test project from which I call this component.
class Program
{
static void Main(string[] args)
{
MyComponent myComp = new MyComponent();
myComp.getHello();//1st Breakpoint
}
}
I am not able to reach 2nd Breakpoint. This was working before I switched to VS 2012. Strange thing is after switching to 2012 its no longer working in VS 2010 too.
I've already tried,
Attach to process
Unchecked "Enable Just My Code" in debug settings
Can someone please give direction from here?
UPDATE 1
From the links given by Mike, I tried symchk for my DLL in the same folder where DLL and PDB files were there. It fails with error saying PDB mismatched or not found. I don't know how to resolve this error.
You may be missing the .pdb file in your project.
Check this microsoft link out for an explanation: https://msdn.microsoft.com/en-us/library/yd4f8bd1(vs.71).aspx

Unable to publish Website Using Microsoft.Build Library

I am currently attempting write an application that will function as an automatic publishing process. In the process, I need to build, and publish a number of items. I am able to build, and publish the web application successfully, however, when publishing the website, I am running into problems.
I am able to successfully complete the required with the following command line execution:
msbuild website.publishproj /p:deployOnbuild=true /p:PublishProfile="test.pubxml"
I am trying to execute this by using the build libraries, but it is failing:
string projectFileNamepub = CurrentPublish.ExcaliburBuildPath;
Dictionary<string, string> GlobalPropertypub = new Dictionary<string, string>();
ProjectCollection pcpub = new ProjectCollection();
//pcpub.SkipEvaluation = true;
//GlobalPropertypub.Add("Configuration", "Release");
//GlobalPropertypub.Add("Platform", "x86");
GlobalPropertypub.Add("DeployOnBuild", "true");
GlobalPropertypub.Add("PublishProfile",CurrentPublish.ExcaliburPublishProfile);
//GlobalPropertypub.Add("VisualStudioVersion", "11.0");
BuildRequestData BuildRequestpub = new BuildRequestData(projectFileNamepub, GlobalPropertypub, null, new string[] { "Build" }, null);
BuildResult buildResultpub = BuildManager.DefaultBuildManager.Build(new BuildParameters(pcpub), BuildRequestpub);
if (buildResultpub.OverallResult == BuildResultCode.Success)
{
bsuccess = true;
txtOutput.Text = txtOutput.Text + "Publish Success \n";
}
The commented out properties are properties that I have attempted to use, but none of them were successful.
Is there something that I am doing wrong? I have used exactly this to publish another web application before this one, and it completes successfully.
This target completes successfully:
_CheckForInvalidConfigurationAndPlatform
It then fails on Build.
If you create your build parameters this way you can display the build output on the console:
var buildParameters = new BuildParameters(pc)
{
Loggers = new List<Microsoft.Build.Framework.ILogger> { new ConsoleLogger() }
};
When I did this I saw the following error:
C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v14.0\Web\Microsoft.Web.Publishing.targets(4353,5): error MSB4127: The "GetPublishingLocalizedString" task could not be instantiated from the assembly "C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v14.0\Web\Microsoft.Web.Publishing.Tasks.dll". Please verify the task assembly has been built using the same version of the Microsoft.Build.Framework assembly as the one installed on your computer and that your host application is not missing a binding redirect for Microsoft.Build.Framework. Unable to cast object of type 'Microsoft.Web.Publishing.Tasks.GetPublishingLocalizedString' to type 'Microsoft.Build.Framework.ITask'.
I searched for error MSB4127 and found the answer here: MSBuild "GenerateFakes" Error MSB4127, MSB4060
I was already specifying the VisualStudioVersion. I simply added the <runtime> section from C:\Program Files (x86)\MSBuild\14.0\Bin\MSBuild.exe.config into my App.config and the build and publish worked.

Powershell Importing custom C# CMDlets, no available "ExportedCommands"

first question here :)
So I have to create a custom CMDLet for Powershell 2.0, using visual studio 2010 express.
I have followed this seemingly simple tutorial : http://blogs.msdn.com/b/saveenr/archive/2010/03/08/how-to-create-a-powershell-2-0-module-and-cmdlet-with-visual-studio-2010-screencast-included.aspx
My code is almost the same (even tried copy pasting thier code) but after I call Import-Module "path_to_dll"
and then call Get-Module, i see my imported module, but no ExportedCommands are available.
ModuleType Name ExportedCommands
---------- ---- ----------------
Binary PowerShellCMDLetsLibrary {}
C# Code:
namespace PowerShellCMDLetsLibrary
{
[System.Management.Automation.Cmdlet(System.Management.Automation.VerbsCommon.Get,"RemedyXml")]
public class Get_RemedyXml:System.Management.Automation.PSCmdlet
{
[System.Management.Automation.Parameter(Position = 0, Mandatory = true)]
public string TicketID;
protected override void ProcessRecord()
{
...
this.WriteObject(Result.InnerXml, true);
}
Might be a blunder, I just can't see it
Two things jump out # me:
The TicketID is a field, not a Property.
The overnamedspaced attribution makes the code hard to read.
I suspect it's #1 , but I can't see enough past #2 to be sure.
Hope this Helps
Dont know if repost, but:
I found the solution. Copied my dll from UNC networkpath to local c:\
And now the command shows up.
If you are running this off a network or unc path , you must add the path to your .net trusts:
ie:
caspol -machine -addgroup 1. -url "file:\\\network\dir\\*" FullTrust -n Uniquename
HTH,
Bob
This is due to Code Access Security in .NET. By default, an assembly loaded from a network share executes with reduced privileges, whereas one loaded from local storage has no restrictions at all. Unfortunately, the Import-Module cmdlet gives no indication that it failed to import the cmdlets within a module, even when called with the -Verbose parameter.
To change the set of permissions granted to a particular network location, use the caspol.exe utility to create a new code group for that location:
caspol.exe -machine -addgroup 1.2 -url "file://server/share/directory/*" FullTrust
The 1.2 in the above command refers to the LocalIntranet code group, which will be the new code group's parent. The following command will show which code groups are defined, and can be used to display the group that you created:
caspol.exe -machine -listgroups
Note that on 32-bit Windows caspol.exe is located in %WinDir%\Microsoft.NET\Framework\CLR_VERSION\ (where, for PowerShell 2.0, CLR_VERSION is v2.0.50727), and on 64-bit Windows another copy is located in %WinDir%\Microsoft.NET\Framework64\CLR_VERSION\. The 32- and 64-bit versions each have their own security configuration file (CONFIG\security.config), so you will need to make sure you apply each security change to both versions using their respective caspol.exe.
The following command can be used to display the permissions that will be granted to a particular assembly:
caspol.exe -resolveperm "//server/share/directory/assembly.dll"
I basically copied an pasted your code. I did a Get-Module ClassLibrary2. Also TicketID does work.
ModuleType Name ExportedCommands
---------- ---- ----------------
Binary ClassLibrary2 Get-RemedyXml
using System.Management.Automation;
namespace ClassLibrary1
{
[Cmdlet(VerbsCommon.Get, "RemedyXml")]
public class Class1 : PSCmdlet
{
[Parameter(Position = 0, Mandatory = true)]
public string TicketID;
protected override void ProcessRecord()
{
WriteObject(TicketID);
}
}
}

Categories