Use URL instead of hostname with WinSCP .NET assembly - c#

I am using WinSCP to upload a file to an FTP host. But I only had ftp://xxx.xx.xx.xx path, not hostname like ftp.example.com.
Can I use ftp://xxx.xx.xx.xx for hostname?
My code is based on
SessionOptions sessionOptions = new SessionOptions
{
Protocol = Protocol.Ftp,
HostName = "example.com",
UserName = "user",
Password = "mypassword",
};
// Configure proxy
sessionOptions.AddRawSettings("ProxyMethod", "3");
sessionOptions.AddRawSettings("ProxyHost", "proxy");
using (Session session = new Session())
{
// Connect
session.Open(sessionOptions);
// Upload file
string localFilePath = #"C:\path\file.txt";
string pathUpload = "/file.txt";
session.PutFiles(localFilePath, pathUpload).Check();
}

The ftp://xxx.xx.xx.xx URL specify that you want to connect with FTP protocol to xxx.xx.xx.xx host.
That's what you do in WinSCP .NET assembly by setting SessionOptions.Protocol and SessionOptions.HostName:
var sessionOptions = new SessionOptions
{
Protocol = Protocol.Ftp,
HostName = "xxx.xx.xx.xx",
...
};
Or you can use SessionOptions.ParseUrl:
var sessionOptions = new SessionOptions();
sessionOptions.ParseUrl("ftp://xxx.xx.xx.xx");
...

Related

How do I rename file before sending

