https://www.codeproject.com/Articles/1087859/Web-crawling-with-Csharp-part-one

 

HTTPClientThread.zip

MVCSimpleServerApp.zip

 

            ProcessStartInfo startInfo = new ProcessStartInfo(filePath);
            startInfo.Verb = "edit";

            Process.Start(startInfo);

 

'C#.NET > C#' 카테고리의 다른 글

Visual Studio 2017 에서 코드상의 빈 줄 제거 하기  (0) 2018.04.24
Web crawling with C#  (0) 2018.04.17
(C#) 그림판 실행하기  (0) 2018.03.22
(C#) png 파일을 ico 파일로 만들기  (0) 2018.03.21
Win API  (0) 2018.03.18
FileSystemWatcher (폴더 모니터링 기능)  (3) 2018.03.15

png 파일을 ico 파일로 만들때가 많아졌다;

아래 코드를 이용해 윈폼프로그램 하나 만들어서 사용중..

Image image = Bitmap.FromFile(path);
String fileName = Path.ChangeExtension(path, "ico");
Stream IconStream = System.IO.File.OpenWrite(fileName);

Bitmap bitmap = new Bitmap(image);
bitmap.SetResolution(64, 64);
Icon icon = System.Drawing.Icon.FromHandle(bitmap.GetHicon());
icon.Save(IconStream);
IconStream.Close();

'C#.NET > C#' 카테고리의 다른 글

Web crawling with C#  (0) 2018.04.17
(C#) 그림판 실행하기  (0) 2018.03.22
(C#) png 파일을 ico 파일로 만들기  (0) 2018.03.21
Win API  (0) 2018.03.18
FileSystemWatcher (폴더 모니터링 기능)  (3) 2018.03.15
(C#) 나만의 커서(Cursor) 만들기  (0) 2018.03.06

Windows API 에 대한 내용이 있는 사이트

확장 툴로도 제공한다.

https://www.pinvoke.net/

'C#.NET > C#' 카테고리의 다른 글

(C#) 그림판 실행하기  (0) 2018.03.22
(C#) png 파일을 ico 파일로 만들기  (0) 2018.03.21
Win API  (0) 2018.03.18
FileSystemWatcher (폴더 모니터링 기능)  (3) 2018.03.15
(C#) 나만의 커서(Cursor) 만들기  (0) 2018.03.06
(C#) 방화벽 뚫기 코드  (0) 2018.03.03

FileSystemWatcher 로 지정된 폴더를 모니터링(감시) 할 수 있다.

로컬 및 네트워크 드라이브, 원격 파일까지 감시가 가능하다.

파일/폴더의 변경, 삭제, 수정 에 대해 감시가 가능하고

감시 대상(파일 폴더)에 대해 사이즈 변경, 이름 변경 등의 필터링이 가능하다

또한 특정 파일, 특정 확장자 기준으로 필터링 할수 있다.

 

(아래 예제는 간단하게 어느 특정 폴더에 파일이 추가된 경우 처리하는 코드입니다.)

        FileSystemWatcher fsw = new ileSystemWatcher();
        public FileSystemWatcherTestForm()
        {
            InitializeComponent();
        }

        private void directoryButton_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fd = new FolderBrowserDialog();
            if (fd.ShowDialog() == DialogResult.OK)
            {
                this.watchTextBox.Text = fd.SelectedPath;
            }
        }

        private void watchFolderButton_Click(object sender, EventArgs e)
        {
            fsw.Path = this.watchTextBox.Text;
            fsw.EnableRaisingEvents = true;
            fsw.Created += Fsw_Created;

            //fsw.NotifyFilter = System.IO.NotifyFilters.FileName | System.IO.NotifyFilters.DirectoryName | System.IO.NotifyFilters.Size;
            //fsw.Changed += fsw_Changed;
            //fsw.Deleted += fsw_Deleted;
            //fsw.Renamed += fsw_Renamed;
        }

        /// <summary>
        /// FileSystemWatcher 가 바라보는 폴더에 파일이 추가된 경우 발생되는 이벤트입니다.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Fsw_Created(object sender, FileSystemEventArgs e)
        {
            try
            {
                Invoke(new MethodInvoker(delegate ()
                {
                     this.copyListBox.Items.Add(e.Name);
                 }));
            }
            catch (Exception ex)
            {

            }
        }

 

FileSystemWatcherTest.zip

 

 

  1. Favicon of http://kjun.kr kjun.kr 2018.03.15 13:14 신고

    https://www.pinvoke.net/

  2. Favicon of http://kjun.kr kjun.kr 2018.03.15 13:24 신고

    http://csharphelper.com/blog/2017/12/use-debug-and-trace-listeners-in-c/

  3. Favicon of http://kjun.kr kjun.kr 2018.03.15 13:24 신고

    http://csharphelper.com/blog/2017/12/format-values-in-a-listbox-in-c/

커서 모양을 다른 걸로 변경하고 싶을때

.cur 파일을 만드는 방법이 있다.

하지만 번거롭다 그냥 이미지를 커서로 만드는 방법은 아래와 같다.

            Image image = Bitmap.FromFile("pen.png");
            Bitmap bitmap = new Bitmap(image);
            Graphics graphics = Graphics.FromImage(bitmap);
            IntPtr handle = bitmap.GetHicon();
            Cursor penCursor = new Cursor(handle);

 

'C#.NET > C#' 카테고리의 다른 글

Win API  (0) 2018.03.18
FileSystemWatcher (폴더 모니터링 기능)  (3) 2018.03.15
(C#) 나만의 커서(Cursor) 만들기  (0) 2018.03.06
(C#) 방화벽 뚫기 코드  (0) 2018.03.03
How to generate a PDF from HTML using wkhtmltopdf with C# in WinForms  (0) 2018.03.02
RabbitMQ - 링크  (0) 2018.02.28

파워 쉘 명령어를 이용해 방화벽을 뚫어주는 코드

설명은 생략^^

public class FireWallManager
{
    public static bool AllowThisProgram(string programName, string Protocol, string RemotePorts, string LocalPorts, string Direction)
    {
        string programFullName = AppDomain.CurrentDomain.BaseDirectory + AppDomain.CurrentDomain.FriendlyName;
        int End = programFullName.LastIndexOf("\\");
        if (programName.Length == 0) programName = programFullName.Substring(End + 1);
        return AllowProgram(programName, programFullName, Protocol, RemotePorts, LocalPorts, Direction);
    }

    public static bool AllowProgram(string programName, string ProgramFileName, string Protocol, string RemotePorts, string LocalPorts, string Direction)
    {
        //netsh advfirewall firewall delete rule name="NetBIOS TCP Port 139" protocol=TCP localport=139
        //netsh advfirewall firewall add rule name="NetBIOS TCP Port 139" dir=in action=allow protocol=TCP localport=139
        programName = "Allow " + programName + " " + Protocol.ToUpper() + " " + Direction.ToLower() + " " + LocalPorts + " " + RemotePorts;
        programName = programName.Replace("  ", " ").Trim();
        string CmdDelete = "netsh advfirewall firewall delete rule name='" + programName + "' protocol=" + Protocol.ToUpper() + " dir=" + Direction.ToLower();
        if (LocalPorts.Length > 0) CmdDelete += " localport=\"" + LocalPorts + "\"";
        if (RemotePorts.Length > 0) CmdDelete += " remoteport=\"" + RemotePorts + "\"";
        if (ProgramFileName.Length > 0) CmdDelete += " program=\"" + ProgramFileName + "\"";
        string Test = ExecuteCommandAsAdmin(CmdDelete);
        string CmdAdd = "netsh advfirewall firewall add rule name='" + programName + "' dir=" + Direction.ToLower() + " action=allow protocol=" + Protocol.ToUpper();
        if (LocalPorts.Length > 0) CmdAdd += " localport=\"" + LocalPorts + "\""; else LocalPorts = "Any";
        if (RemotePorts.Length > 0) CmdAdd += " remoteport=\"" + RemotePorts + "\""; else RemotePorts = "Any";
        if (ProgramFileName.Length > 0) CmdAdd += " program=\"" + ProgramFileName + "\""; else ProgramFileName = "Any";
        CmdAdd += " description='Allow " + ProgramFileName + " on " + Protocol + " using local-ports " + LocalPorts + " and remote-ports " + RemotePorts + "'";
        return ExecuteCommandAsAdmin(CmdAdd).ToUpper().StartsWith("OK");
    }

    public static string ExecuteCommandAsAdmin(string command)
    {
        ProcessStartInfo psinfo = new ProcessStartInfo();
        psinfo.FileName = "powershell.exe";
        psinfo.Arguments = command;
        psinfo.RedirectStandardError = true;
        psinfo.RedirectStandardOutput = true;
        psinfo.UseShellExecute = false;

        using (Process proc = new Process())
        {
            proc.StartInfo = psinfo;
            proc.Start();

            string output = proc.StandardOutput.ReadToEnd();

            if (string.IsNullOrEmpty(output))
                output = proc.StandardError.ReadToEnd();

            return output;
        }
    }
}

'C#.NET > C#' 카테고리의 다른 글

FileSystemWatcher (폴더 모니터링 기능)  (3) 2018.03.15
(C#) 나만의 커서(Cursor) 만들기  (0) 2018.03.06
(C#) 방화벽 뚫기 코드  (0) 2018.03.03
How to generate a PDF from HTML using wkhtmltopdf with C# in WinForms  (0) 2018.03.02
RabbitMQ - 링크  (0) 2018.02.28
(C#) ShuffleArray  (0) 2018.02.24

1. Install Pechkin

To generate a PDF from a HTML file with C# in Windows Forms, we are going to use Pechkin, the .NET Wrapper for wkhtmltopdf DLL, library that uses Webkit engine to convert HTML pages to PDF. Pechkin is available as a NuGet package, in most cases you should use SynchronizedPechkin as it protects multithreaded code from crashing the lib. But for simple usage from one thread, you can use SimplePechkin directly.

Note

Pechkin includes the latest version of wkhtmltox DLL in the project (and in NuGet package) along with its dependencies, and copied into build folder on project build. So there's no need to install any prerequisites before using the library on the computer.

Install the package with Visual Studio, by accessing the NuGET package manager. Do right click in your project in the Solution Explorer at the right top of Visual Studio and select Manage NuGet packages in the dropdown menu:

Solution explorer nuget packages

Now from the emergent window search for the Pechkin.Synchronized package, select it and install it in your project:

Pechkin.Synchronized NuGET package visual studio

Once the setup finishes, you will be able to use the wrapper in your project.

2. Generate a PDF

The Convert method converts a HTML string (or a configuration object) to PDF with the given settings and returns a byte arrays that store the binary data of the PDF.

Note

With all the examples, the pdfContent variable will generate only the content of the PDF and you won't see anything, therefore don't forget to write the created content into a file by following the step #3.

A. Generate simple PDF from a HTML string

You can create a PDF quickly with an empty global configuration object. Import the Pechkin type in your class:

using Pechkin;

And then create the content of the PDF with the following snippet:

byte[] pdfContent = new SimplePechkin(new GlobalConfig()).Convert("<html><body><h1>Hello world!</h1></body></html>");

B. Generate PDF from a Website

Instead of a plain HTML string, you can render a website through it's URL with the SetPageUri method in the configuration. Import the Pechkin.Synchronized type at the top of your class:

using Pechkin.Synchronized;

And then use the following code to create a PDF from a website:

// create global configuration object
GlobalConfig gc = new GlobalConfig();

// set it up using fluent notation
// Remember to import the following type:
//     using System.Drawing.Printing;
//
// a new instance of Margins with 1-inch margins.
gc.SetMargins(new Margins(100, 100, 100, 100))
    .SetDocumentTitle("Test document")
    .SetPaperSize(PaperKind.Letter)
    // Set to landscape
    //.SetPaperOrientation(true)
;

// Create converter
IPechkin pechkin = new SynchronizedPechkin(gc);

// Create document configuration object
ObjectConfig configuration = new ObjectConfig();

// and set it up using fluent notation too
configuration.SetCreateExternalLinks(false)
    .SetFallbackEncoding(Encoding.ASCII)
    .SetLoadImages(true)
    .SetPageUri("http://ourcodeworld.com");

// Generate the PDF with the given configuration
// The Convert method will return a Byte Array with the content of the PDF
// You will need to use another method to save the PDF (mentioned on step #3)
byte[] pdfContent = pechkin.Convert(configuration);

C. Generate PDF from a local HTML file

To create a PDF from a local HTML file, you can do it by providing the local filepath of the file with the SetPageUri method (in the same way that you do with a website) but at the same time, allow the usage of local resources with the SetAllowLocalContent method (note that you need to append as prefix file:/// to the html filepath). Import the Pechkin.Synchronized type at the top of your class:

using Pechkin.Synchronized;

And use the following code to create a PDF from a local HTML file:

// create global configuration object
GlobalConfig gc = new GlobalConfig();

// set it up using fluent notation
// Remember to import the following type:
//     using System.Drawing.Printing;
//
// a new instance of Margins with 1-inch margins.
gc.SetMargins(new Margins(100, 100, 100, 100))
    .SetDocumentTitle("Test document")
    .SetPaperSize(PaperKind.Letter);

// Create converter
IPechkin pechkin = new SynchronizedPechkin(gc);

// Create document configuration object
ObjectConfig configuration = new ObjectConfig();


string HTML_FILEPATH = "C:/Users/sdkca/Desktop/example.html";

// and set it up using fluent notation too
configuration
.SetAllowLocalContent(true)
.SetPageUri(@"file:///" + HTML_FILEPATH);

// Generate the PDF with the given configuration
// The Convert method will return a Byte Array with the content of the PDF
// You will need to use another method to save the PDF (mentioned on step #3)
byte[] pdfContent = pechkin.Convert(configuration);

Now that you know how to generate the content of a PDF, you only need to learn how to save it.

3. Save the PDF

As mentioned previously, Pechkin generates a PDF and return the data as a byte array, that means that you will need to write that data somehow by yourself. We will write the PDF into a file using the FileStream class included in the assembly System.IO. With FileStream you can read from, write to, open, and close files on a file system, as well as to manipulate other file related operating system handles including pipes, standard input, and standard output. Before using it, import the following type with the using directive in the top of your class:

using System.IO;

And then, use the class to create a file with the returned ByteArray as content. You can use the following method that expects as first parameter the absolute path of the file and as second parameter the data to write (pdf content):

/// <summary>
/// Writes a byte array (format returned by SimplePechkin) into a file
/// </summary>
/// <param name="_FileName"></param>
/// <param name="_ByteArray"></param>
/// <returns></returns>
public bool ByteArrayToFile(string _FileName, byte[] _ByteArray)
{
    try
    {
        // Open file for reading
        FileStream _FileStream = new FileStream(_FileName, FileMode.Create, FileAccess.Write);
        // Writes a block of bytes to this stream using data from  a byte array.
        _FileStream.Write(_ByteArray, 0, _ByteArray.Length);

        // Close file stream
        _FileStream.Close();

        return true;
    }
    catch (Exception _Exception)
    {
        Console.WriteLine("Exception caught in process while trying to save : {0}", _Exception.ToString());
    }
    
    return false;
}

Then it can be used as shown in the following example:

// Simple PDF from String
byte[] pdfBuffer = new SimplePechkin(new GlobalConfig()).Convert("<html><body><h1>Hello world!</h1></body></html>");

// Folder where the file will be created 
string directory = "C:\\Users\\sdkca\\Desktop\\";
// Name of the PDF
string filename = "hello_world.pdf";

if (ByteArrayToFile(directory + filename, pdfBuffer))
{
    Console.WriteLine("PDF Succesfully created");
}
else
{
    Console.WriteLine("Cannot create PDF");
}

Happy coding !

출처 : https://ourcodeworld.com/articles/read/366/how-to-generate-a-pdf-from-html-using-wkhtmltopdf-with-c-in-winforms

'C#.NET > C#' 카테고리의 다른 글

(C#) 나만의 커서(Cursor) 만들기  (0) 2018.03.06
(C#) 방화벽 뚫기 코드  (0) 2018.03.03
How to generate a PDF from HTML using wkhtmltopdf with C# in WinForms  (0) 2018.03.02
RabbitMQ - 링크  (0) 2018.02.28
(C#) ShuffleArray  (0) 2018.02.24
(C#) xps to png  (0) 2018.02.24

일단 링크만 모아놓고 나중에 봐야겠다. ㅜㅠ

 

설치 (윈도우)

http://icodebroker.tistory.com/4964

설치(Mac, Ubuntu)

http://blog.saltfactory.net/install-rabbitmq/

 

왜 써야하는가?

http://heowc.tistory.com/36?category=677973

 

메세지손실 최소화

https://m.blog.naver.com/PostView.nhn?blogId=tmondev&logNo=221051503100&proxyReferer=http%3A%2F%2Fwww.google.co.kr%2Furl%3Fsa%3Dt%26rct%3Dj%26q%3D%26esrc%3Ds%26source%3Dweb%26cd%3D10%26ved%3D0ahUKEwiR7fL6ssjZAhUFKJQKHcqrCewQFghjMAk%26url%3Dhttp%253A%252F%252Fm.blog.naver.com%252Ftmondev%252F221051503100%26usg%3DAOvVaw2CAnDXafK6JH2x8ydHwNOF

 

소스

https://github.com/hjb417/rabbitmq-wcf-transports (RabbitMQ transports for WCF)

 

다른것과 비교

https://atinjin.github.io/blog/rabbitmq/

http://heowc.tistory.com/35?category=677973

 

결론을 요약하면 (직접 좀 많이 구현을 해야 하지만...) ZeroMQ가 제일 성능이 좋지만 RabbitMQ도 괜찮다.

◦ZeroMQ broker outperforms all others. This means that unless you have a need for complex broker features, ZeroMQ is a perfect message dispatcher among processes.

◦Except for big messages, RabbitMQ seems to be the best bet as it outperforms others by a factor of 3.

'C#.NET > C#' 카테고리의 다른 글

(C#) 방화벽 뚫기 코드  (0) 2018.03.03
How to generate a PDF from HTML using wkhtmltopdf with C# in WinForms  (0) 2018.03.02
RabbitMQ - 링크  (0) 2018.02.28
(C#) ShuffleArray  (0) 2018.02.24
(C#) xps to png  (0) 2018.02.24
(C#) 프린터 출력시 이벤트 처리하기  (0) 2018.02.24
        /// <summary>
        /// Array 내용을 랜덤하게 뽑아오되 앞에서 뽑힌내용은 제외하고 뽑아올때 사용됩니다.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="array"></param>
        /// <param name="seed"></param>
        /// <returns></returns>
        public static T[] ShuffleArray<T>(T[] array, int seed)
        {
            System.Random r = new System.Random(seed);

            for (int i = 0; i < array.Length - 1; i++)
            {
                int randomIndex = r.Next(i, array.Length);
                T tempItem = array[randomIndex];
                array[randomIndex] = array[i];
                array[i] = tempItem;
            }
           
            return array;
        }

'C#.NET > C#' 카테고리의 다른 글

How to generate a PDF from HTML using wkhtmltopdf with C# in WinForms  (0) 2018.03.02
RabbitMQ - 링크  (0) 2018.02.28
(C#) ShuffleArray  (0) 2018.02.24
(C#) xps to png  (0) 2018.02.24
(C#) 프린터 출력시 이벤트 처리하기  (0) 2018.02.24
(C#)프린터 목록 가져오기  (0) 2018.02.24

+ Recent posts

티스토리 툴바