org.apache.velocity.exception.ResourceNotFoundException: Unable to find resource 'verificationEmail.vm' - spring-mvc

I have seen the solution regarding this question but i did not found any solution for my scenario.
my mailsender.xml is
<bean id="velocityEngine"
class="org.springframework.ui.velocity.VelocityEngineFactoryBean">
<property name="resourceLoaderPath" value="/email_Templates" />
<property name="preferFileSystemAccess" value="false" />
</bean>
and my velocity implementation code is..
public void sendUserActivationMail(User user, String requestUrl) throws Exception {
String plainText = System.currentTimeMillis() + "##" + user.getUserId();
userDao.insertRegistraionToken(user.getUserId(), plainText, "123456");
String token = AESEncrypter.encrypt(plainText);
String url = requestUrl + "/activateUser.htm?token=" + URLEncoder.encode(token, "UTF-8");
try {
Map<String, Object> storemap = new HashMap<String, Object>();
storemap.put("toUserName", user.getName());
storemap.put("fromUseerName", ApplicationConstants.TEAM_NAME);
storemap.put("url", url);
String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "verificationEmail.vm", "UTF-8", storemap);
mailService.sendMail(senderMailId, new String[] { user.getEmail() }, null, "Registration Activation", text);
} catch (Exception e) {
logger.println(IMessage.ERROR,new StringBuilder(CLASS_NAME).append("::runProfileIncompleteCron() exception ==" + e));
}
}
my folder structure is-
src/main/resources
|_email_Templates
|
|__verificationEmail.vm
But is shows error
org.apache.velocity.exception.ResourceNotFoundException: Unable to find resource 'verificationEmail.vm'

Related

Error while reading metadatafile using activityInfo.LoadXmlMetaData()

