Thứ Năm, 5 tháng 6, 2014

Converting between RTF and HTML

 Have you ever had the desire to convert some RTF text into HTML or take HTML and generate a RTF document? Probably not. But if you did, then you are in luck! I recently had the need to do this conversion and after some searching found out a way to do it by enhancing a sample distributed in the MSDN library
That sample has code which converts HTML to and from a XAML Flow Document. But this doesn’t make things easier until you realize that there is a way to convert RTF to XAML and XAML to RTF easily. The key is to use System.Windows.Controls.RichTextBox which can load RTF/XAML from a stream and save it as XAML/RTF.
RTF to XAML
C#
private static string ConvertRtfToXaml(string rtfText) 
{ 
    var richTextBox = new RichTextBox(); 
    if (string.IsNullOrEmpty(rtfText)) return ""; 
    var textRange = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd); 
    using (var rtfMemoryStream = new MemoryStream()) 
    { 
        using (var rtfStreamWriter = new StreamWriter(rtfMemoryStream)) 
        { 
            rtfStreamWriter.Write(rtfText); 
            rtfStreamWriter.Flush(); 
            rtfMemoryStream.Seek(0, SeekOrigin.Begin); 
            textRange.Load(rtfMemoryStream, DataFormats.Rtf); 
        } 
    } 
    using (var rtfMemoryStream = new MemoryStream()) 
    { 
        textRange = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd); 
        textRange.Save(rtfMemoryStream, DataFormats.Xaml); 
        rtfMemoryStream.Seek(0, SeekOrigin.Begin); 
        using (var rtfStreamReader = new StreamReader(rtfMemoryStream)) 
        { 
            return rtfStreamReader.ReadToEnd(); 
        } 
    } 
}
 
XAML to RTF
C#
private static string ConvertXamlToRtf(string xamlText) 
{ 
    var richTextBox = new RichTextBox(); 
    if (string.IsNullOrEmpty(xamlText)) return ""; 
    var textRange = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd); 
    using (var xamlMemoryStream = new MemoryStream()) 
    { 
        using (var xamlStreamWriter = new StreamWriter(xamlMemoryStream)) 
        { 
            xamlStreamWriter.Write(xamlText); 
            xamlStreamWriter.Flush(); 
            xamlMemoryStream.Seek(0, SeekOrigin.Begin); 
            textRange.Load(xamlMemoryStream, DataFormats.Xaml); 
        } 
    } 
    using (var rtfMemoryStream = new MemoryStream()) 
    { 
        textRange = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd); 
        textRange.Save(rtfMemoryStream, DataFormats.Rtf); 
        rtfMemoryStream.Seek(0, SeekOrigin.Begin); 
        using (var rtfStreamReader = new StreamReader(rtfMemoryStream)) 
        { 
            return rtfStreamReader.ReadToEnd(); 
        } 
    } 
}
 
 With this code we have all we need to convert RTF to HTML and HTML to RTF. I modified the MSDN library sample to add this RTF/XAML to XAML/RTF conversion and then I either run that XAML through HTML converter which results in the HTML text or I run the HTML through the XAML converter and generate XAML text. I added an interface for these conversion utilities and converted the sample into a library so that I would be able to use it from other projects. Here is the interface:
C#
public interface IMarkupConverter 
{ 
    string ConvertXamlToHtml(string xamlText); 
    string ConvertHtmlToXaml(string htmlText); 
    string ConvertRtfToHtml(string rtfText); 
    string ConvertHtmlToRtf(string htmlText); 
} 
 
public class MarkupConverter : IMarkupConverter 
{ 
    public string ConvertXamlToHtml(string xamlText) 
    { 
        return HtmlFromXamlConverter.ConvertXamlToHtml(xamlText, false); 
    } 
 
    public string ConvertHtmlToXaml(string htmlText) 
    { 
        return HtmlToXamlConverter.ConvertHtmlToXaml(htmlText, true); 
    } 
 
    public string ConvertRtfToHtml(string rtfText) 
    { 
        return RtfToHtmlConverter.ConvertRtfToHtml(rtfText); 
    } 
 
    public string ConvertHtmlToRtf(string htmlText) 
    { 
        return HtmlToRtfConverter.ConvertHtmlToRtf(htmlText); 
    } 
}
 
With this I am now able to convert from RTF to HTML and from HTML to RTF. However, there is one catch – the conversion uses the RichTextBox WPF control which requires a single threaded apartment (STA). Therefore in order to run your code that calls the ConvertRtfToHtml or ConvertHtmlToRtf functions, they must also be running in a STA. If you can’t have your program run in a STA (for example: when running an ASP .NET website) then you must create a new STA thread to run the conversion. Like this:
C#
MarkupConverter markupConverter = new MarkupConverter(); 
  
