Monday, October 19, 2009

FTP oprations in C#, GET and PUT oprations, Checking FTP Directory Listing




using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.IO;

///
/// Summary description for FTP
///
namespace Tools
{
    public class FTP
    {
        public FTP()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        public static void downloadFiles(List<String> files, String targetFolder, string FTPAddress,string username, string password)
        {
            foreach (string fileToDownload in files)
            {
                downloadFile(FTPAddress, fileToDownload, targetFolder, username, password);
            }
        }
        public static void downloadFile(string FTPAddress, string filename,String targetFolder, string username, string password)
        {
            byte[] downloadedData = new byte[0];

            try
            {
               
                //Create FTP request
                //Note: format is ftp://server.com/file.ext
                FtpWebRequest request = FtpWebRequest.Create(FTPAddress + "/" + filename) as FtpWebRequest;

                //Get the file size first (for progress bar)
                request.Method = WebRequestMethods.Ftp.GetFileSize;
                request.Credentials = new NetworkCredential(username, password);
                request.UsePassive = true;
                request.UseBinary = true;
                request.KeepAlive = true; //don't close the connection

                int dataLength = (int)request.GetResponse().ContentLength;

                //Now get the actual data
                request = FtpWebRequest.Create(FTPAddress + "/" + filename) as FtpWebRequest;
                request.Method = WebRequestMethods.Ftp.DownloadFile;
                request.Credentials = new NetworkCredential(username, password);
                request.UsePassive = true;
                request.UseBinary = true;
                request.KeepAlive = false; //close the connection when done

                //Streams
                FtpWebResponse response = request.GetResponse() as FtpWebResponse;
                Stream reader = response.GetResponseStream();

                //Download to memory
                //Note: adjust the streams here to download directly to the hard drive
                MemoryStream memStream = new MemoryStream();
                byte[] buffer = new byte[1024]; //downloads in chuncks

                while (true)
                {
                   

                    //Try to read the data
                    int bytesRead = reader.Read(buffer, 0, buffer.Length);

                    if (bytesRead == 0)
                    {
                        break;
                    }
                    else
                    {
                        //Write the downloaded data
                        memStream.Write(buffer, 0, bytesRead);
                                              
                    }
                }

                //Convert the downloaded stream to a byte array
                downloadedData = memStream.ToArray();
               
                // Save File to Disk
                FileStream newFile = new FileStream(targetFolder + "\\" + filename, FileMode.Create);
                newFile.Write(downloadedData, 0, downloadedData.Length);
                newFile.Close();
               
                //Clean up
                reader.Close();
                memStream.Close();
                response.Close();

                //MessageBox.Show("Downloaded Successfully");
            }
            catch (Exception)
            {
                //MessageBox.Show("There was an error connecting to the FTP Server.");
            }

            //txtData.Text = downloadedData.Length.ToString();
            //this.Text = "Download Data through FTP";

            //username = string.Empty;
            //password = string.Empty;
        }

        public static List<String> getFileList(string FTPAddress, string username, string password)
        {
            List<string> files = new List<string>();

            try
            {

                //Create FTP request
                FtpWebRequest request = FtpWebRequest.Create(FTPAddress) as FtpWebRequest;


                request.Method = WebRequestMethods.Ftp.ListDirectory;
                request.Credentials = new NetworkCredential(username, password);
                request.UsePassive = true;
                request.UseBinary = true;
                request.KeepAlive = false;



                FtpWebResponse response = request.GetResponse() as FtpWebResponse;
                Stream responseStream = response.GetResponseStream();
                StreamReader reader = new StreamReader(responseStream);

                while (!reader.EndOfStream)
                {
                    //Application.DoEvents();
                    files.Add(reader.ReadLine());
                }

                //Clean-up
                reader.Close();
                responseStream.Close(); //redundant
                response.Close();
                return files;
            }
            catch (Exception)
            {
                //MessageBox.Show("There was an error connecting to the FTP Server");
                files.RemoveRange(0, files.Count - 1);
                return files;
            }
        }
        public static bool uploadFile(string FTPAddress, string filePath, string username, string password)
        {
            try
            {
                string finePathName = Path.GetFileName(filePath);
                //Create FTP request
                FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(FTPAddress + "/" + Path.GetFileName(filePath));

                request.Method = WebRequestMethods.Ftp.UploadFile;
                request.Credentials = new NetworkCredential(username, password);
                request.UsePassive = true;
                request.UseBinary = true;
                request.KeepAlive = false;

                //Load the file
                FileStream stream = File.OpenRead(filePath);
                byte[] buffer = new byte[stream.Length];

                stream.Read(buffer, 0, buffer.Length);
                stream.Close();

                //Upload file
                Stream reqStream = request.GetRequestStream();
                reqStream.Write(buffer, 0, buffer.Length);
                reqStream.Close();

                return true;
            }
            catch (Exception e)
            {
                return false;
            }
        }

    }
}