Implementing weakfulIntentService in xamarin.android .
Problem while reading metadatafile.
eturn null while reading metadatafile xml file in BroadCastReceiver.
** XmlReader reader = activityInfo.LoadXmlMetaData(packageManager, WAKEFUL_META_DATA);**
BroadcastReceiver
namespace Squarelabs.Droid
{
[BroadcastReceiver]
public class AlarmReceiver : BroadcastReceiver
{
private static string WAKEFUL_META_DATA = "squrelabs.inspection";
public override void OnReceive(Context context, Intent intent)
{
WakefulIntentService.IAlarmListener alarmListener =
GetListener(context);
if (alarmListener != null)
{
if (intent.Action == null)
{
alarmListener.SendWakefulWork(context);
}
else
{
WakefulIntentService.ScheduleAlarms(alarmListener, context, true);
}
}
}
private WakefulIntentService.IAlarmListener GetListener(Context context)
{
PackageManager packageManager = context.PackageManager;
ComponentName componentName = new ComponentName(context, Class);
try
{
ActivityInfo activityInfo = packageManager.GetReceiverInfo(componentName, PackageInfoFlags.MetaData);
XmlReader reader = activityInfo.LoadXmlMetaData(packageManager, WAKEFUL_META_DATA);
while (reader!=null)
{
if (reader.IsStartElement())
{
if (reader.Name == "WakefulIntentService")
{
string className = reader.Value;
Class cls = Java.Lang.Class.ForName(className);
return ((WakefulIntentService.IAlarmListener)cls.NewInstance());
}
}
reader.MoveToNextAttribute();
}
} catch (NameNotFoundException e) {
throw new RuntimeException("Cannot find own info???", e);
} catch (XmlPullParserException e) {
throw new RuntimeException("Malformed metadata resource XML", e);
} catch (IOException e) {
//throw new RuntimeException("Could not read resource XML", e);
} catch (ClassNotFoundException e) {
throw new RuntimeException("Listener class not found", e);
} catch (IllegalAccessException e) {
throw new RuntimeException("Listener is not public or lacks public constructor", e);
} catch (InstantiationException e) {
throw new RuntimeException("Could not create instance of listener", e);
}
return (null);
}
}
manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:installLocation="auto" android:versionCode="2" android:versionName="1.9.5" package="squrelabs.inspection">
<uses-sdk android:minSdkVersion="15" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.android.alarm.permission.SET_ALARM" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application android:label="Squarelabs" android:icon="#drawable/icon">
<receiver android:name="AlarmReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
<meta-data android:name="squrelabs.inspection" android:resource="#xml/wakeful" />
</receiver>
</application>
xml in resource
<WakefulIntentService
listener="squrelabs.inspection.Droid.AppListener"
/>
Kindly help me to solve this issue.
Problem while reading metadatafile. eturn null while reading metadatafile xml file in BroadCastReceiver.
You can add attribute MetaData on your AlarmReceiver, and change android:resource="#xml/wakeful" code to load resource directly from string. For example:
[MetaData("mTag", Value = "#string/WakefulIntentService")]
string resource is like this:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">MetaDataDemo</string>
<string name="WakefulIntentService">squrelabs.inspection.Droid.AppListener </string>
</resources>
Then your final purpose is to get the ((WakefulIntentService.IAlarmListener)cls.NewInstance()), you can replace the code:
ActivityInfo activityInfo = packageManager.GetReceiverInfo(componentName, PackageInfoFlags.MetaData);
XmlReader reader = activityInfo.LoadXmlMetaData(packageManager, WAKEFUL_META_DATA);
while (reader!=null)
{
if (reader.IsStartElement())
{
if (reader.Name == "WakefulIntentService")
{
string className = reader.Value;
Class cls = Java.Lang.Class.ForName(className);
return ((WakefulIntentService.IAlarmListener)cls.NewInstance());
}
}
reader.MoveToNextAttribute();
}
With:
ComponentName cn = new ComponentName(context, Class);
ActivityInfo info = context.PackageManager.GetReceiverInfo(cn, PackageInfoFlags.MetaData);
System.String mTag = info.MetaData.GetString("mTag");
Class cls = Java.Lang.Class.ForName(mTag);
return cls.NewInstance();
Update:
try to replace this code with var listener = ReflectionHelper.CreateInstance<WakefulIntentService.IAlarmListener>("Demo.AppListener", Assembly.GetExecutingAssembly().FullName); and then change the string WakefulIntentService like this:
<string name="WakefulIntentService">yournamespace.AppListener</string>
The ReflectionHelper is like this:
public static class ReflectionHelper
{
public static T CreateInstance<T>(string fullName, string assemblyName)
{
string path = fullName + "," + assemblyName;
Type o = Type.GetType(path);
object obj = Activator.CreateInstance(o, true);
return (T)obj;
}
public static T CreateInstance<T>(string assemblyName, string nameSpace, string className)
{
try
{
string fullName = nameSpace + "." + className;
object ect = Assembly.Load(assemblyName).CreateInstance(fullName);
return (T)ect;
}
catch
{
return default(T);
}
}
}

StopWatch#stop(), throwing NPE

while working on interceptor with SpringMVC I'm getting NPE. I am using log4j.properties and here is the following code of interceptor
ThreadLocal<StopWatch> stopWatchLocal = new ThreadLocal<>();
Logger logger = Logger.getLogger(this.getClass());
#Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object object,
Exception exception) throws Exception {
StopWatch stopWatch = stopWatchLocal.get();
stopWatch.stop();//Line 24
logger.info("Total time taken for processing: " + stopWatch.getTotalTimeMillis() + " ms");
stopWatchLocal.set(null);
}
#Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object,
ModelAndView modelAndView) throws Exception {
logger.info("Request processing ended on " + getCurrentTime());
}
#Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
StopWatch stopWatch = new StopWatch(object.toString());
stopWatch.start(object.toString());
stopWatchLocal.set(stopWatch);
logger.info("Accessing URL path: " + getURLPath(request));
logger.info("Request processing started on: " + getCurrentTime());
return true;
}
private String getCurrentTime() {
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy 'at' hh:mm:ss");
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
return formatter.format(calendar.getTime());
}
private String getURLPath(HttpServletRequest request) {
String currentPath = request.getRequestURI();
String queryString = request.getQueryString();
queryString = queryString == null ? "" : "?" + queryString;
return currentPath + queryString;
}
this is the log
j
ava.lang.NullPointerException
at com.webstore.interceptor.PerformanceMontiorInterceptor.afterCompletion(PerformanceMontiorInterceptor.java:24)
at org.springframework.web.servlet.HandlerExecutionChain.triggerAfterCompletion(HandlerExecutionChain.java:167)
at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1023)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:952)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
interceptor in dispatcherServlet
<mvc:interceptors>
<bean class="com.package.InterceptorClass"></bean>
</mvc:interceptors>
Am I doing something wrong ?
Please Help, is my configuration is broken because I'm not able to get the answer why I am getting NPE