private string ConvertRtfToHtml(string rtfText) 
{ 
   var thread = new Thread(ConvertRtfInSTAThread); 
   var threadData = new ConvertRtfThreadData { RtfText = rtfText }; 
   thread.SetApartmentState(ApartmentState.STA); 
   thread.Start(threadData); 
   thread.Join(); 
   return threadData.HtmlText; 
} 
  
private void ConvertRtfInSTAThread(object rtf) 
{ 
   var threadData = rtf as ConvertRtfThreadData; 
   threadData.HtmlText = markupConverter.ConvertRtfToHtml(threadData.RtfText); 
} 
  
  
private class ConvertRtfThreadData 
{ 
   public string RtfText { getset; } 
   public string HtmlText { getset; } 
}
 
 That is all there is too it! Hopefully, this will come in handy for anyone needing to perform this conversion.
LinkSoure: http://adf.ly/pK35v
Create by Matthew Manela !

Thứ Tư, 4 tháng 6, 2014

File Upload, Download, Delete from FTP Server Using C#

File Upload, Download, Delete from FTP Server Using C#

Some time we need to download, upload file from FTP server. Here is some example to FTP operation.
For this we need to include one namespace and it is. using System.Net


File Download from FTP Server

public void DownloadFile(string HostURL, string UserName, string Password, string SourceDirectory, string FileName, string LocalDirectory)
        {
            if (!File.Exists(LocalDirectory + FileName))
            {
                try
                {
                    FtpWebRequest requestFileDownload = (FtpWebRequest)WebRequest.Create(HostURL + "/" + SourceDirectory + "/" + FileName);
                    requestFileDownload.Credentials = new NetworkCredential(UserName, Password);
                    requestFileDownload.Method = WebRequestMethods.Ftp.DownloadFile;
                    FtpWebResponse responseFileDownload = (FtpWebResponse)requestFileDownload.GetResponse();
                    Stream responseStream = responseFileDownload.GetResponseStream();
                    FileStream writeStream = new FileStream(LocalDirectory + FileName, FileMode.Create);
                    int Length = 2048;
                    Byte[] buffer = new Byte[Length];
                    int bytesRead = responseStream.Read(buffer, 0, Length);
                    while (bytesRead > 0)
                    {
                        writeStream.Write(buffer, 0, bytesRead);
                        bytesRead = responseStream.Read(buffer, 0, Length);
                    }
                    responseStream.Close();
                    writeStream.Close();
                    requestFileDownload = null;
                    responseFileDownload = null;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }




Show File List in FTP Server
public List<string> ShowFileList(string HostURL, string UserName, string Password, string SourceDirectory)

        {

            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(HostURL + "/" + SourceDirectory);

            request.Credentials = new NetworkCredential(UserName, Password);

            request.Method = WebRequestMethods.Ftp.ListDirectory;
            StreamReader streamReader = new StreamReader(request.GetResponse().GetResponseStream());
            List<string> lines = new List<string>();
            string line;
            while ((line = streamReader.ReadLine()) != null)
            {
                lines.Add(line);
            }
            return lines;
        }




Delete form FTP Server
public void DeleteFile(string HostURL, string UserName, string Password, string SourceDirectory, string FileName)
        {

            FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create(HostURL + "/" + SourceDirectory + "/" + FileName);
            ftpRequest.Credentials = new NetworkCredential(UserName, Password);
            ftpRequest.Method = WebRequestMethods.Ftp.DeleteFile;
            FtpWebResponse responseFileDelete = (FtpWebResponse)ftpRequest.GetResponse();

        }



Move File from One Directory to Another in FTP Server

public void MoveFile(string HostURL, string UserName, string Password, string SourceDirectory, string DestinationDirectory, string FileName)
        {
            FtpWebRequest ftpRequest = null;
            FtpWebResponse ftpResponse = null;
            try
            {
                ftpRequest = (FtpWebRequest)WebRequest.Create(HostURL + "/" + SourceDirectory + "/" + FileName);
                ftpRequest.Credentials = new NetworkCredential(UserName, Password);
                ftpRequest.UseBinary = true;
                ftpRequest.UsePassive = true;
                ftpRequest.KeepAlive = true;
                ftpRequest.Method = WebRequestMethods.Ftp.Rename;
                ftpRequest.RenameTo = DestinationDirectory + "/" + FileName;

                if (CheckFileExistOrNot(HostURL, UserName, Password, SourceDirectory + "/" + DestinationDirectory, FileName) == false)
                ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();            
              

                ftpResponse.Close();
                ftpRequest = null;
            }
            catch (Exception ex)
            {
                throw ex;             

          
            }
        }


Check File Existence in FTP Server

public bool CheckFileExistOrNot(string HostURL, string UserName, string Password, string SourceDirectory, string FileName)
        {
            FtpWebRequest ftpRequest = null;
            FtpWebResponse ftpResponse = null;
            bool IsExists = true;

            try
            {
                ftpRequest = (FtpWebRequest)WebRequest.Create(HostURL + "/" + SourceDirectory + "/" + FileName);
                ftpRequest.Credentials = new NetworkCredential(UserName, Password);              
                ftpRequest.Method = WebRequestMethods.Ftp.GetFileSize;              
                ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
                ftpResponse.Close();
                ftpRequest = null;
            }
            catch (Exception ex)
            {
                IsExists = false;
            }
            return IsExists;
        }

Tạo Nhiều Profile Với FireFox


Tạo Nhiều Profile Với FireFox

Việc tạo profile cho Firefox sẽ làm tiện dụng hơn khi bạn phải làm nhiều công việc, ví dụ MMO (make money online), SEO,.. mỗi profile như là một trình duyệt Firefox riêng vậy.



Trước tiên ta cần có trình duyệt FireFox đã, bạn nào chưa có download bản mới nhất tại đây. Tiếp theo các bạn tiến hành cài đặt bình thường.


Bước 1: Sau khi cài đặt xong, các bạn nhấp phải chuột vào biểu tượng của FireFox ngoài màn hình Desktop và chọn Properties.

Trong tab Shortcut, tại khung Target bạn nhập thêm vào cáckí tự " -p" (gồm: khoảng trắng, dấu gạch ngang, chữ p viết thường).


Target        "C:\Program Files\Mozilla Firefox\firefox.exe"

  =>sau khi thêm  -p vào :  

Target        "C:\Program Files\Mozilla Firefox\firefox.exe" -p

Điền xong bạn nhấn nút OK.


step 1

Bước 2:

- Tìm đến biểu tượng My Computer trên Desktop, bạn nhấp chuột phải và chọn Properties:

+ Chọn tab Advanced rồi click chọn Environment Variables

+ Dưới khung Systern variables chọn New

  Một cửa sổ nhỏ hiện ra và bạn điền như sau :


Name : MOZ_NO_REMOTE
Value : 1
vào advanced


Bước 3:
- Bật Firefox, cửa sổ chọn profile để sử dụng. Tại đây bạn có thể tạo mới, sửa tên, xóa một profile. Lưu ý là nếu đã xóa thì rất khó khôi phục được bạn nhé.



chose 1


Như vậy là đã hoàn thành rồi, các bạn sẽ thấy thực sự tiện lợi đấy. Nếu có thắc mắc gì hãy comment bạn nhé.

Sao lưu một Profile: một profile bạn tạo ra được lưu trong đường dẫn (với win xp/Vista) C:\Documents and Settings\[User Name]\Applications\Data\Mozilla\Firefox\Profiles\ với User Name là tên người dùng của máy tính. Bạn cần copy thư mục chứa profile đó, khi nào cần khôi phục thì paste vào đúng chỗ đó là được.
Có một cách khác là:

1. vào Start >Run> "C:\Program Files\Mozilla Firefox\firefox.exe" -profilemanager  > Enter

Image 

2. Khi hộp thọai Profile Manager xuất hiện, bạn nhấp vào nút Create Profile…. > cung cấp tên của Profile cần tạo (mình lấy ví dụ là BiBo) > nhấp nút Finish
Image 
3. Bạn sẽ được đưa về hộp thoại danh sách Profiles. Bạn chọn profile
tên Default rồi nhấp nút Start FireFox để qui định profile này mở mặc
định. Sau đó đóng Firefox lại.
Image
4. Giờ thì tạo Shotcut để khởi động FireFox với thông tin của người dùng BiBo chứ không pải là Profile mặc định.
Trở về Desktop, nhấp chuột phải lên vùng trống màn hình, chọn New
>> Shortcut.
 Trong hộp thoại tạo Shortcut nhập đường dẫn là "C:\Program Files\Mozilla Firefox\firefox.exe" -P PROFILENAME  -no-remote với PROFILENAME  là tên Profile bạn vừa tạo. Như vậy đường dẫn sẽ là "C:\Program Files\Mozilla Firefox\firefox.exe" -P BiBo -no-remote Sau đó nhấp Next > OK
Image 
5. Nhấp kép chuột vào Shortcut này, bạn sẽ khởi động FireFox với một giao hiện và cấu hình hoàn toàn mới. Đó là FireFox của profile BiBo.
Image 
Nếu người dùng khác khởi động firefox bằng shorcut thông thường trên Menu Start sẽ dẫn đến một FireFox mặc định.