I have the following c# Console app I would run this in ssis but i am using a couple of PDF manipulating librarys. so i am going to call an exe from my ssis package while passing in a file path.
But i am getting the following error when trying to run via the exe.
Unhandled Exception: System.IndexOutOfRangeException: Index was
outside the bounds of the array. at ConsoleApp.program.Main(String[]
args) line 87
BUT if i run in debug it works fine. Once i get it working on its own via the exe, i want to pass the filepath as a parameter in ssis.
see c# below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using org.apache.pdfbox.pdmodel;
using org.apache.pdfbox.util;
using System.IO;
namespace PDF_Read_ConsoleApp
{
class Program
{
public static void FilePath(string path)
{
//Console.WriteLine("Please enter full pdf path \n\n ");
//path = Console.ReadLine();
string fp;
fp = #path;
string[] files = Directory.GetFiles(path, "*.pdf");
foreach (string s in files)
{
string txtOutput = s.Replace(".pdf", ".txt");
if (File.Exists(txtOutput))
{
File.Delete(txtOutput);
}
string output;
PDDocument doc = null;
try
{
doc = PDDocument.load(s);
PDFTextStripper stripper = new PDFTextStripper();
stripper.getText(doc);
output = stripper.getText(doc);
StreamWriter NewFile;
NewFile = new StreamWriter(txtOutput);
//NewFile.Write(output.ToString());
NewFile.Write(output.ToString());
NewFile.Close();
}
finally
{
//if (doc != null)
//{
doc.close();
// Console.WriteLine("\n\n File saveed - ({0} ", txtOutput);
//}
}
}
}
static void Main(string[] args)
{
args[0] = #"C:\SSIS_Packages\PDF_Import\PDF_Import\PO_pdfs"; //// TESTING FILE PATH1
FilePath(args[0]);
}
}
}
Kind Regards
Rob
I have managed to get it working, I need to enter an argument within the debug screen, see information in URL below
Console app arguments, how arguments are passed to Main method
THank you for everyone's comments
Related
I was trying to make a program to clean out some directories on my NAS and I noticed that a lot of folders contained nested rar and zip files and I have plenty of space to unpack them. The program should ask the user for a directory to be cleaned then unpack all rars then delete all of the rars. I'm trying to use UnRAR DLL and I cant even get the rars to unpack. I realize I'm having an issue where visual studio 2022 is refusing to recognize the Unrar DLL in the "using" command. Because of that I've been unable to unpack a single file. This is one my first useful programs so if im missing something basic I understand.
This is my initial attempt:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Diagnostics;
using UnRAR;
namespace Cleaning
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter Directory To Be Cleaned");
string rar_path = Console.ReadLine();
string[] Rars = Directory.GetFiles(rar_path, "*.rar", SearchOption.AllDirectories);
foreach (string rar in Rars)
{
string source = rar;
string dest = "C:\\Users\\Kaleb\\OneDrive\\Desktop\Test Area";
UnRAR unrar = new UnRAR();
unrar.Password = "password_of_myarchive";
unrar.Open(#source, UnRAR.OpenMode.Extract);
while (unrar.ReadHeader())
{
unrar.ExtractToDirectory(#dest);
}
unrar.Close();
}
}
}
}
For reference I have added the UnRAR DLL to the project folder.
SO I was able to get it working with the source code from the great people over at SharpCompress and utilizing their source I've got the following stable build.
using SharpCompress.Archives;
using SharpCompress.Archives.Rar;
using SharpCompress.Common;
using System;
using System.IO;
using System.Linq;
using System.Globalization;
namespace ConsoleApp3
{
public class Program
{
static void Main(string[] args)
{
for (; ; )
{
Console.WriteLine("Enter E to extract all directories in file path");
Console.WriteLine("Enter D to delete all Archives in file path");
Console.WriteLine("REMEMBER TO ALWAYS EXTRACT BEFORE DELETING");
string option = Console.ReadLine();
if (option == "e" || option == "E")
{
Console.WriteLine("Enter Directory To Be Cleaned");
//as a warning this will extract all files from any rar in the slected driectory one at a time in order.
//if a rar is broken it will halt the program until the offendin rar is deleted best way to find is to see what has been extracted so far and go from there
//or one could also limit the directory in order to refine the number of rars to look for
string rar_path = Console.ReadLine();
string[] Rars = Directory.GetFiles(rar_path, "*.rar", SearchOption.AllDirectories);
foreach (string rar in Rars)
{
var DirectoryFinal = Path.GetDirectoryName(rar);
using (var archive = RarArchive.Open(#rar))
{
foreach (var entry in archive.Entries.Where(entry => !entry.IsDirectory))
{
entry.WriteToDirectory(#DirectoryFinal, new ExtractionOptions()
{
ExtractFullPath = true,
Overwrite = true
});
}
};
}
}
else if (option == "d" || option == "D")
{
Console.WriteLine("Enter Directory To Be Cleaned");
//be careful with this i would recomend extracting and then chekcing everything first
string rar_path = Console.ReadLine();
string[] TobeDeleted = Directory.GetFiles(rar_path, "*.r*", SearchOption.AllDirectories);
foreach (string rarstobedeleted in TobeDeleted)
{
File.Delete(rarstobedeleted);
}
}
else
{
Console.WriteLine("Thats not an option try again");
}
Console.WriteLine("Cleaning Complete.");
;
}
}
}
}
This work effectively for rar files only for the time being but will effectively clean up any directories where someone may have downloaded a large amount of files stored in separated rars
I have an unusual situation here.
Problem
I'm using Visual studio (VS) to write scripts to use in-game in the game Space Engineers.
The problem is that you only use a portion of the code from the file in-game. (I.E, Ctrl+A wont do). So selecting the correct portion is tedious.
I want to streamline the process of copying the desired code in VS and pasting it in Space Engineers.
The idea is to trim all unnecessary white space (there's a character limit) and copy to clipboard when pressing run in VS.
Where I'm at
I've found that you can make your own build configuration and use the "Pre-build event command line" to run something custom. The idea is to make a simple console application that does what I described above. But I don't know how to get the correct file to send to said application.
Am I on the right track? How do I send the desired file to the trimming application? Is there a better way?
Edit:
This is what I had in mind when I said "simple console application".
It does everything I needed it to do (trimming white-space and adding a portion of the code to clipboard). Only thing missing is that I have to specify the file name I want it to use. Which isn't important, it would just be nice.
using System;
using System.Windows.Forms;
namespace TrimFileToClipboard
{
class Program
{
[STAThread()]
static void Main(string[] args)
{
string startString = (args.Length > 1) ? "#region " + args[1] : "#region in-game";
string line;
string trimmed = "";
bool read = false;
int depth = 0;
System.IO.StreamReader file = new System.IO.StreamReader(args[0]);
while ((line = file.ReadLine()) != null)
{
if (!read && line.Contains(startString)) read = true;
else if (read && line.Contains("#region")) depth++;
else if (read && line.Contains("#endregion"))
{
if (depth == 0) break;
else if (depth < 0)
{
Console.WriteLine("There's something wrong with your #regions. Please edit the file.");
Console.ReadLine();
Environment.Exit(0);
}
else depth--;
}
else if (read) trimmed += line.Trim() + "\n";
}
file.Close();
Clipboard.SetText(trimmed);
}
}
}
It can be used by adding
"<path>\TrimFileToClipboard.exe" "$(ProjectDir)<classname>.cs"
to Pre-build event command line, in the project properties/Build events. Where <path> is the path to the application above and <classname> is the file you want to process.
Maybe I should post this part as an answer but I don't know if it's a decent approach or an ugly hack.
Instead of coping the code to the clipboard, I save it directly inside the game as saved workshop script with this simple C# console application.
The SE script I edit using VS has the comments \\script-begin and \\script-end to tell the application where to look for the actual code that needs to be in the programmable block.
After the execution the script will be available at the local workshop. It makes it very easy to work with the SE scripts, whenever I make a change using VS, I run the console application again and the script will be updated inside the game.
internal class Program
{
private static void Main(string[] args)
{
String[] InputLines, outputLines;
Int32 scriptBegin = 0, scriptEnd = 0;
String scriptName = args[0];
String inputPath = "C:\\Users\\hfand\\source\\repos\\se-scripts\\" + scriptName + ".cs";
if (File.Exists(inputPath))
{
InputLines = File.ReadAllLines(inputPath);
for (int i = 0; i < InputLines.Length; i++)
{
if (InputLines[i].Contains("script-begin"))
{
scriptBegin = i + 1;
}
if (InputLines[i].Contains("script-end"))
{
scriptEnd = i - 1;
}
}
outputLines = new List<string>(InputLines).GetRange(scriptBegin, scriptEnd - scriptBegin + 1).ToArray();
for (int i = 0; i < outputLines.Length; i++)
{
if (outputLines[i].Length >= 8)
{
outputLines[i] = outputLines[i].Substring(8);
}
}
String outputPath = "C:\\Users\\hfand\\AppData\\Roaming\\SpaceEngineers\\IngameScripts\\local\\" + scriptName;
if (Directory.Exists(outputPath))
{
File.WriteAllLines(outputPath + "\\Script.cs", outputLines);
}
else
{
Directory.CreateDirectory(outputPath);
File.WriteAllLines(outputPath + "\\Script.cs", outputLines);
}
Console.WriteLine(scriptName + " sincronizado");
}
else
{
Console.WriteLine("Arquivo \"" + inputPath + "\" não encontrado");
}
}
}
Here is an example of how the code in VS should look like
using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using VRageMath;
using VRage.Game;
using Sandbox.ModAPI.Interfaces;
using Sandbox.ModAPI.Ingame;
using Sandbox.Game.EntityComponents;
using VRage.Game.Components;
using VRage.Collections;
using VRage.Game.ObjectBuilders.Definitions;
using VRage.Game.ModAPI.Ingame;
using SpaceEngineers.Game.ModAPI.Ingame;
namespace BlankScript
{
public class Program : MyGridProgram
{
//script-begin
public Program()
{
}
public void Save()
{
}
public void Main(string argument, UpdateType updateSource)
{
}
//script-end
}
}
You can write a C# command with my Visual Commander extension that gets active file path in Visual Studio as DTE.ActiveWindow.Document.FullName and then runs your file.ReadLine() loop over it and calls Clipboard.SetText(trimmed) at the end. See for example Copy current file, line, method sample code.
I have written a python script to parse a xml file. I'm calling this file from C# project. But when running a program I'm getting error: No Module named xml.etree.cElementTree.
Program.cs
-----------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using IronPython.Hosting;
using IronPython.Modules;
namespace RunExternalScript
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Press enter to execute the python script!");
Console.ReadLine();
var py = Python.CreateEngine();
try
{
py.ExecuteFile("wg.py");
}
catch (Exception ex)
{
Console.WriteLine(
"Oops! We couldn't execute the script because of an exception: " + ex.Message);
}
Console.WriteLine("Press enter to exit...");
Console.ReadLine();
}
}
}
wg.py
-----
import xml.etree.cElementTree as ET
tree = ET.parse('Wg.xml')
root = tree.getroot()
childrens = root.getchildren()
for p in root.findall('WGTemplate'):
name = p.find('TemplateName').text
# print(name)
loc = p.find('Filename').text
# print(loc)
for p1 in p.findall('Product'):
print("{:<50}{:<50}{:>50}".format(name, loc, p1.text))
Note: There is no folder or file with name 'xml'
set your python path, to know your system path
in .py file just type
import sys
print(sys.path)
and with this you will get your sys path and set those all path in
ScriptEngine engine = Python.CreateEngine(); //For Engine to initiate the script
List<string> pathes = engine.GetSearchPaths().ToList();
pathes.AddRange(new[]
{
#"<add your all path here>"
});
engine.SetSearchPaths(pathes);
i hope my answer help you to solve your problem.
Iam trying to get the dht implementation of monotorrent to work but i just cant seem to find any peers.
ive tried most of the examplecode code availeble on the net like the testclient and dhttest.
I have tried with several diffrent infohashes.
Anyone here got it working? or do you know where i can find the devs?
This is how my code looks atm:
using System;
using System.Collections.Generic;
using System.Text;
using MonoTorrent.Dht;
using MonoTorrent.Dht.Listeners;
using System.Net;
using System.IO;
using MonoTorrent.Common;
using MonoTorrent.Tracker.Listeners;
namespace SampleClient
{
class Program
{
static void Main(string[] args)
{
string basePath = Environment.CurrentDirectory;
string torrentsPath = Path.Combine(basePath, "Torrents");
Torrent torrent = null;
// If the torrentsPath does not exist, we want to create it
if (!Directory.Exists(torrentsPath))
Directory.CreateDirectory(torrentsPath);
// For each file in the torrents path that is a .torrent file, load it into the engine.
foreach (string file in Directory.GetFiles(torrentsPath))
{
if (file.EndsWith(".torrent"))
{
try
{
// Load the .torrent from the file into a Torrent instance
// You can use this to do preprocessing should you need to
torrent = Torrent.Load(file);
Console.WriteLine(torrent.InfoHash.ToString());
}
catch (Exception e)
{
Console.Write("Couldn't decode {0}: ", file);
Console.WriteLine(e.Message);
continue;
}
}
}
DhtListener listener = new DhtListener(new IPEndPoint(IPAddress.Parse("192.168.2.3"), 10000));
DhtEngine engine = new DhtEngine(listener);
//engine.RegisterDht(dht);
byte[] nodes = null;
if (File.Exists("mynodes"))
nodes = File.ReadAllBytes("mynodes");
listener.Start();
int i = 0;
bool running = true;
StringBuilder sb = new StringBuilder(1024);
while (running)
{
engine.Start(nodes);
while (Console.ReadLine() != "q")
{
engine.GetPeers(torrent.InfoHash);
}
File.WriteAllBytes("mynodes", engine.SaveNodes());
}
}
}
}
I know it's very old question, I'm not sure why it's still noone has answer it, anyway. The problem seem to be this line:
DhtListener listener = new DhtListener(new IPEndPoint(IPAddress.Parse("192.168.2.3"), 10000));
This ip is not the real ip, so you actually asl peers to send the respone to unkonw adress.
What to do? register your own adress.
I tring to test a new dll that I've build for c#
private void button1_Click(object sender, EventArgs e)
{
String [] first = UserQuery.Get_All_Users();
//MessageBox.Show(first);
}
but I get the following error at String [] first = UserQuery.Get_All_Users();
An unhandled exception of type 'System.NullReferenceException' occurred in User_Query.dll
Additional information: Object reference not set to an instance of an object.
I been tring to figure this one out for hours but can't find any null varibles
I post my dll in case the dll is wrong
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.DirectoryServices;
namespace User_Query
{
public class UserQuery
{
public static string[] Get_All_Users()
{
string[] names = new string[10];
var path = string.Format("WinNT://{0},computer", Environment.MachineName);
using (var computerEntry = new DirectoryEntry(path))
{
var userNames = from DirectoryEntry childEntry in computerEntry.Children
where childEntry.SchemaClassName == "User"
select childEntry.Name;
byte i = 0;
foreach (var name in userNames)
{
Console.WriteLine(name);
names[i] = name;
i++;
}
return names;
}
}
}
}
There is a problem with your. path variable... since there should be \\ instead of //
The problem here turned out not to be the code but be VS2010 not loading the dll. This happen because I decided to change the program from using the dll from the debug to the release version but I did not clean the project after doing it and therefore the program was not correctly loading the dll. All that need to be done was clean the project