Upload file from applet to servlet using apache fileupload

To accomplish:
Upload a file from my local to server using an applet and servlet using apache fileupload jar.
Tried:
I have used a simple jsp, with a browse button and posted the action to my servlet (where I used apache fileupload). I was successful in uploading the file to the server.
Issue:
I am trying to upload a file, from my local machine, using an applet. I do not want to manually select files, instead upload files that are present in a specific folder. For now I have hardcoded the folder. I am able to look at the folder and get the list of files I want to upload.
Also, I have successfully established a connection from my applet to servlet.
Issue arises at the upload.parseRequest(request) in the servlet. I'm thinking its because the applet cannot post to servlet's request object.
Also, I have set the request type to multipart/form-data in my applet.
Right now, I am trying to pass the absolute path of the file to servlet and upload.
I have seen other posts where byte stream data is passed from applet to servlet, but the servlet uses the traditional File.write.
For me, it is mandatory to achieve this using apache fileupload.
Please suggest on how to pass a file/file path from applet to servlet, where the upload is handled by apache fileupload.
Below are my FileUploadHandler (where the HTTP requests are handled) and FileUpload(which is my applet)
Below is my FileUpload Handler:
#WebServlet(name = "FileUploadHandler", urlPatterns = { "/upload" })
#MultipartConfig
public class FileUploadHandler extends HttpServlet {
String uploadFolder ="";
#Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
System.out.println("doPost-servlet URL is: "
+ request.getRequestURL());
try {
uploadFolder = fileToUpload(request);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
uploadFolder = getServletContext().getRealPath("")+ File.separator;
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// process only if its multipart content
if (ServletFileUpload.isMultipartContent(request)) {
System.out.println("Yes, it is a multipart request...");
try {
List<FileItem> multiparts = upload.parseRequest(request);
System.out.println("Upload.parseRequest success !");
for (FileItem item : multiparts) {
if (!item.isFormField()) {
String name = new File(item.getName()).getName();
item.write(new File(uploadFolder + File.separator
+ name));
}
}
System.out.println("File uploaded to server !");
// File uploaded successfully
request.setAttribute("message", "File Uploaded Successfully");
} catch (Exception ex) {
request.setAttribute("message", "File Upload Failed due to "
+ ex);
}
} if(!ServletFileUpload.isMultipartContent(request)){
throw new ServletException("Content type is not multipart/form-data");
}
doGet(request, response);
//request.getRequestDispatcher("/result.jsp").forward(request, response);
OutputStream outputStream = response.getOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
objectOutputStream.writeObject("Success !");
objectOutputStream.flush();
objectOutputStream.close();
}
private String fileToUpload(HttpServletRequest request) throws IOException,
ClassNotFoundException {
ServletInputStream servletIn = request.getInputStream();
ObjectInputStream in = new ObjectInputStream(servletIn);
String uploadFile = (String) in.readObject();
System.out.println("Value in uploadFolder is: " + uploadFile);
return uploadFile;
}
Below is the fileupload applet:
public class FileUpload extends Applet {
private JButton capture;
private JTextField textField;
private final String pathDirectory = "C:\\";
private final String captureConfirmMessage = "Are you sure you want to continue?";
private final String confirmDialogTitle = "Confirm upload";
final File folder = new File(pathDirectory);
public void init() {
upload= new JButton("Upload");
textField = new JTextField();
capture.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int selection = JOptionPane.showConfirmDialog(upload,
uploadConfirmMessage, confirmDialogTitle,
JOptionPane.YES_NO_OPTION);
if (selection == JOptionPane.OK_OPTION) {
listFilesForFolder(folder);
} else if (selection == JOptionPane.CANCEL_OPTION) {
JOptionPane.showMessageDialog(upload,
"You have aborted upload", "Upload Cancelled", 2);
}
}
});
add(upload);
add(textField);
}
public void listFilesForFolder(final File folder) {
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
listFilesForFolder(fileEntry);
} else {
try {
onSendData(fileEntry.getAbsolutePath());
System.out.println(fileEntry.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
private URLConnection getServletConnection() throws MalformedURLException,
IOException {
// Open the servlet connection
URL urlServlet = new URL("http://localhost:8081/UploadFile/upload");
HttpURLConnection servletConnection = (HttpURLConnection) urlServlet
.openConnection();
// Config
servletConnection.setDoInput(true);
servletConnection.setDoOutput(true);
servletConnection.setUseCaches(false);
servletConnection.setDefaultUseCaches(false);
servletConnection.setRequestProperty("Content-Type", "multipart/form-data;");
servletConnection.connect();
return servletConnection;
}
private void onSendData(String fileEntry) {
try {
// Send data to the servlet
HttpURLConnection servletConnection = (HttpURLConnection) getServletConnection();
OutputStream outstream = servletConnection.getOutputStream();
ObjectOutputStream objectOutputStream= new ObjectOutputStream(
outstream);
objectOutputStream.writeObject(fileEntry);
// Receive result from servlet
InputStream inputStream = servletconnection.getInputStream();
ObjectInputStream objectInputStream = new ObjectInputStream(
inputStream);
String result = (String) objectInputStream.readObject();
objectInputStream.close();
inputStream.close();
out.flush();
out.close();
// Display result on the applet
textField.setText(result);
} catch (java.net.MalformedURLException mue) {
mue.printStackTrace();
textField.setText("Invalid serlvetUrl, error: " + mue.getMessage());
} catch (java.io.IOException ioe) {
ioe.printStackTrace();
textField.setText("Couldn't open a URLConnection, error: "
+ ioe.getMessage());
} catch (Exception e) {
e.printStackTrace();
textField.setText("Exception caught, error: " + e.getMessage());
}
}
public void paint(Graphics g) {
g.drawString("Click the button above to capture", 5, 50);
}
I could finally succeed posting the request to the servlet from the applet.
It was a simple logic that I was missing. I did not add the header and trailer while posting to the servlet, which was the key, in the servlet to identify the incoming request as a multipart data.
FileInputStream fileInputStream = new FileInputStream(new File(
fileEntry));
dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
dataOutputStream
.writeBytes("Content-Disposition: form-data; name=\"upload\";"
+ " filename=\"" + fileEntry + "\"" + lineEnd);
dataOutputStream.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dataOutputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
System.out.println(fileEntry + " uploaded.");
}
// send multipart form data necesssary after file data
dataOutputStream.writeBytes(lineEnd);
dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens
+ lineEnd);
I added the header and trailer and also used this to create the URL connection.
private URLConnection getServletConnection() throws MalformedURLException,
IOException {
// Open the servlet connection
URL urlServlet = new URL("http://localhost:8083/UploadFile/upload");
HttpURLConnection servletConnection = (HttpURLConnection) urlServlet
.openConnection();
// Config
servletConnection.setDoInput(true);
servletConnection.setDoOutput(true);
servletConnection.setUseCaches(false);
servletConnection.setDefaultUseCaches(false);
servletConnection.setRequestMethod("POST");
servletConnection.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + this.boundary);
servletConnection.setRequestProperty("Connection", "Keep-Alive");
servletConnection.connect();
return servletConnection;
}
Then, in the servlet, I was just reading the data using upload.ParseRequest(request).
Thank you for the help.

