프로젝트

일반

사용자정보

통계
| 브랜치(Branch): | 개정판:

markus / ConvertService / ConverterService / ConverterStation / Remoting / ConverterService.cs @ 7ca218b3

이력 | 보기 | 이력해설 | 다운로드 (34.6 KB)

1
using System;
2
using System.ComponentModel;
3
using System.Runtime.Remoting;
4
using System.Runtime.Remoting.Channels;
5
using System.Runtime.Remoting.Channels.Tcp;
6
using System.Threading;
7
using System.Data.SqlClient;
8
using System.Linq;
9
using System.Collections.Generic;
10
using System.Diagnostics;
11
using System.Threading.Tasks;
12
using System.Collections;
13
using DeepViewDataModel.DataModel;
14
using DeepViewDataModel.Common;
15
using System.IO;
16
using System.Net;
17
using IConverterPDF;
18
using DZConverterLib;
19
using System.Text;
20
using ConverterStation.Remoting;
21
using System.Diagnostics.CodeAnalysis;
22
using System.Runtime.InteropServices;
23
using System.Security;
24
using PropertiesType;
25
using DeepView.Toolkit.GuidGenerator;
26
using DZConverterLib.Event;
27

    
28
namespace ConverterStation.Service
29
{
30
    public class ConverterService : InterfaceConverterPDF, IDisposable
31
    {
32
        #region Properties
33
        public TcpChannel channel { get; set; }
34
        public ServiceEventLog _log { get; set; }
35
        private ConverterServiceType SeriviceType { get; set; }
36
        private Guid ServiceID { get; set; }
37
        private string _serviceID { get; set; }
38
        private Guid _ServiceID { get; set; }
39
        private Thread _ConverterPdfThread { get; set; }
40
        private Queue<CONVERTER_DOC> _WorkItems { get; set; }
41
        private List<CONVERTER_DOC> _thread { get; set; }
42
        private List<ServiceItem> LstService { get; set; }
43
        public int remotingPort { get; set; }
44
        public string hostName { get; set; }
45
        #endregion
46

    
47
        #region inheritance property
48
        private int _MultiProcessCount;
49

    
50
        public int MultiProcessCount
51
        {
52
            get
53
            {
54
                if (_MultiProcessCount == 0)
55
                    return 1;
56
                else
57
                    return _MultiProcessCount;
58
            }
59

    
60
            set
61
            {
62
                using (DeepView_Entity _deepview = new DeepView_Entity(ConnectStringBuilder.DeepViewConnectionString().ToString()))
63
                {
64
                    _serviceID = ServiceID.ToString();
65
                    var _service = _deepview.SERVICE_PROPERTIES.Where(s => s.ID == _serviceID);
66

    
67
                    if (_service.Count() > 0)
68
                    {
69
                        _service.First().PROCESS_COUNT = value;
70
                        _deepview.SaveChanges();
71
                        _MultiProcessCount = value;
72
                    }
73
                }
74
            }
75
        }
76

    
77
        #endregion
78

    
79
        #region inheritance Method
80
        public void Dispose()
81
        {
82
            if (channel != null)
83
            {
84
                ChannelServices.UnregisterChannel(channel);
85
            }
86
        }
87

    
88
        public ConverterPDFResult Notify(string ProjectNo, Guid ConverterID)
89
        {
90
            try
91
            {
92
                using (DeepView_Entity _Entity = new DeepView_Entity(ConnectStringBuilder.DeepViewConnectionString().ToString()))
93
                {
94
                    _serviceID = ConverterID.ToString();
95
                    var _result = from Converter in _Entity.CONVERTER_DOC
96
                                  where Converter.ID == _serviceID
97
                                  select Converter;
98

    
99
                    StartConverterPDFProcess(_result.ToList());
100
                }
101
            }
102
            catch (Exception ex)
103
            {
104
                SetError(ConverterID, "Notify error 서비스를 시작할 수 없습니다.", ex.ToString(), 0);
105
                return new ConverterPDFResult { ConverterID = ConverterID, ProjectNo = ProjectNo, Exception = ex.ToString() };
106
            }
107

    
108
            return new ConverterPDFResult { ConverterID = ConverterID, ProjectNo = ProjectNo };
109
        }
110

    
111
        public Guid[] RunningProcessID()
112
        {
113
            string[] _temp = _thread.Select(t => t.ID).ToArray();
114
            Guid[] _return = new Guid[_temp.Length];
115

    
116
            for (int i = 0; i < _temp.Length; i++ )
117
            {
118
                _return[i] = Guid.Parse(_temp[i]);
119
            }
120

    
121
            return _return;
122
            //return _thread.Select(t => Guid.Parse(t.ID)).ToArray();
123
        }
124

    
125
        public ServiceInfo ServiceInfomation()
126
        {
127
            ServiceInfo _info = new ServiceInfo();
128
            StringBuilder bl = new StringBuilder();
129
            try
130
            {
131
                _info.ServiceUri = ServiceUri();
132
            }
133
            catch (Exception ex)
134
            {
135
                bl.AppendLine("<ServiceUri Error>");
136
                bl.AppendLine(ex.ToString());
137
                bl.AppendLine("_________________________");
138
            }
139

    
140
            try
141
            {
142
                _info.ServiceID = ServiceID;
143
            }
144
            catch (Exception ex)
145
            {
146
                bl.AppendLine("ServiceID Error :");
147
                bl.AppendLine("service ID : " + ServiceID.ToString());
148
                bl.AppendLine(ex.ToString());
149
                bl.AppendLine("_________________________");
150
            }
151

    
152
            try
153
            {
154
                _info.StorageInfo = TileSorceStorageInfomation(); ;
155
            }
156
            catch (Exception ex)
157
            {
158
                bl.AppendLine("TileSorceStorageInfomation Error :");
159
                bl.AppendLine(ex.ToString());
160
                bl.AppendLine("_________________________");
161
            }
162

    
163
            if (bl.Length > 0)
164
                _info.Exception = bl.ToString();
165

    
166
            return _info;
167
        }
168

    
169
        public TileSorceStorageInfo[] TileSorceStorageInfomation()
170
        {
171
            List<TileSorceStorageInfo> _info = new List<TileSorceStorageInfo>();
172
            string _TestDir = "createTestDir";
173

    
174
            using (DeepView_Entity _deepview = new DeepView_Entity(ConnectStringBuilder.DeepViewConnectionString().ToString()))
175
            {
176
                var _storage = (from proper in _deepview.PROPERTIES
177
                                where proper.TYPE == PropertiesType.PropertiesType.Const_TileSorceStorage
178
                                group proper by proper.VALUE into p
179
                                select p.Key
180
                                ).ToList();
181

    
182
                _storage.ForEach(s =>
183
                {
184
                    TileSorceStorageInfo _storageInfo = new TileSorceStorageInfo();
185
                    _storageInfo.FolderName = s;
186
                    _storageInfo.FreeSpace = FreeSpace(s);
187

    
188
                    try
189
                    {
190
                        DirectoryInfo _Dirinfo = new DirectoryInfo(s);
191

    
192
                        var _dir = _Dirinfo.EnumerateDirectories().Where(d => d.Name == _TestDir);
193

    
194
                        if (_dir.Count() == 0)
195
                            _Dirinfo = _Dirinfo.CreateSubdirectory("createTestDir");
196
                        else
197
                            _Dirinfo = _dir.First();
198

    
199
                        if (_Dirinfo.Exists)
200
                            _Dirinfo.Delete(true);
201

    
202
                        _Dirinfo = new DirectoryInfo(_Dirinfo.FullName);
203

    
204
                        if (!_Dirinfo.Exists)
205
                            _storageInfo.Access = true;
206
                    }
207
                    catch (Exception ex)
208
                    {
209
                        throw;
210
                    }
211

    
212
                    _info.Add(_storageInfo);
213
                });
214
            }
215

    
216
            return _info.ToArray();
217
        }
218

    
219
        public bool ServiceOn(Guid ServiceID)
220
        {
221
            try
222
            {
223
                SetSubPassService();
224
            }
225
            catch (Exception ex)
226
            {
227
                SendError("Service On Error", ex.ToString(), 0);
228
            }
229

    
230
            return true;
231
        }
232
        #endregion
233

    
234
        #region Constructors
235

    
236
        public ConverterService(ServiceEventLog eventLog)
237
        {
238
            var IsServerSet = SetServerSetting();
239

    
240
            _log = eventLog;
241

    
242
            if (_WorkItems == null)
243
                _WorkItems = new Queue<CONVERTER_DOC>();
244

    
245
            if (_thread == null)
246
                _thread = new List<CONVERTER_DOC>();
247

    
248
            if (IsServerSet)
249
            {
250
                InitWork();
251
            }
252
            else
253
                _log.Write("Converter Service 호스트 이름을 찾을 수 없습니다.");
254

    
255
        }
256

    
257
        #endregion
258

    
259
        #region Event of DZConverter
260
        void dz_EndConverter(object sender, EndConverterEventArgs e)
261
        {
262
            var _T = _thread.Where(t => t.ID == (sender as DZConverterLib.DZConverter).ConverterItem.ID);
263

    
264
            if (_T.Count() > 0)
265
            {
266
                Guid _id = Guid.Parse(_T.First().ID);
267
                SetConveterState(_id, IConverterPDF.ConverterStatus.Success);
268
                _thread.Remove((sender as DZConverterLib.DZConverter).ConverterItem);
269
                (sender as DZConverterLib.DZConverter).ConverterMakeError -= new EventHandler<MakeConverterErrorArgs>(dz_ConverterMakeError);
270
                (sender as DZConverterLib.DZConverter).EndConverter -= new EventHandler<EndConverterEventArgs>(dz_EndConverter);
271
                (sender as DZConverterLib.DZConverter).Dispose();
272
            }
273
            else
274
            {
275
                SetError(Guid.Parse((sender as DZConverterLib.DZConverter).ConverterItem.ID), "Thread Count 0", "Thread가 없습니다", 0);
276
            }
277

    
278
            if (_WorkItems.Count() == 0 && this.SeriviceType == ConverterServiceType.Main)
279
                ReAttemptConverterPDF();
280
        }
281

    
282
        void dz_ConverterMakeError(object sender, MakeConverterErrorArgs e)
283
        {
284
            SetError(e.ConverterID, e.ErrorCode, e._Exception, e.Level);
285

    
286
            try
287
            {
288
                if (e.ThreadStop)
289
                {
290
                    _thread.Remove((sender as DZConverterLib.DZConverter).ConverterItem);
291
                    (sender as DZConverterLib.DZConverter).ConverterMakeError -= new EventHandler<MakeConverterErrorArgs>(dz_ConverterMakeError);
292
                    (sender as DZConverterLib.DZConverter).EndConverter -= new EventHandler<EndConverterEventArgs>(dz_EndConverter);
293
                    (sender as DZConverterLib.DZConverter).Dispose();
294
                }
295
            }
296
            catch (Exception ex)
297
            {
298
                SetError(e.ConverterID, "dz_ConverterMakeError에서 Thread 제거 불가", ex.ToString(), 0);
299
            }
300
        }
301
        #endregion
302

    
303
        #region Method
304
        private void CreateServerSetting()
305
        {
306
            hostName = System.Environment.MachineName;
307

    
308
            using (DeepView_Entity de = new DeepView_Entity(ConnectStringBuilder.DeepViewConnectionString().ToString()))
309
            {
310
                var serviceProperties = de.SERVICE_PROPERTIES.Where(host => host.HOST_NAME == hostName);
311

    
312
                if (serviceProperties.Count() == 0)
313
                {
314
                    SERVICE_PROPERTIES serviceProperty = new SERVICE_PROPERTIES();
315
                    serviceProperty.ID = GuidGenerator.GetUniqueGuid().ToString();
316
                    serviceProperty.HOST_NAME = hostName;
317

    
318
                    IPAddress ipaddress = Dns.Resolve(Dns.GetHostName()).AddressList[0];
319
                    serviceProperty.SERVICE_ADDRESS = ipaddress.ToString();
320
                    serviceProperty.SERVICE_PORT = Properties.Settings.Default.RemotingPort;
321
                    serviceProperty.PROCESS_COUNT = Properties.Settings.Default.MultipleConverterCount;
322
                    serviceProperty.SERVICET_TYPE = (int)PropertiesType.ConverterServiceType.Sub;
323

    
324
                    de.SERVICE_PROPERTIES.AddObject(serviceProperty);
325
                    de.SaveChanges();
326
                    
327
                }
328
            }
329
        }
330

    
331
        public bool SetServerSetting()
332
        {
333
            bool SettingCompleted = false;
334

    
335
            hostName = System.Environment.MachineName;
336

    
337
            try
338
            {
339
                using (DeepView_Entity de = new DeepView_Entity(ConnectStringBuilder.DeepViewConnectionString().ToString()))
340
                {
341
                    var serviceProperties = de.SERVICE_PROPERTIES.Where(host => host.HOST_NAME == hostName);
342

    
343
                    if (serviceProperties.Count() > 0)
344
                    {
345
                        var serviceProperty = serviceProperties.First();
346
                        remotingPort = int.Parse(serviceProperty.SERVICE_PORT.ToString());
347
                        ServiceID = Guid.Parse(serviceProperty.ID);
348
                        MultiProcessCount = serviceProperty.PROCESS_COUNT;
349
                        SeriviceType = (ConverterServiceType)serviceProperty.SERVICET_TYPE;
350
                    }
351
                    else
352
                    {
353
                        CreateServerSetting();
354
                    }
355

    
356
                    SettingCompleted = true;
357
                }
358
            }
359
            catch (Exception ex)
360
            {
361
                SettingCompleted = false;
362
                _log.Write("ServerSetting Error : " + ex.ToString());
363
            }
364

    
365
            return SettingCompleted;
366
        }
367

    
368
        private static long FreeSpace(string folderName)
369
        {
370
            if (string.IsNullOrEmpty(folderName))
371
            {
372
                throw new ArgumentNullException("folderName");
373
            }
374

    
375
            if (!folderName.EndsWith("\\"))
376
            {
377
                folderName += '\\';
378
            }
379

    
380
            long free = 0, dummy1 = 0, dummy2 = 0;
381

    
382
            if (GetDiskFreeSpaceEx(folderName, ref free, ref dummy1, ref dummy2))
383
            {
384
                return free;
385
            }
386
            else
387
            {
388
                return -1;
389
            }
390
        }
391

    
392
        public void InitWork()
393
        {
394
            Thread _initThread = new Thread(new ThreadStart(Init));
395
            _initThread.Start();
396
        }
397

    
398
        public void InitializeProcess()
399
        {
400
            using (DeepView_Entity _deepview = new DeepView_Entity(ConnectStringBuilder.DeepViewConnectionString().ToString()))
401
            {
402
                _serviceID = ServiceID.ToString();
403
                var _converterItems = _deepview.CONVERTER_DOC.Where(c => c.SERVICE_ID == _serviceID &&
404
                                                                        c.STATUS != (int)ConverterStatus.Success &&
405
                                                                        c.RECONVERTER < 3);
406
                foreach (var item in _converterItems)
407
                {
408
                    item.STATUS = 0;
409
                    item.RECONVERTER = 1;
410
                    item.SERVICE_ID = null;
411
                }
412

    
413
                if (_converterItems.Count() > 0)
414
                    _deepview.SaveChanges();
415
            }
416
        }
417

    
418
        public void Init()
419
        {
420
            try
421
            {
422
                channel = new TcpChannel(remotingPort);
423
                ChannelServices.RegisterChannel(channel, false);
424
                RemotingConfiguration.RegisterWellKnownServiceType(typeof(RemConverterPDFObject), "remConverterPDF", WellKnownObjectMode.Singleton);
425
                IConverterPDF.Cache.Attach(this);
426

    
427
                _log.Write("Notice <Service Infomation>");
428
                _log.Write("Port" + remotingPort.ToString());
429
                _log.Write("HostName" + hostName);
430
                _log.Write("Service ID :" + ServiceID.ToString());
431
                _log.Write("Service Type :" + SeriviceType.ToString());
432
                _log.Write("Service Host :" + hostName);
433

    
434
                if (hostName != null)
435
                {
436
                    InitializeProcess();
437

    
438
                    foreach (var item in TileSorceStorageInfomation())
439
                    {
440
                        _log.Write("Storage(" + item.FolderName + ") " +
441
                                  (item.FreeSpace / 1024f) / 1024f / 1024f + "GB");
442
                    }
443

    
444
                    //0번일 때
445
                    if (this.SeriviceType == ConverterServiceType.Main)
446
                    {                               
447
                        //Sub 
448
                        _log.Write("SetSubPassService :" + SetSubPassService());
449
                        ReAttemptConverterPDF();
450
                    }
451
                    else
452
                    {
453
                        List<SERVICE_PROPERTIES> _service = new List<SERVICE_PROPERTIES>();
454

    
455
                        using (DeepView_Entity _deepview = new DeepView_Entity(ConnectStringBuilder.DeepViewConnectionString().ToString()))
456
                        {
457
                            _service = _deepview.SERVICE_PROPERTIES.ToList();
458

    
459
                            _log.Write("_service :" + _service.First().ToString());
460
                            var _mainService = _service.Where(s => s.HOST_NAME == hostName &&
461
                                            (ConverterServiceType)s.SERVICET_TYPE == ConverterServiceType.Main);
462

    
463
                            _log.Write("_mainService_count :" + _mainService.Count());
464
                            if (_mainService.Count() > 0)
465
                            {
466
                                var mainservice = _mainService.First();
467

    
468
                                try
469
                                {
470
                                    RemConverterPDFObject rem = (RemConverterPDFObject)Activator.GetObject(typeof(RemConverterPDFObject),
471
                                                               "tcp://" + mainservice.SERVICE_ADDRESS + ":"
472
                                                               + mainservice.SERVICE_PORT + "/remConverterPDF");
473
                                
474
                                    if (rem != null)
475
                                        rem.ServiceOn(ServiceID); //SetSubPassService() 메서드 호출
476
                                }
477
                                catch (Exception ex)
478
                                {
479
                                    _log.Write("Main Connection Error  : " + ex.ToString());
480
                                }
481
                            }
482
                        }
483
                    }
484
                }
485
                else
486
                {
487
                    _log.Write("Converter Service : " + hostName + "데이터베이스에서 호스트 정보를 찾을 수 없습니다.");
488
                }
489

    
490
                //SendError("Start Service Info.", _ServiceStartRpt.ToString(), 0);
491
            }
492
            catch (Exception ex)
493
            {
494
                if (_log != null)
495
                    _log.Write("RemConverterStation" + "02156");
496
            }
497
        }
498

    
499
        private Uri ServiceUri()
500
        {
501
            Uri _result = null;
502

    
503
            try
504
            {
505
                if (channel.ChannelData != null)
506
                    if (channel.ChannelData.GetType() == typeof(ChannelDataStore))
507
                    {
508
                        var _uris = (channel.ChannelData as ChannelDataStore).ChannelUris;
509

    
510
                        if (_uris.Count() > 0)
511
                            _result = new Uri(_uris[0]);
512
                    }
513
            }
514
            catch (Exception)
515
            {
516
                new Exception("service Uri Eorror");
517
            }
518

    
519
            return _result;
520
        }
521

    
522
        public string SetSubPassService()
523
        {
524
            if (LstService == null) LstService = new List<ServiceItem>();
525

    
526
            StringBuilder _ServiceStartRpt = new StringBuilder();
527
            List<SERVICE_PROPERTIES> _service = new List<SERVICE_PROPERTIES>();
528

    
529
            using (DeepView_Entity _deepview = new DeepView_Entity(ConnectStringBuilder.DeepViewConnectionString().ToString()))
530
            {
531
                //_service = _deepview.ServiceProperties.Where(f => f.HostName.ToLower() 
532
                //                                            == hostName.ToLower()).ToList();
533

    
534
                _service = _deepview.SERVICE_PROPERTIES.ToList();
535
            }
536
            _serviceID = ServiceID.ToString();
537
            //강인구
538
            _service.ForEach(s =>
539
            {
540
                _ServiceID = Guid.Parse(s.ID);
541
                if (s.ID != _serviceID && LstService.Where(ser => ser.ServiceID == _ServiceID).Count() == 0)
542
                {
543
                    System.Runtime.Remoting.Channels.IChannel _ch = ChannelServices.GetChannel("tcp");
544

    
545
                    if (_ch == null)
546
                    {
547
                        TcpChannel chan = new TcpChannel();
548
                        ChannelServices.RegisterChannel(chan, false);
549
                    }
550
                    // Create an instance of the remote object
551
                    RemConverterPDFObject rem = (RemConverterPDFObject)Activator.GetObject(typeof(RemConverterPDFObject),
552
                                                                "tcp://" + s.SERVICE_ADDRESS + ":" + s.SERVICE_PORT + "/remConverterPDF");
553

    
554
                    try
555
                    {
556
                        rem.MultiProcessCount = s.PROCESS_COUNT;
557

    
558
                        var _Info = rem.ServiceInfomation();
559

    
560
                        _ServiceStartRpt.AppendLine("");
561
                        _ServiceStartRpt.AppendLine("Service Type :" + ((ConverterServiceType)s.SERVICET_TYPE).ToString());
562
                        _ServiceStartRpt.AppendLine("Service ID :" + s.ID.ToString());
563
                        _ServiceStartRpt.AppendLine("Service Address :" + _Info.ServiceUri);
564

    
565

    
566
                        foreach (var item in _Info.StorageInfo)
567
                        {
568
                            _ServiceStartRpt.AppendLine("Storage(" + item.FolderName + ") Access:" + item.Access.ToString());
569
                        }
570

    
571
                        var _runningItem = rem.RunningProcessID();
572

    
573
                        _ServiceStartRpt.AppendLine("");
574
                        _ServiceStartRpt.AppendLine("Running Item");
575

    
576
                        _runningItem.ToList().ForEach(f =>
577
                        {
578
                            _ServiceStartRpt.AppendLine(f.ToString());
579
                        });
580
                        //여기
581
                        LstService.Add(new ServiceItem { RemotingSerivce = rem, ServiceID = Guid.Parse(s.ID) });
582
                    }
583
                    catch (Exception ex)
584
                    {
585
                        StringBuilder _bl = new StringBuilder();
586
                        _bl.AppendLine("<Sub Service Infomation Error>");
587
                        _bl.AppendLine("Service ID :" + s.ID.ToString());
588
                        _bl.AppendLine("Service Address :" + s.SERVICE_ADDRESS);
589
                        _bl.AppendLine("Service Port :" + s.SERVICE_PORT);
590
                        _bl.AppendLine(ex.ToString());
591
                        SendError("Service Not Found", _bl.ToString(), 0);
592
                    }
593
                }
594
            });
595

    
596
            return _ServiceStartRpt.ToString();
597
        }
598

    
599
        public void ReAttemptConverterPDF()
600
        {
601
            using (DeepView_Entity _deepview = new DeepView_Entity(ConnectStringBuilder.DeepViewConnectionString().ToString()))
602
            {
603
                _log.Write("_deepview in");
604
                var _ConverterList = _deepview.CONVERTER_DOC.Where(converter
605
                                          => (converter.STATUS != (int)IConverterPDF.ConverterStatus.Success
606
                                              && converter.STATUS != (int)IConverterPDF.ConverterStatus.Error && converter.SERVICE_ID == null)
607
                                              || (converter.STATUS == (int)IConverterPDF.ConverterStatus.Error && converter.RECONVERTER < 4));
608

    
609
                _log.Write("_ConverterList count" + _ConverterList.Count());
610
                if (_ConverterList.Count() > 0)
611
                {
612
                    var _exceptItem = _ConverterList.Except(_WorkItems.ToList());
613

    
614
                    List<CONVERTER_DOC> _insertItem = _exceptItem.Except(_thread).ToList();
615
                    List<CONVERTER_DOC> _workingItem = new List<CONVERTER_DOC>();
616

    
617
                    if (LstService != null)
618
                    {
619
                        for (int i = 0; i < LstService.Count(); i++)
620
                        {
621
                            //var _guid = LstService[i].RemotingSerivce.RunningProcessID();
622
                            string _guid = LstService[i].RemotingSerivce.RunningProcessID().ToString();
623
                            
624

    
625
                            var _lstconvert = from c in _deepview.CONVERTER_DOC
626
                                              where _guid.Contains(c.ID)
627
                                              select c;
628

    
629
                            if (_lstconvert.Count() > 0)
630
                                _workingItem.AddRange(_lstconvert.ToList());
631
                        }
632
                    }
633

    
634
                    _workingItem.ForEach(f =>
635
                    {
636
                        var _items = _insertItem.Where(item => item.PROJECT_NO == f.PROJECT_NO &&
637
                                                               item.DOCUMENT_ID == f.DOCUMENT_ID);
638

    
639
                        if (_items.Count() > 0)
640
                        {
641
                            CONVERTER_DOC _SubWorkingitem = _items.First();
642
                            _insertItem.Remove(_SubWorkingitem);
643
                        }
644
                    });
645

    
646
                    StartConverterPDFProcess(_insertItem);
647
                }
648
            }
649
        }
650

    
651
        private void StartConverterPDFProcess(List<CONVERTER_DOC> lstConverterPDF)
652
        {
653
            if (lstConverterPDF.Count() > 0)
654
            {
655
                foreach (var item in lstConverterPDF)
656
                {
657
                    System.Diagnostics.Debug.WriteLine("ConverterPDF Item 추가" + item.ID);
658
                    _WorkItems.Enqueue(item);
659
                }
660

    
661
                if (_ConverterPdfThread == null)
662
                {
663
                    _ConverterPdfThread = new Thread(new ThreadStart(ConverterPDFProcess));
664
                    _ConverterPdfThread.SetApartmentState(ApartmentState.MTA);
665
                    _ConverterPdfThread.Start();
666
                }
667
            }
668
        }
669

    
670
        private void ConverterPDFProcess()
671
        {
672
            while (_WorkItems.Count() > 0)
673
            {
674
                if (_thread.Count() < _MultiProcessCount)
675
                {
676
                    CONVERTER_DOC _item = _WorkItems.Dequeue();
677
                    var _identPathItem = _thread.Where(item => item.DOCUMENT_URL == _item.DOCUMENT_URL);
678

    
679
                    if (_identPathItem.Count() > 0)
680
                    {
681
                        _WorkItems.Enqueue(_item);
682
                    }
683
                    else
684
                    {
685
                        DZConverter dz = new DZConverter();
686
                        dz.ConverterMakeError += new EventHandler<MakeConverterErrorArgs>(dz_ConverterMakeError);
687
                        dz.EndConverter += new EventHandler<EndConverterEventArgs>(dz_EndConverter);
688

    
689
                        Thread _stathread = new Thread(new ParameterizedThreadStart(dz.GetSingleFile));
690
                        _stathread.Name = _item.ID.ToString();
691
                        _stathread.SetApartmentState(ApartmentState.MTA); //multithreaded apartment(MTA)
692
                        _stathread.Start(_item); //Parameter 전달
693
                        _thread.Add(_item);
694

    
695
                        SetConveterState(Guid.Parse(_item.ID), IConverterPDF.ConverterStatus.Wait);
696
                        System.Diagnostics.Debug.WriteLine("Status Change : " + _item.ID);
697
                    }
698
                }
699
                else
700
                {
701
                    if (this.SeriviceType == ConverterServiceType.Main)
702
                    {
703
                        bool _subpass = false;
704
                        CONVERTER_DOC _item = _WorkItems.Dequeue();
705

    
706
                        try
707
                        {
708
                            for (int i = 0; i < LstService.Count; i++)
709
                            {
710
                                int maxCount = LstService[i].RemotingSerivce.MultiProcessCount;
711
                                Guid[] _id = LstService[i].RemotingSerivce.RunningProcessID();
712

    
713
                                if (maxCount > _id.Count())
714
                                {
715
                                    var _conveter = LstService[i].RemotingSerivce.SetConverterPDF(_item.PROJECT_NO, Guid.Parse(_item.ID));
716

    
717
                                    if (_conveter.Exception == null)
718
                                    {
719
                                        _subpass = true;
720
                                        break;
721
                                    }
722
                                }
723
                            }
724

    
725
                        }
726
                        catch (Exception ex)
727
                        {
728
                            //SendError("subPass Error :" + ex.ToString());
729
                        }
730

    
731
                        if (!_subpass) _WorkItems.Enqueue(_item);
732
                    }
733
                }
734

    
735
                Thread.Sleep(10);
736
            }
737
            _ConverterPdfThread = null;
738
        }
739

    
740
        private void SetConveterState(Guid ConverterID, IConverterPDF.ConverterStatus Status)
741
        {
742
            using (DeepView_Entity _deepview = new DeepView_Entity(ConnectStringBuilder.DeepViewConnectionString().ToString()))
743
            {
744
                _serviceID = ConverterID.ToString();
745
                var converterList = _deepview.CONVERTER_DOC.Where(Converter => Converter.ID == _serviceID);
746

    
747
                if (converterList.Count() > 0)
748
                {
749
                    converterList.First().STATUS = (int)Status;
750

    
751
                    if (Status == ConverterStatus.Create)
752
                    {
753
                        converterList.First().START_DATETIME = DateTime.Now;
754
                    }
755
                    else if (Status == ConverterStatus.Success)
756
                    {
757
                        converterList.First().END_DATETIME = DateTime.Now;
758
                    }
759

    
760
                    converterList.First().SERVICE_ID = ServiceID.ToString();
761

    
762
                    _deepview.SaveChanges();
763
                }
764
            }
765
        }
766

    
767
        private void SetError(Guid ConverterID, string Msg, string Ex, int level)
768
        {
769
            try
770
            {
771
                using (DeepView_Entity _deepview = new DeepView_Entity(ConnectStringBuilder.DeepViewConnectionString().ToString()))
772
                {
773
                    _serviceID = ConverterID.ToString();
774
                    var ConverterList = _deepview.CONVERTER_DOC.Where(converter => converter.ID == _serviceID);
775

    
776
                    if (ConverterList.Count() > 0)
777
                    {
778
                        ConverterList.First().STATUS = (int)IConverterPDF.ConverterStatus.Error;
779
                        ConverterList.First().EXCEPTION = Msg;
780
                        _deepview.SaveChanges();
781
                    }
782
                }
783
            }
784
            catch (Exception ex)
785
            {
786
                _log.Write("database insert error" + "100");
787
            }
788

    
789
            try
790
            {
791
                StringBuilder _bl = new StringBuilder();
792
                _bl.AppendLine("ConverterPDFID : " + ConverterID.ToString());
793
                _bl.AppendLine(Msg);
794

    
795
                //SendError(_bl.ToString(), Ex, level);
796
            }
797
            catch (Exception ex)
798
            {
799
                _log.Write("SendMail Error" + "1023");
800
            }
801
        }
802

    
803

    
804
        void SendError(string Msg, string ex, int Level)
805
        {
806
            List<EmailModel> toEmailModels = new List<EmailModel>();
807

    
808
            EmailModel fromEmailModel = null;
809

    
810
            List<string> _lstID = new List<string>();
811

    
812
            if (!string.IsNullOrWhiteSpace(Properties.Settings.Default.ErrorNoticeID))
813
            {
814
                using (DeepView_Entity de = new DeepView_Entity(ConnectStringBuilder.DeepViewConnectionString().ToString()))
815
                {
816
                    //var errorUserList = de.ToEmail.Where(f => f.ServiceID.Value == ServiceID).ToList();
817
                    ////수신자
818
                    //errorUserList.ForEach(emailItem =>
819
                    //{
820
                    //    toEmailModels.Add(new EmailModel()
821
                    //                    {
822
                    //                        Host = emailItem.Host,
823
                    //                        UserID = emailItem.UserID,
824
                    //                        ServiceId = emailItem.ServiceID.Value
825
                    //                    });
826
                    //});
827

    
828
                    ////발신자
829
                    //var emailModel = de.FromEmail.Where(fo => fo.ServiceID == ServiceID);
830

    
831
                    //if (emailModel.Count() > 0)
832
                    //{
833
                    //    var emailItem = emailModel.First();
834
                    //    fromEmailModel = new EmailModel()
835
                    //                    {
836
                    //                        Host = emailItem.Host,
837
                    //                        UserID = emailItem.UserID,
838
                    //                        Smtp = emailItem.Smtp,
839
                    //                        ServiceId = emailItem.ServiceID.Value,
840
                    //                        SmtpPort = emailItem.SmtpPort.Value
841
                    //                    };
842
                    //}
843
                }
844

    
845

    
846
                //if (fromEmailModel != null && toEmailModels.Count > 0)
847
                //{
848
                //    string header = "<Converter Service Error Notice>";
849

    
850
                //    EmailClient.EmailClient _client =
851
                //            new EmailClient.EmailClient(fromEmailModel.UserID, fromEmailModel.Host);
852

    
853
                //    _client.Smtp = fromEmailModel.Smtp;
854
                //    _client.SmtpPort = fromEmailModel.SmtpPort;
855
                //    _client.IsSSL = true;
856
                //    _client.Send(toEmailModels, header, Msg, false);
857
                //}
858
            }
859
        }
860
        #endregion
861

    
862
        #region extern method
863
        [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressUnmanagedCodeSecurity]
864
        [DllImport("Kernel32", SetLastError = true, CharSet = CharSet.Auto)]
865
        [return: MarshalAs(UnmanagedType.Bool)]
866
        private static extern bool GetDiskFreeSpaceEx
867
        (
868
            string lpszPath,                    // Must name a folder, must end with '\'.
869
            ref long lpFreeBytesAvailable,
870
            ref long lpTotalNumberOfBytes,
871
            ref long lpTotalNumberOfFreeBytes
872
        );
873

    
874
        #endregion
875

    
876
        //public void Init2()
877
        //{
878
        //    try
879
        //    {
880
        //        StringBuilder _ServiceStartRpt = new StringBuilder();
881
        //        _ServiceStartRpt.AppendLine("<Service Infomation>");
882

    
883
        //        int _RemotingPort = Properties.Settings.Default.RemotingPort;
884
        //        channel = new TcpChannel(_RemotingPort);
885
        //        ChannelServices.RegisterChannel(channel, false);
886
        //        RemotingConfiguration.RegisterWellKnownServiceType(typeof(RemConverterPDFObject),
887
        //                                                            "remConverterPDF", WellKnownObjectMode.Singleton);
888

    
889
        //        IConverterPDF.Cache.Attach(this);
890
        //        CheckWaitItem();
891

    
892
        //    }
893
        //    catch (Exception ex)
894
        //    {
895
        //        if (_log != null)
896
        //            _log.Write("RemConverterStation  : " + ex.ToString());
897
        //    }
898
        //}
899

    
900
    }
901
}
클립보드 이미지 추가 (최대 크기: 500 MB)