Sending Email using C# and Gmail with Attachments


//This is my new post for sending emails using C#.net and Gmail with Attachments
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net.Mail;
using System.Net;
using System.Configuration;
//using System.Web.Mail;
///
/// Summary description for Email
///
namespace Tools
{
    public class Email
    {
        public Email()
        {
            //
            // TODO: Add constructor logic here
            //
        }
        public static bool SendMail(string to, string subject, string message, string CSVAttachmentList)
        {
            try
            {
                string gMailAccount;
                string password;
                gMailAccount = ConfigurationManager.AppSettings.Get("emailUserName");
                password = ConfigurationManager.AppSettings.Get("emailPassword");
                NetworkCredential loginInfo = new NetworkCredential(gMailAccount, password);
                System.Net.Mail.MailMessage msg = new MailMessage();
                msg.From = new MailAddress(gMailAccount);
                msg.To.Add(new MailAddress(to));
                msg.Subject = subject;
                msg.Body = message;
                msg.IsBodyHtml = true;
                SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
                client.EnableSsl = true;
                client.UseDefaultCredentials = false;
                client.Credentials = loginInfo;
                string[] filesToAttch = CSVAttachmentList.Split(',');
                foreach (string fileName in filesToAttch)
                {
                    Attachment msgAttachment = new Attachment(fileName);
                    msg.Attachments.Add(msgAttachment);
                }
                client.Send(msg);
                return true;
            }
            catch (Exception e)
            {
                return false;
            }
        }
    }
}

Email sending using C# and Gmail




//Simple Email Sending function in C# using Gmail
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net.Mail;
using System.Net;
using System.Configuration;
///
/// Summary description for Email
///
namespace Tools
{
    public class Email
    {
        public Email()
        {
            //
            // TODO: Add constructor logic here
            //
        }
        public static bool SendMail(string to, string subject, string message)
        {
            try
            {
                string gMailAccount;
                string password;
                gMailAccount = ConfigurationManager.AppSettings.Get("emailUserName");
                password = ConfigurationManager.AppSettings.Get("emailPassword");
                NetworkCredential loginInfo = new NetworkCredential(gMailAccount, password);
                System.Net.Mail.MailMessage msg = new MailMessage();
                msg.From = new MailAddress(gMailAccount);
                msg.To.Add(new MailAddress(to));
                msg.Subject = subject;
                msg.Body = message;
                msg.IsBodyHtml = true;
                SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
                client.EnableSsl = true;
                client.UseDefaultCredentials = false;
                client.Credentials = loginInfo;
                //Attachment msgAttachment = new Attachment("g:\\test.doc");
                //msg.Attachments.Add(msgAttachment);
                client.Send(msg);
                return true;
            }
            catch (Exception e)
            {
                return false;
            }
        }
    }
}



Wednesday, October 14, 2009

Restore Cache Backup From Cache Terminal

It is quite easy to restore the cache classes backup using cache studio but some times we have a scenario where we have to restore the cache classes backup from the cache terminal. Usually we need this in Linux. We can achive this goal by using a simple command.

$system.OBJ.Load(”path to the xml File”,”ck”)
Just start cache terminal go to the specific namespace by typeing
zn “Namespace Name”
and then run the command
w $system.OBJ.Load(”path to the xml File”,”ck”)
and the xml file will be restored in the current namespace.

Cache installation steps on Red Hat Linux

Cache installation steps on Red Hat Linux

Download the cache setup files for your Linux version. and then Uzip the files.
Start the Terminal window in Linux.
Go to the cache setup foldcer. eg. cd /root/cache-2007/
Run ./cinstall command
The cache installation script will be start and ask you some question regarding installation .

1 ) It will display the Linux version which is supported with this version of cache and ask you to choose by asking “Is this the correct type of your system”. Select accordingly.

2 ) Next it will ask “Enter instance name”. Type the name of the instance for example cache07.

3 ) Then it will ask “Enter directory name for this installation ”. Type the path for your installation e.g /xyz/abc/.

4 ) If the directory you provide does not exist it will ask “Do you want to create it”. Type Yes.

5 ) Next it will ask u about the setup type “Standard or Custom”. Type 1 for standard.

6 ) Next it will ask u about Unicode support. Reply accordingly.

7 ) Then it will ask u about Security Settings. Select accordingly.

8 ) Then it will ask u about the Group which is allowed to start and stop the cache instance.

9 ) Then it will ask u about licence key. “Are u want to enter the licence Key”. Type yes if you want to provide a licence key.

10) It will then show u the provide option as installation summary and will ask u to proced. Type yes … and the installation will start.

11) After the installation if every thing goes fine it will show u the URL of System Management Portal.

12) Done

Followers

Search This Blog