How to consume image upload data as byte[] using Spring MVC 3

I need write the image data in a particular directory on the server side but I am getting a null for the raw byte[] image upload data that I am trying to send from an html form and jquery ajaxuploader plugin from here.
Following is the snippet from the controller I am using to handle raw bytes of image being uploaded:
#RequestMapping(value = "uploadImage", method = RequestMethod.POST)
public void uploadImage(byte[] uploadData, Writer writer, HttpServletRequest request) throws IOException, JSONException {
//uploadData is turning out to be null
//..
}
#InitBinder
protected void initBinder(ServletRequestDataBinder binder) {
binder.registerCustomEditor(byte[].class,
new ByteArrayMultipartFileEditor());
}
I have got the following configured in the spring configuration file for handling uploads:
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
</bean>
I am using Spring MVC 3. Could someone guide me on how to send raw bytes of upload data?
Thanks.
First, if you're form is uploading an image, make sure your content type is "multipart/form-data". You might want to change your RequestMapping as follows:
#RequestMapping(value = "uploadImage", method = RequestMethod.POST, headers={"content-type=multipart/form-data"})
Also, I'd suggest using CommonsMultipartFile to handle the upload. Change your function signature as follows, where "fieldName" is the name of the input field in your form:
public void uploadImage(byte[] uploadData, Writer writer, HttpServletRequest request, #RequestParam("fieldName") CommonsMultipartFile file)
Then you can get the raw bytes as follows:
file.getBytes()
Make sure you include the commons-fileupload dependency for CommonsMultipartFile.
I'm using spring3 + jquery ajaxform and this works like a charm. Hope this helps!
Following is the JavaScript and HTML code I used on the client side that got things working:
JavaScript:
function createUploader(){
var uploader = new qq.FileUploader({
element: document.getElementById('file-uploader'),
action: 'uploadImage',
allowedExtensions: ['jpg', 'jpeg', 'png', 'gif'],
debug: true,
onSubmit: function(id, fileName){
console.log("id - " + id + ", fileName - " + fileName);
},
onComplete: function(id, fileName, responseJSON) {
console.log("responseJSON - " + responseJSON);
}
});
}
window.onload = createUploader;
HTML:
<div id="file-uploader" >
<noscript>
<p>Please enable JavaScript to upload your property location images</p>
</noscript>
</div>
Controller:
#Controller
public class FranchiseeLocationImageController {
private static final Log logger = LogFactory.getLog(FranchiseeLocationImageController.class);
#Autowired
private ServletContext servletContext;
#Autowired
private FranchiseeLocationImageService franchiseeLocationImageService;
#RequestMapping(value = "uploadImage", method = RequestMethod.POST)
public void uploadImage(byte[] qqfile, Writer writer, #RequestParam("qqfile") String img, HttpServletRequest request, HttpServletResponse response) throws IOException, JSONException{
FranchiseeLocationImage image = null;
PrintWriter pr = null;
InputStream is = null;
File file = null;
FileOutputStream fos = null;
String filename = request.getHeader("X-File-Name");
String imageId = FilenameUtils.removeExtension(img);
String imageFormat = franchiseeLocationImageService.getImageFormat();
String outputDir = servletContext.getRealPath("") + File.separator + franchiseeLocationImageService.getImagesDirectory() + File.separator;
File baseDirectory = null;
File output = null;
String path = FilenameUtils.removeExtension(img) + "." + imageFormat;
File outputDirectory = null;
HttpSession session = request.getSession();
/*
HttpSession session = request.getSession(false);
if(session == null) {
session = request.getSession();
}
*/
List<String> franchiseeLocationImages = (List<String>) session.getAttribute("franchiseeLocationImages");
if(franchiseeLocationImages == null) {
franchiseeLocationImages = new ArrayList<String>();
}
logger.debug( "filename - " + filename + " | img - " + img + " | img name - " + FilenameUtils.removeExtension(img) + " | img format - " + FilenameUtils.getExtension(img) + " | uploadData - " + qqfile + " | imageFormat - " + imageFormat);
/**
* Reading the image being uploaded and writing it to images/franchiseeLocation folder ["qqfile" is used instead of "X-File-Name" as "X-File-Name" gives encoded HTML name with "%20" for " "]
*/
try {
pr = response.getWriter();
is = request.getInputStream();
/*
baseDirectory = new File(outputDir);
baseDirectory.mkdirs();
file = new File(outputDir, FilenameUtils.removeExtension(img) + "." + imageFormat);
fos = new FileOutputStream(file);
int copiedNum = IOUtils.copy(is, fos);
*/
outputDirectory = new File(outputDir);
outputDirectory.mkdirs();
output = new File(outputDirectory, path);
BufferedImage sourceImage = ImageIO.read(is);
boolean written = ImageIO.write(sourceImage, imageFormat, output);
franchiseeLocationImages.add(img);
session.setAttribute("franchiseeLocationImages", franchiseeLocationImages);
logger.debug("franchiseeLocationImages - " + franchiseeLocationImages);
logger.debug("outputDirectory - " + outputDirectory + " | output - " + output + " | sourceImage - " + sourceImage + " | is - " + is + " | file - " + file + " |fos - " + fos + " | copiedNum - " + "copiedNum" + " | baseDirectory - " + baseDirectory + " | sourceImage - " + sourceImage + " | written - " + written);
/*
image = franchiseeLocationImageService.processProductImage(qqfile, imageId);
JSONObject json = new JSONObject();
json.put("path", image.getPath());
json.put("id", image.getId());
writer.write(json.toString());
*/
pr.print("{success: true}");
} finally {
writer.close();
/*
try {
fos.close();
is.close();
} catch (IOException ignored) {
}
*/
pr.flush();
pr.close();
}
}
#InitBinder
protected void initBinder(ServletRequestDataBinder binder) {
binder.registerCustomEditor(byte[].class,
new ByteArrayMultipartFileEditor());
}
private static String html2text(String html) {
return Jsoup.parse(html).text();
}
}

Upload file to Secured FTP in ASP.NET

I want to upload files to FTPS and SFTP. My code is currently using FtpWebRequest object to upload to FTP. What changes or class should I use to upload to FTP, FTPS and SFTP servers?
SFTP is not a built-in protocol for .NET, you'll have to use a third-party library, like SharpSSH; however, FTP and FTPS are. There are a number of third-party libraries both commercial and OpenSource (SSH Factory for .NET , Rebex SFTP for .NET/.NET CF, SharpSSH - A Secure Shell (SSH) library for .NET, Compare SFTP (SSH File Transfer Protocol) components for .NET (C#, VB.NET) - SecureBlackbox®) and you'll need to do some research to determine which one will best suit your needs.
Here's a sample console app I wrote that does FTP and FTPS using the .NET Framework's FtpWebRequest:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
namespace FtpSslTest
{
class Program
{
static void Main(string[] args)
{
string server = null;
do
{
Console.Write("Enter the server to connect to: ");
server = Console.ReadLine();
} while (IsServerValid(server) == false);
UriBuilder ftpUrl = new UriBuilder("ftp", server);
bool useSsl = GetYesNo("Use SSL?");
bool allowInvalidCertificate = false;
if (useSsl)
{
allowInvalidCertificate = GetYesNo("Allow invalid SSL certificate?");
}
bool useActiveFtp = GetYesNo("Use Active FTP?");
string path = null;
do
{
Console.Write("Enter the path: ");
path = Console.ReadLine();
} while (IsValidPath(path) == false);
ftpUrl.Path = path;
Console.Write("Enter the user name: ");
string userName = Console.ReadLine();
string password = GetPasswordFromUser();
Console.WriteLine();
Console.WriteLine();
List<string> directoryContents = null;
try
{
directoryContents = DisplayDirectoryContents(ftpUrl.ToString(), userName, password, useSsl, allowInvalidCertificate, useActiveFtp, false);
}
catch (WebException ex)
{
Console.WriteLine("The request failed with status {0}. {1}", ex.Status, ex.Message);
}
catch (Exception ex)
{
Console.Error.WriteLine(ex.ToString());
}
if (directoryContents != null && directoryContents.Count == 1)
{
bool saveFile = GetYesNo(string.Format("Download the file {0} from {1}? ", directoryContents[0], server));
if (saveFile)
{
string savePath = null;
do
{
Console.Write("Enter a local path to save the file: ");
savePath = Console.ReadLine();
} while (!IsValidPath(savePath));
try
{
DownloadFileFromServer(ftpUrl.ToString(), userName, password, useSsl, allowInvalidCertificate, useActiveFtp, savePath);
}
catch (WebException ex)
{
Console.WriteLine("The request failed with status {0}. {1}", ex.Status, ex.Message);
}
catch (Exception ex)
{
Console.Error.WriteLine(ex.ToString());
}
}
}
}
private static bool GetYesNo(string message)
{
Console.Write("{0} (Y/N) ", message);
string input = null;
do
{
input = new string(Console.ReadKey(true).KeyChar, 1);
} while (!input.Equals("Y", StringComparison.CurrentCultureIgnoreCase) && !input.Equals("N", StringComparison.CurrentCultureIgnoreCase));
Console.WriteLine(input);
return input.Equals("Y", StringComparison.CurrentCultureIgnoreCase);
}
private static bool IsValidPath(string path)
{
bool validPath = false;
validPath = path != null && path.IndexOfAny(Path.GetInvalidPathChars()) < 0;
if (validPath == false)
{
Console.WriteLine("You must enter a valid path.");
}
return validPath;
}
private static bool IsServerValid(string server)
{
bool serverValid = false;
if (!string.IsNullOrEmpty(server))
{
try
{
IPAddress[] addresses = Dns.GetHostAddresses(server);
serverValid = (addresses != null && addresses.Length > 0);
}
catch (SocketException ex)
{
Console.WriteLine(ex.Message);
}
}
else
{
Console.WriteLine("You must provide a valid host name or IP address.");
}
return serverValid;
}
private static string GetPasswordFromUser()
{
Console.Write("Enter the password: ");
StringBuilder password = new StringBuilder();
char readChar = '\x00';
while (readChar != '\r')
{
readChar = Console.ReadKey(true).KeyChar;
if (readChar == '\b')
{
if (password.Length > 0)
{
password.Length--;
Console.Write("\b \b");
}
}
else if (readChar != '\r')
{
Console.Write('*');
password.Append(readChar);
}
}
return password.ToString();
}
public static bool ServicePointManager_ServerCertificateValidationCallback(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
bool allowCertificate = true;
if (sslPolicyErrors != SslPolicyErrors.None)
{
Console.WriteLine("Accepting the certificate with errors:");
if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateNameMismatch) == SslPolicyErrors.RemoteCertificateNameMismatch)
{
Console.WriteLine("\tThe certificate subject {0} does not match.", certificate.Subject);
}
if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateChainErrors) == SslPolicyErrors.RemoteCertificateChainErrors)
{
Console.WriteLine("\tThe certificate chain has the following errors:");
foreach (X509ChainStatus chainStatus in chain.ChainStatus)
{
Console.WriteLine("\t\t{0}", chainStatus.StatusInformation);
if (chainStatus.Status == X509ChainStatusFlags.Revoked)
{
allowCertificate = false;
}
}
}
if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateNotAvailable) == SslPolicyErrors.RemoteCertificateNotAvailable)
{
Console.WriteLine("No certificate available.");
allowCertificate = false;
}
Console.WriteLine();
}
return allowCertificate;
}
private static FtpWebRequest CreateFtpWebRequest(string ftpUrl, string userName, string password, bool useSsl, bool allowInvalidCertificate, bool useActiveFtp)
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpUrl);
request.Credentials = new NetworkCredential(userName, password);
if (useSsl)
{
request.EnableSsl = true;
if (allowInvalidCertificate)
{
ServicePointManager.ServerCertificateValidationCallback = ServicePointManager_ServerCertificateValidationCallback;
}
else
{
ServicePointManager.ServerCertificateValidationCallback = null;
}
}
request.UsePassive = !useActiveFtp;
return request;
}
private static List<string> DisplayDirectoryContents(string ftpUrl, string userName, string password, bool useSsl, bool allowInvalidCertificate, bool useActiveFtp, bool detailed)
{
List<string> directoryContents = new List<string>();
FtpWebRequest request = CreateFtpWebRequest(ftpUrl, userName, password, useSsl, allowInvalidCertificate, useActiveFtp);
if (detailed)
{
request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
}
else
{
request.Method = WebRequestMethods.Ftp.ListDirectory;
}
Stopwatch stopwatch = new Stopwatch();
long bytesReceived = 0;
stopwatch.Start();
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
{
Console.WriteLine(response.BannerMessage);
Console.WriteLine(response.WelcomeMessage);
Console.WriteLine(response.StatusDescription);
using (Stream responseStream = response.GetResponseStream())
using (StreamReader responseStreamReader = new StreamReader(responseStream))
{
while (!responseStreamReader.EndOfStream)
{
string directoryEntry = responseStreamReader.ReadLine();
Console.WriteLine(directoryEntry);
directoryContents.Add(directoryEntry);
}
}
Console.WriteLine(response.ExitMessage);
}
stopwatch.Stop();
Console.WriteLine();
Console.WriteLine("{0} bytes received in {1} seconds.", bytesReceived, stopwatch.ElapsedMilliseconds / 1000.0);
return directoryContents;
}
private static List<string> ListDirectoryContents(string ftpUrl, string userName, string password, bool useSsl, bool allowInvalidCertificate, bool useActiveFtp, bool detailed)
{
List<string> directoryContents = new List<string>();
FtpWebRequest request = CreateFtpWebRequest(ftpUrl, userName, password, useSsl, allowInvalidCertificate, useActiveFtp);
if (detailed)
{
request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
}
else
{
request.Method = WebRequestMethods.Ftp.ListDirectory;
}
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
using (StreamReader responseStreamReader = new StreamReader(responseStream))
{
while (!responseStreamReader.EndOfStream)
{
string directoryEntry = responseStreamReader.ReadLine();
directoryContents.Add(directoryEntry);
}
}
}
return directoryContents;
}
private static void DownloadFileFromServer(string ftpUrl, string userName, string password, bool useSsl, bool allowInvalidCertificate, bool useActiveFtp, string savePath)
{
FtpWebRequest request = CreateFtpWebRequest(ftpUrl, userName, password, useSsl, allowInvalidCertificate, useActiveFtp);
request.Method = WebRequestMethods.Ftp.DownloadFile;
Stopwatch stopwatch = new Stopwatch();
long bytesReceived = 0;
stopwatch.Start();
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
{
Console.WriteLine(response.BannerMessage);
Console.WriteLine(response.WelcomeMessage);
Console.WriteLine(response.StatusDescription);
using (Stream responseStream = response.GetResponseStream())
using (FileStream saveFileStream = File.OpenWrite(savePath))
{
// Note that this method call requires .NET 4.0 or higher. If using an earlier version it will need to be replaced.
responseStream.CopyTo(saveFileStream);
}
bytesReceived = response.ContentLength;
Console.WriteLine(response.ExitMessage);
}
stopwatch.Stop();
Console.WriteLine();
Console.WriteLine("{0} bytes received in {1} seconds.", bytesReceived, stopwatch.ElapsedMilliseconds / 1000.0);
}
private static void UploadFileToServer(string ftpUrl, string userName, string password, bool useSsl, bool allowInvalidCertificate, bool useActiveFtp, string filePath)
{
FtpWebRequest request = CreateFtpWebRequest(ftpUrl, userName, password, useSsl, allowInvalidCertificate, useActiveFtp);
request.Method = WebRequestMethods.Ftp.UploadFile;
Stopwatch stopwatch = new Stopwatch();
long bytesReceived = 0;
stopwatch.Start();
long bytesSent = 0;
using (Stream requestStream = request.GetRequestStream())
using (FileStream uploadFileStream = File.OpenRead(filePath))
{
// Note that this method call requires .NET 4.0 or higher. If using an earlier version it will need to be replaced.
uploadFileStream.CopyTo(requestStream);
bytesSent = uploadFileStream.Position;
}
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
{
Console.WriteLine(response.BannerMessage);
Console.WriteLine(response.WelcomeMessage);
Console.WriteLine(response.StatusDescription);
bytesReceived = response.ContentLength;
Console.WriteLine(response.ExitMessage);
}
stopwatch.Stop();
Console.WriteLine();
Console.WriteLine("{0} bytes sent in {1} seconds.", bytesSent, stopwatch.ElapsedMilliseconds / 1000.0);
}
}
}
You can also get detailed tracing for debugging purposes by using the following config file with the sample application:
<?xml version="1.0"?>
<configuration>
<system.diagnostics>
<sources>
<source name="System.Net">
<listeners>
<add name="TraceFile"/>
</listeners>
</source>
<source name="System.Net.Sockets" maxdatasize="1024">
<listeners>
<add name="TraceFile"/>
</listeners>
</source>
</sources>
<sharedListeners>
<add name="TraceFile" type="System.Diagnostics.TextWriterTraceListener" initializeData="System.Net.trace.log" traceOutputOptions="DateTime"/>
</sharedListeners>
<switches>
<add name="System.Net" value="Verbose"/>
<!--<add name="System.Net.Sockets" value="Verbose"/>-->
</switches>
<trace autoflush="true" />
</system.diagnostics>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
</startup>
</configuration>
I use this library to download and upload files over sftp. Should be samples of how to use the library if you download the source. http://sshnet.codeplex.com

Resources