close

Trust Me!! Trust You!!


  • Blog
  • Local Log
  • Tag Cloud
  • Key Log
  • Guestbook
  • RSS Feed
  • Write a Post
  • Admin

혹시 블로그 스킨이 깨져 보이시나요? 최신버전의 Internet Explorer(Windows용), Opera, Firefox를 사용해보세요.

Batch Printing in C#

App 프로그래밍
2016/05/17 14:41
 
bool isPrinted = BatchPrint.PrintBinaryFile("file path", "Printer IP Address", "Queue Name", "User");
public class BatchPrint
{

    private const int cPort = 515;
    private const char cLineFeed = '\n';
    private const int cDefaultByteSize = 4;
    public static string ErrorMessage = string.Empty;
    private static string mHost;
    private static string mQueue;
    private static string mUser;
    private static readonly Queue mPrintQueue = new Queue();
    private static readonly Dictionary<string, int> mLastPrintId = new Dictionary<string, int>();

    public static bool PrintBinaryFile(string filePath, string printerName, string queueName, string userName)
    {
        try
        {
            mHost = printerName;
            mQueue = queueName;
            mUser = userName;
            BeginPrint(filePath);
        }
        catch (Exception ex)
        {
            ErrorMessage += ex.Message + cLineFeed + ex.StackTrace;
        }
        return ErrorMessage.Length <= 0;
    }

    private static void BeginPrint(string filePath)
    {      
        mPrintQueue.Enqueue(filePath);
        ThreadStart myThreadDelegate = SendFileToPrinter;
        var myThread = new Thread(myThreadDelegate);
        myThread.Start();
    }

    private static void SendFileToPrinter()
    {
        ErrorMessage = string.Empty;
        var fileFromQueue = (string)mPrintQueue.Dequeue();
        var tcpClient = new TcpClient();
        tcpClient.Connect(mHost, cPort);
        const char space = ' ';
        using (var networkStream = tcpClient.GetStream())
        {
            if (!networkStream.CanWrite)
            {
                ErrorMessage = "NetworkStream.CanWrite failed";
                networkStream.Close();
                tcpClient.Close();
                return;
            }
            var thisPc = Dns.GetHostName();
            var printId = GetPrintId();
            var dfA = string.Format("dfA{0}{1}", printId, thisPc);
            var cfA = string.Format("cfA{0}{1}", printId, thisPc);
            var controlFile = string.Format("H{0}\nP{1}\n{5}{2}\nU{3}\nN{4}\n", thisPc, mUser, dfA, dfA, Path.GetFileName(fileFromQueue), true);
            const int bufferSize = (cDefaultByteSize * 1024);
            var buffer = new byte[bufferSize];
            var acknowledgement = new byte[cDefaultByteSize];
            var position = 0;
            buffer[position++] = 2;
            ProcessBuffer(mQueue, ref buffer, ref position, (byte)cLineFeed);
            if (!IsAcknowledgementValid(buffer, position, acknowledgement, networkStream, tcpClient, "No response from printer"))
                return;               
            position = 0;
            buffer[position++] = 2;
            var cFileLength = controlFile.Length.ToString();
            ProcessBuffer(cFileLength, ref buffer, ref position, (byte)space);
            ProcessBuffer(cfA, ref buffer, ref position, (byte)cLineFeed);
            if (!IsAcknowledgementValid(buffer, position, acknowledgement, networkStream, tcpClient, "Error on control file len"))
                return;
            position = 0;
            ProcessBuffer(controlFile, ref buffer, ref position, 0); 
            if (!IsAcknowledgementValid(buffer, position, acknowledgement, networkStream, tcpClient, "Error on control file"))
                return;
            position = 0;
            buffer[position++] = 3;
            var dataFileInfo = new FileInfo(fileFromQueue);
            cFileLength = dataFileInfo.Length.ToString();
            ProcessBuffer(cFileLength, ref buffer, ref position, (byte)space);
            ProcessBuffer(dfA, ref buffer, ref position, (byte)cLineFeed);
            if (!IsAcknowledgementValid(buffer, position, acknowledgement, networkStream, tcpClient, "Error on dfA"))
                return;              
            long totalbytes = 0;
            using (var fileStream = new FileStream(fileFromQueue, FileMode.Open))
            {
                int bytesRead;
                while ((bytesRead = fileStream.Read(buffer, 0, bufferSize)) > 0)
                {
                    totalbytes += bytesRead;
                    networkStream.Write(buffer, 0, bytesRead);
                    networkStream.Flush();
                }
                fileStream.Close();
            }
            if (dataFileInfo.Length != totalbytes)
                ErrorMessage = fileFromQueue + "File length error";
            position = 0;
            buffer[position++] = 0;
            if (!IsAcknowledgementValid(buffer, position, acknowledgement, networkStream, tcpClient, "Error on file"))
                return;
            networkStream.Close();
            tcpClient.Close();
        }
    }

