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

설명은 생략^^

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

       

 xps 파일을  png 파일로 변경하는 코드

        public int XpsToPng(string xps_file)
        {
            // Make sure this is an xps file.
            if (!xps_file.ToLower().EndsWith(".xps"))
                throw new ArgumentException(
                    "Method XpsToPng only works for .xps files.");

            // Get the file's name without the .xps on the end.
            string file_prefix =
                xps_file.Substring(0, xps_file.Length - 4);

            // Load the XPS document.
            XpsDocument xps_doc = new XpsDocument(xps_file, FileAccess.Read);

            // Get a fixed paginator for the document.
            IDocumentPaginatorSource page_source =  xps_doc.GetFixedDocumentSequence();
            DocumentPaginator paginator =  page_source.DocumentPaginator;

            // Process the document's pages.
            int num_pages = paginator.PageCount;
            for (int i = 0; i < num_pages; i++)
            {
                using (DocumentPage page = paginator.GetPage(i))
                {
                    // Render the page into the memory stream.
                    int width = (int)page.Size.Width;
                    int height = (int)page.Size.Height;
                    RenderTargetBitmap bitmap =
                        new RenderTargetBitmap(
                            width, height, 96, 96,
                            PixelFormats.Default);
                    bitmap.Render(page.Visual);

                    // Save the PNG file.
                    PngBitmapEncoder encoder = new PngBitmapEncoder();
                    encoder.Frames.Add(BitmapFrame.Create(bitmap));

                    using (MemoryStream stream = new MemoryStream())
                    {
                        encoder.Save(stream);

                        using (FileStream file = new FileStream(
                            file_prefix + (i + 1).ToString() + ".png",
                            FileMode.Create))
                        {
                            file.Write(stream.GetBuffer(), 0,
                                (int)stream.Length);
                            file.Close();
                        }
                    }
                }
            }
            return num_pages;
        }

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

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
ICollection 과 IEnumerable 또는 List <T> 의 차이 - 링크  (0) 2018.02.18
            System.Management.ManagementScope oMs = new System.Management.ManagementScope(@"\\" + host + @"\root\cimv2");
            oMs.Connect();
            manEWatch = new ManagementEventWatcher(oMs, new EventQuery("SELECT * FROM    __InstanceCreationEvent WITHIN 0.1 WHERE TargetInstance ISA 'Win32_PrintJob'"));

            manEWatch.EventArrived += new EventArrivedEventHandler(mewPrintJobs_EventArrived);
            manEWatch.Start();

프린터에서 인쇄 이벤트가 발생될 경우 이벤트를 받아서 처리하는 코드..

 

        static void mewPrintJobs_EventArrived(object sender, EventArrivedEventArgs e)
        {
            foreach (PropertyData prop in e.NewEvent.Properties)
            {
                string val = prop.Value == null ? "null" : prop.Value.ToString();

            }

            ManagementBaseObject printJob = (ManagementBaseObject)e.NewEvent.Properties["TargetInstance"].Value;
            string v = "";
            foreach (PropertyData propp in printJob.Properties)
            {
                string name = propp.Name;
                string val = propp.Value == null ? "null" : propp.Value.ToString();
                val += "\n";
                v += name + ":" + val;

            }
            System.Windows.Forms.MessageBox.Show(v);
        }

 

이벤트에서 ManagementBaseObject 값을 출력해 보면 아래와 같다.

 

 

 

List<string> printerList = new PrintServer().GetPrintQueues().Select(c => c.Name).ToList();

컴퓨터에 설치된 프린터 목록의 이름만 가져오는 코드입니다.

foreach (PrintQueue pq in ps.GetPrintQueues())

foreach 를 이용하여 PrintQueue 의 항목에서 설치된 프린터 정보들을 가져올 수 있습니다.

https://stackoverflow.com/questions/10113244/why-use-icollection-and-not-ienumerable-or-listt-on-many-many-one-many-relatio

Json 문자열을 Deserialize 하여 사용할때 Class 로 만들면 접근하기가 좋다

헌데 복잡한 문자열은 Class 화 하기가 머리아픈데 아래 사이트가면 간단하게 만들수 있다.

 

http://json2csharp.com/

 

변환하면 RootObject Class 가 가장 상위단의 Class 이며 RootObject 로 DeserializeObject 하면 된다.

RootObject data= JsonConvert.DeserializeObject<RootObject>(jsonString);

 

예시 (카카오 쳇봇 중)

{
  "message": {
    "text": "귀하의 차량이 성공적으로 등록되었습니다. 축하합니다!",
    "photo": {
      "url": "https://photo.src",
      "width": 640,
      "height": 480
    },
    "message_button": {
      "label": "주유 쿠폰받기",
      "url": "https://coupon/url"
    }
  },
  "keyboard": {
    "type": "buttons",
    "buttons": [
      "처음으로",
      "다시 등록하기",
      "취소하기"
    ]
  }
}

변환

public class Photo
{
    public string url { get; set; }
    public int width { get; set; }
    public int height { get; set; }
}

public class MessageButton
{
    public string label { get; set; }
    public string url { get; set; }
}

public class Message
{
    public string text { get; set; }
    public Photo photo { get; set; }
    public MessageButton message_button { get; set; }
}

public class Keyboard
{
    public string type { get; set; }
    public List<string> buttons { get; set; }
}

public class RootObject
{
    public Message message { get; set; }
    public Keyboard keyboard { get; set; }
}

1) ‘시작|실행’ 을 선택하여 cmd 를 입력하여 Command 입력 윈도우를 연다.

2) .NET Framework 가 설치된 디렉토리로 이동한다. ( 보통의 경우 : cd C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727 )

3) aspnet_regiis –i 를 실행한다.

4) 등록 메시지가 화면에 표시되면서 ASP.NET를 웹 사이트에 등록된다. ( <그림 1> 참조 )

5) 웹 사이트 등록정보 HTTP 헤더 탭에서 ASP.NET 등록을 확인한다.

 

 

펌 : http://www.autobase.biz/Korean/AutoBaseHelp/Help10/network/NetworkWebServerAspNetInstall.htm

+ Recent posts