Renci SSH.NET SCP Download fails, but doesn't tell me why - c#

I'm working on a program in C# which downloads a file from a remote server. I set up the connection (like I did for the upload function) like this:
void execute_scp_download(ScpClient scpclient, string remoteFilePath, string targetPath) {
var downloadFilestream = File.OpenWrite(targetPath);
try {
scpclient.Download(remoteFilePath, downloadFilestream);
scpclient.Disconnect();
} catch (Exception e) {
log_error("download could not be done: " + e);
}
}
scpclient gets created in the calling method where I can successfully write scpclient.Connect() without any problems.
But when I try to download a file it'll throw an exception:
30.07.2020 11:08:02 Error: download could not be done: Renci.SshNet.Common.ScpException: scp: /usr/local/etc/cert.der
at Renci.SshNet.ScpClient.ReadString(Stream stream)
at Renci.SshNet.ScpClient.InternalDownload(IChannelSession channel, Stream input, FileSystemInfo fileSystemInfo)
at Renci.SshNet.ScpClient.Download(String filename, FileInfo fileInfo)
at SMGWUpdateTool.Form1.execute_scp_download(ScpClient scpclient, String remoteFilePath, String targetPath) in C:\bla\myscript.cs Line:226.
(I translated some of the words but none of the exception itself)
I have no clue why this doesn't work. It looks like it is an problem with the target file. The remote server is a BusyBox/Linux while my client is running on Windows 10.
Is there any way to fix this?

Related

The specified network name is no longer available - C# Console Application

I am trying to read files from different server, using c# console application, but it gives error - "The specified network name is no longer available".
When I ping the server, i am getting a reply, but when I run the exe file of project that has code to access files from server it shows the mentioned error.
The path I am using is in this format: \\xxx.xxx.xx.x\EEE\EEE\FolderName
The code that access/read files:
public List<string> GetFiles()
{
List<string> filelist = null;
string fileFromPath = help.fileFromPath;
try
{
filelist = Directory.GetFiles(fileFromPath).ToList();
if (filelist.Count == 0)
{
log.Error("No file to be processed.");
}
}
catch (Exception ex)
{
log.Error(ex.Message);
}
return filelist;
}
Where help.fileFromPath has path value and it is stored in app.config
What could be the reason and how could it be fixed?

Opening a document from Imanage in Word 2016