    private static int GetPrintId()
    {
        var count = 0;
        lock (mLastPrintId)
        {
            if (mLastPrintId.ContainsKey(mUser))
                count = mLastPrintId[mUser];
            count++;          
            count %= 1000; 
            if (mLastPrintId.ContainsKey(mUser))
                mLastPrintId[mUser] = count;
            else
                mLastPrintId.Add(mUser, count);
        }
        return count;
    }

    private static void ProcessBuffer(string item, ref byte[] buffer, ref int position, byte nextPosition)
    {
        foreach (var t in item)
        {
            buffer[position++] = (byte)t;
        }
        buffer[position++] = nextPosition;
    }

    private static bool IsAcknowledgementValid(byte[] buffer, int position, byte[] acknowledgement, NetworkStream networkStream, TcpClient tcpClient, string errorMsg)
    {
        networkStream.Write(buffer, 0, position);
        networkStream.Flush();
        networkStream.Read(acknowledgement, 0, cDefaultByteSize);
        if (acknowledgement[0] == 0) 
            return true;
        ErrorMessage = errorMsg;
        networkStream.Close();
        tcpClient.Close();
        return false;
    }

}
이올린에 북마크하기
No received trackback. / Comment 4

Trackback Address :: http://viper150.cafe24.com/trackback/279

You can also say.

Prev 1 ... 21 22 23 24 25 26 27 28 29 ... 298 Next
블로그 이미지
이것저것 불펌금지도 퍼다가 담습니다. 외부에 비공개된 페이지 입니다. By. 어른왕자

카테고리

  • 전체 (298)
    • 사는 이야기 (115)
    • 웹 프로그래밍 (102)
    • App 프로그래밍 (22)
    • IT 뉴스&기타 (22)
    • 박한별 (4)
    • 역사&기타지식 (9)

태그목록

  • 집안일
  • 피로
  • 몰래카메라
  • 시력검사
  • 달걀찜
  • tomcat
  • 욕심
  • 남여관계
  • 만화
  • 몰카
  • List
  • Calendar
  • 초경합금
  • 이미지버튼
  • 우리
  • Button
  • jQuery plugin
  • uTorrent
  • 미국의료
  • 부부관계
  • Ultra
  • mysql
  • 조선500년
  • 파락호
  • Windows 7
  • 최적화
  • 육이오
  • api
  • 실시간tv
  • 락산

최근에 올라온 글

  • 보험사의 조정신청 대응방법.
  • 어느 천재의 앞선 시선.
  • [병맛더빙] 누구게..... (1)
  • 韓경제 `회색 코뿔소` 상황...
  • SVN Connector 설치 URL.
  • 군대를 가지 않는 서울대생.
  • “운은 하늘의 귀여움 받는...
  • 목장에서 알바하다가 캐스...
  • [펌]믿고 거르는 관상.
  • 하루에 1세트씩 하면 좋다...

최근에 달린 댓글

  • <p><img src="https://i.imgur... 브레드 01/22
  • <p><img src="https://i.imgur... 브레드 01/22
  • <p><img src="https://i.imgur... 브레드 01/22
  • <p><img src="https://i.imgur... 브레드 01/22
  • <p><img src="https://i.imgur... 브레드 01/22

최근에 받은 트랙백

  • công ty may đồng phục. công ty may đồng phục 01/08
  • Israelnightclub`s recent blo... Israelnightclub`s recent blo.. 01/06
  • Suggested Browsing. Suggested Browsing 01/06
  • similar site. similar site 01/06
  • לאתר הבית שלנו. לאתר הבית שלנו 01/06

글 보관함

  • 2019/03 (1)
  • 2018/12 (1)
  • 2018/09 (1)
  • 2018/08 (1)
  • 2018/02 (1)

달력

«   2021/01   »
일 월 화 수 목 금 토
          1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31            

링크

  • Total : 262062
  • Today : 49
  • Yesterday : 46
Tattertools
Eolin
rss

어른왕자's blog is powered byTattertools1.1.2.2 : Animato