I am using Mailkit with c# to send an email with an attachment.
How do I rename the attachment before sending the email?
I am currently using the code below but throws an error when deployed in IIS.
var username = "username";
var password = "password";
var displayname = "display";
var from = new MailboxAddress(displayname, username);
var to = new MailboxAddress("User", emailto);
msg.From.Add(from);
msg.To.Add(to);
msg.Subject = emailsubject;
var attachment = new MimePart("application","zip")
{
Content = new MimeContent(File.OpenRead(Path.Combine(fileutil.GetDir, "originalname.zip"))),
ContentDisposition = new ContentDisposition(ContentDisposition.Attachment),
ContentTransferEncoding = ContentEncoding.Base64,
FileName = "new filename.zip"
};
var msgbody = new BodyBuilder
{
HtmlBody = string.Format(#"Message"),
TextBody = "Test Message!"
};
msgbody.Attachments.Add(attachment);
msg.Body = msgbody.ToMessageBody();
var client = new SmtpClient();
client.Connect("smtp-mail.outlook.com", 587, SecureSocketOptions.StartTls);
client.Authenticate(username, password);
client.Send(msg);
client.Disconnect(true);
client.Dispose();
Edit: After a bit of digging, I found out that this is the exception thrown
The server's SSL certificate could not be validated for the following reasons:
• The server certificate has the following errors:
• The revocation function was unable to check revocation for the certificate.
• The revocation function was unable to check revocation because the revocation server was offline.
• An intermediate certificate has the following errors:
• The revocation function was unable to check revocation for the certificate.
• The revocation function was unable to check revocation because the revocation server was offline.```
Try this:
var client = new SmtpClient();
client.ServerCertificateValidationCallback = (o, c, ch, e) => true;
client.Connect("smtp-mail.outlook.com", 587, SecureSocketOptions.StartTls);
client.Authenticate(username, password);

Basic authentication requires a secure connection to the server. in TFS

I was try to connect my TFS server using my credentials . But i am getting error 'Basic authentication requires a secure connection to the server.'
string username = "adminuser";
string pwd = "mypassword";
string domain = "http://localhost:8080/tfs/defaultcollection";
NetworkCredential networkCredential = new NetworkCredential(username, pwd);
BasicAuthCredential basicAuthCredential = new BasicAuthCredential(networkCredential);
TfsClientCredentials tfsClientCredentials = new TfsClientCredentials(basicAuthCredential)
{
AllowInteractive = false
};
TfsTeamProjectCollection tfs = new TfsTeamProjectCollection(new Uri(domain), tfsClientCredentials);
tfs.EnsureAuthenticated();
My tfs didn't have the https. Any alternative to fix it But browser level it is working fine
The BasicAuthCredential requires https://, I believe, and I wasn't able to access my TFS with https://. So I found another way to get from NetworkCredential to VssCredentials.
string username = "adminuser";
string pwd = "mypassword";
string domain = "http://localhost:8080/tfs/defaultcollection";
NetworkCredential networkCredential = new NetworkCredential(username, pwd);
//BasicAuthCredential basicAuthCredential = new BasicAuthCredential(networkCredential);
Microsoft.VisualStudio.Services.Common.WindowsCredential winCred = new Microsoft.VisualStudio.Services.Common.WindowsCredential(networkCredential);
VssCredentials vssCred = new VssClientCredentials(winCred);
TfsTeamProjectCollection tfs = new TfsTeamProjectCollection(new Uri(domain), vssCred);
tfs.EnsureAuthenticated();
Try using the following code:
String collectionUri = "http://localhost:8080/tfs/defaultcollection";
VssCredentials creds = new VssClientCredentials();
creds.Storage = new VssClientCredentialStorage();
VssConnection connection = new VssConnection(new Uri(collectionUri), creds);

Unable to connect to FTP Server with SOCKS5 using WinSCP

I choose WinSCP so I can implement a SOCKS5 Proxy into my FTP Client.
With the Proxy commented out I am able to connect and download files from a FTP Server without a proxy.
If I try to connect to the FTP Server with SOCKS5 Proxy I am unable to connect.
Any erros in my proxy configuration or something ? LoginData is correct, works with filezilla.
public void Download(string LocalFile)
{
try
{
// Setup session options
SessionOptions sessionOptions = new SessionOptions
{
Protocol = Protocol.Ftp,
HostName = LoginData.Servername,
UserName = LoginData.Username,
Password = LoginData.Passwort,
};
// Configure proxy
sessionOptions.AddRawSettings("ProxyMethod", "2"); // socks5 proxy
sessionOptions.AddRawSettings("ProxyHost", "***"); //host ip
sessionOptions.AddRawSettings("ProxyPort", "***"); //Port
sessionOptions.AddRawSettings("ProxyUsername", "***"); //Username
sessionOptions.AddRawSettings("ProxyPassword", "***"); //Password
using (Session session = new Session())
{
session.DisableVersionCheck = true;
// Connect
session.Open(sessionOptions);
// Download files
TransferOptions transferOptions = new TransferOptions();
transferOptions.TransferMode = TransferMode.Binary;
TransferOperationResult transferResult;
transferResult =
session.GetFiles(LoginData.RemoteFile, LocalFile, false, transferOptions);
// Throw on any error
transferResult.Check();
// Print results
foreach (TransferEventArgs transfer in transferResult.Transfers)
{
Console.WriteLine("Download of {0} succeeded", transfer.FileName);
}
}
}
catch (Exception e)
{
Console.WriteLine("Error: {0}", e);
}
}
With FileZilla, your proxy host is socks.cgm.ag - CGM
With WinSCP, your proxy host is socks.cmg.ag - CMG

How to connect LDAP server with username and password?

When I use AuthenticationTypes.Anonymous to connect to LDAP server, it`s ok:
var a = new DirectoryEntry("LDAP://localhost:389/dc=maxcrc,dc=com", "", "", AuthenticationTypes.Anonymous);
but when I want to use username and password to connect the server:
var a = new DirectoryEntry("LDAP://localhost:389/dc=maxcrc,dc=com", "cn=Manager,dc=maxcrc,dc=com", "111111");
it causes a "Specifying an invalid dn syntax" error:
If I use this:
var a = new DirectoryEntry("LDAP://localhost:389/dc=moe,dc=com", "cn=Manager,dc=moe,dc=com", "111111", AuthenticationTypes.Encryption);
it causes an "The server is not operational" error:
So how can I connect to my LDAP server with username and password?
here's some of my piece of code when connecting to LDAP and authenticating the user used.
private DirectoryEntry dEntry = null;
private DirectorySearcher dSearch = null;
//Validate User Credentials in Active Directory
dEntry = new DirectoryEntry(ADPath, userName, password, AuthenticationTypes.Secure);
dSearch = new DirectorySearcher(dEntry);
dSearch.PageSize = 1000;
dSearch.PropertiesToLoad.Add("cn");
if (dSearch.FindOne() != null)
{
//success
}
for validate username and password use this code
using(PrincipalContext pc = new PrincipalContext(ContextType.Domain, "YOURDOMAIN"))
{
// validate the credentials
bool isValid = pc.ValidateCredentials("myuser", "mypassword");
}
and for connect with username and password try this
DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://example.com", "username", "password");
Thank you everyone!I slove it by using the AuthenticationTypes.None
My situation is my ldap server is openssh on windows

Email attachement using uri via smptclient and C#

i have to do the following: my documents are stored on a server. The only path i'm getting is an URI
I was trying to get the document but i'm keep getting a "403 Forbidden".
string[] myArray = context.Request.QueryString["ItemsArray"].Split(',');
MailMessage m = new MailMessage(new MailAddress("bart#schelkens.be"),
new MailAddress("bart#schelkens.be")
);
m.Subject = "Emailing documents";
foreach (string path in myArray)
{
using (WebClient wb = new WebClient())
{
wb.UseDefaultCredentials = false;
wb.Credentials = new NetworkCredential(_userName, _passWord);
var stream = wb.OpenRead(path);
m.Attachments.Add(new Attachment(stream, ""));
}
}
string mailBody = "Dear<BR/> Please find attached a new version of the documents.";
mailBody += "<BR/>";
m.Body = mailBody;
m.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient("hybrid.kaneka.be");
smtp.EnableSsl = false;
smtp.Send(m);
Or is there another way to get my document from the website and then mail it?
In SharePoint I created my own button which, using a js-file, goes to my ashx to mail my documents.
Try to add the following line before opening the stream:
wb.Headers.Add("User-Agent: Other");
It could be, that it's forbidden because your server doesn't think, that you are a trusted client and blocks all connections without a User-Agent.
[edit 1]
If you try to download a file from SharePoint you have to use the SharePointOnlineCredentials from the SharePoint Server 2013 Client Components SDK:
Somewhere you have to define the credentials:
const string username = "username";
const string password = "password";
var securedPassword = new SecureString();
foreach (var c in password.ToCharArray()) securedPassword.AppendChar(c);
var credentials = new SharePointOnlineCredentials(username, securedPassword);
After that you can user this credentials in your WebClient:
wb.Credentials = credentials;
[edit 2]
If your on in an on-premises environment than you could use NetworkCredentials. Try to use the following:
wb.Credentials = new NetworkCredential("DOMAINNAME\username", "password");
[edit 3]
Maybe your server wants a real User-Agent. Because if something is wrong with your credentials there would be a 401 (unauthorized). For example try:
wb.Headers.Add("user-agent", " Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.0) Gecko/20100101 Firefox/25.0");
Provide the READ/WRITE rights/permission on the folder where your document is located.
Currently there is no read/write rights/permission on that folder that's why when ever you try to attach the document it returns 403 Forbidden error.

Categories

Resources