I am attempting to open an Imanage document, in MS Word, within a temporary test application (for debugging) to later copy over into an ActiveX control project. The error that is popping up is:
Exception thrown at 0x7618851A (msvcrt.dll) in w3wp.exe: 0xC0000005: Access >violation reading location 0x09801000.
If there is a handler for this exception, the program may be safely continued.
The error occurs when running the cmd.Execute line and I am unsure as to why I am getting the error.
using IManage;
using IMANEXTLib;
using System;
namespace WebApplication3
{
public partial class WebForm2 : System.Web.UI.Page
{
IManDatabase imanagedatabase;
IManDMS myDMS = new ManDMSClass();
protected void Page_Load(object sender, EventArgs e)
{
openImanageDoc("docNumber", "versionNumber", "server", "database", ReadOnly);
}
public void imanageLogin(string server, string database)
{
try
{
IManSession session = myDMS.Sessions.Add(server);
IManWorkArea oWorkArea = session.WorkArea;
session.TrustedLogin();
foreach (IManDatabase dbase in session.Databases)
{
if (dbase.Name == database)
{
imanagedatabase = dbase;
}
}
}
catch (Exception ex)
{
throw ex;
}
}
public void openImanageDoc(string docNo, string versionNo, string server, string database, bool isReadOnly = true)
{
IManDocument doc;
try
{
imanageLogin(server, database);
int iDocNo = int.Parse(docNo);
int iVersion = int.Parse(versionNo);
doc = imanagedatabase.GetDocument(iDocNo, iVersion);
openNRTDocument(ref doc, isReadOnly);
imanagedatabase.Session.Logout();
myDMS.Close();
}
catch (Exception Ex)
{
imanagedatabase.Session.Logout();
throw Ex;
}
finally
{
imanagedatabase = null;
myDMS = null;
}
}
public void openNRTDocument(ref IManDocument nrtDocument, Boolean isReadonly)
{
OpenCmd cmd = new OpenCmd();
ContextItems objContextItems = new ContextItems();
objContextItems.Add("NRTDMS", myDMS);
objContextItems.Add("SelectedNRTDocuments", new[] { (NRTDocument)nrtDocument.LatestVersion });
objContextItems.Add("IManExt.OpenCmd.Integration", false);
objContextItems.Add("IManExt.OpenCmd.NoCmdUI", true);
cmd.Initialize(objContextItems);
cmd.Update();
cmd.Execute();
}
}
}
Due to the nature of the error, I am presuming it is a configuration issue rather than a code error although I could be completely wrong as I am very new to programming.
I have found out that w3wp.exe is an IIS worker process created by the app pool but other than that I have no idea what the numeric code represents. Any help or advice is greatly appreciated.
The error is being raised by the OpenCmd instance because it is most likely trying to access resources such as local registry settings. It's not possible to do that in a web application, unless you host your code in a proprietary technology like ActiveX (which is specific to Internet Explorer)
Actually, it is not appropriate for you to use OpenCmd here. Those type of commands (iManage "ICommand" implementations) are intended to be used in regular Windows applications that have either the iManage FileSite or DeskSite client installed. These commands are all part of the so-called Extensibility COM libraries (iManExt.dll, iManExt2.dll, etc) and should not be used in web applications, or at least used with caution as they may inappropriately attempt to access the registry, as you've discovered, or perhaps even display input Win32 dialogs.
For a web app you should instead just limit yourself to the low-level iManage COM library (IManage.dll). This is in fact what iManage themselves do with their own WorkSite Web application
Probably what you should do is replace your openNRTDocument method with something like this:
// create a temporary file on your web server..
var filePath = Path.GetTempFileName();
// fetch a copy of the iManage document and save to the temporary file location
doc.GetCopy(filePath, imGetCopyOptions.imNativeFormat);
In an MVC web application you would then just return a FileContentResult, something like this:
// read entire document as a byte array
var docContent = File.ReadAllBytes(filePath);
// delete temporary copy of file
File.Delete(filePath);
// return byte stream to web client
return File(stream, MediaTypeNames.Application.Octet, fileName);
In a Web Forms application you could do something like this:
// set content disposition as appropriate - here example is for Word DOCX files
Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
// write file to HTTP content output stream
Response.WriteFile(filePath);
Response.End();

Webclient causing an invalid operation exception

I'm trying to download a simple xml file and save it to the users local profile. When trying to download (i don't think this has anything to do with the saving location but i'm not 100% sure) i get the following exception on the webclient.
System.InvalidOperationException
My code is as follows;
public void downloadProxy() {
string url = Properties.Settings.Default.url;
string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "/netsettings/proxies.xml");
try
{
WebClient GrabFile = new WebClient();
GrabFile.DownloadFile(url, path);
}
catch (WebException webEx)
{
if (webEx.Status == WebExceptionStatus.ConnectFailure)
{
Console.WriteLine("Are you behind a firewall? If so, go through the proxy server.");
}
}
}
If you are on a Windows operating system, use a backslash (not a slash) as folder separator:
\netsettings\proxies.xml

How to send a local file through a REST service?

I am developing a REST web service using WCF and C# (VS 2010). I want to develop an operation like this:
doSomethingWithAFile(String filePath)
so it would be invoked like this:
GET http://my.web.service/endpoint?filePath={filePath}
filePath is a file path in the client (not in the server). So, when invoked, that operation has to send the file pointed by the path to the server so that the server can do some operations with the data contained in the file.
How can I achieve this?
EDIT: As stated in the comment I made, I would set a shared folder in the client, so I send the path and the server reads the file in the folder.
On your server, you will have to have a service with a method that accepts a string input, which you call with the file path from the client application.
You then read/copy/whichever the file from that location, on your server via normal file IO methods.
An example of how to do this you can find below.
The definition of ServerPleaseFetchThisFile naturally depends on what kind of webservice this would be, WCF or IIS web service or self made web service.
public bool ServerPleaseFetchThisFile(string targetPath)
{
// targetPath should enter from the client in format of \\Hostname\Path\to\the\file.txt
return DoSomethingWithAFile(targetPath);
}
private bool DoSomethingWithAFile(string targetFile)
{
bool success = false;
if (string.IsNullOrWhiteSpace(targetFile))
{
throw new ArgumentNullException("targetFile", "The supplied target file is not a valid input.");
}
if (!File.Exists(targetFile))
{
throw new ArgumentNullException("targetFile", "The supplied target file is not a valid file location.");
}
try
{
using (FileStream targetStream = new FileStream(targetFile, FileMode.Open, FileAccess.Read))
{
// Do something with targetStream
success = true;
}
}
catch (SecurityException se)
{
throw new Exception("Security Exception!", se);
// Do something due to indicate Security Exception to the file
// success = false;
}
catch (UnauthorizedAccessException uae)
{
throw new Exception("Unathorized Access!", uae);
// Do something due to indicate Unauthorized Access to the file
// success = false;
}
return success;
}

Upload to FTP server C# using Tamir.SharpSSH

Im able to connect with my sftp server and I'm sure of it because I get the list of files of my server and it passes correct list. But I cant upload file to a folder in mysftp server. Here is my code:
private static void FileUploadUsingSftp(string SFTPAddress, string SFTPUserName, string SFTPPassword,
string SFTPFilePath, string FileName)
{
Sftp sftp = null;
try
{
sftp = new Sftp( SFTPAddress,SFTPUserName , SFTPPassword);
// Connect Sftp
sftp.Connect();
MessageBox.Show("Connected!");
//Check if im surely connected
//list down files in my sftp server folder u01
ArrayList list;
list = sftp.GetFileList("//u01");
foreach (string item in list)
{
MessageBox.Show(item.ToString());
}
MessageBox.Show(list.Count.ToString());
// upload file
sftp.Put(FileName, "//u01"); -----> **I get exception here**
MessageBox.Show("UPLOADED!");
// Close the Sftp connection
sftp.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
if (sftp != null)
{
sftp.Close();
}
}
}
I recieve this exception:
"Exception of type 'Tamir.SharpSsh.jsch.SftpException' was thrown."
at Tamir.SharpSsh.jsch.ChannelSftp.put(String src, String dst, SftpProgressMonitormonitor, Int32 mode)
at Tamir.SharpSsh.Sftp.Put(String fromFilePath, String toFilePath)
I've tried using sftp.Put(FileName,SFTPAddress + "//u01");
Ive tried sftp.Put(FileName,SFTPAddress); And it do work but when I look at my sftp server if the file is there, it isn't.
I've tried sftp.Put(FileName,"//u01"); and it throws the same error.
I must upload my file in a folder in my ftp server and one of the folder is u01.
Can anyone help me out. I don't know what's wrong. I'm sure that i'm connected. and when I tried to upload using filezilla it do work so I'm not restricted in writing to our sftp server.
I believe that you have to enter the full filename in your call to Put.
string strippedFileName = StripPathComponent(FileName);
sftp.Put(FileName,"//u01//" + strippedFileName);
Note that StripPathComponent is not implemented, you will have to implement that as well if needed. It would strip a path component from FileName, i.e. remove C:\...\ or ..\...\.
I was also searching for how to upload a file from local/shared path to SFTP server using this library and finally found the solution. You can use the below code.
string host="ssgty";
string username="usr";
string password="passw";
int port=22;
string fromFile=#"D:\Test.txt";
string toFile=#"/dmon/myfolder/Test.txt";
public string CopyToFTP(string host, string username, string password, int port, string fromFile, string toFile)
{
string error = "";
try
{
Scp scp = new Scp(host, username, password);
scp.Connect(port);
scp.To(fromFile, toFile);
}
catch (Exception ex)
{
error = ex.Message;
}
return error;
}

Categories