프로젝트

일반

사용자정보

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

markus / ConvertService / ServiceBase / Markus.Service.StationController / ViewModel / DataBaseItemsModel.cs @ a6e5055d

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

1
using GemBox.Spreadsheet;
2
using Markus.Message;
3
using Markus.Service.DataBase;
4
using Markus.Service.Extensions;
5
using Markus.Service.StationController.Behaviors;
6
using Markus.Service.StationController.Extensions;
7
using Microsoft.Win32;
8
using System;
9
using System.Collections.Generic;
10
using System.ComponentModel;
11
using System.Linq;
12
using System.Windows;
13
using Telerik.Windows.Controls;
14
using Telerik.Windows.Data;
15
using ConvertItem = Markus.Service.Interface.ConvertItem;
16

    
17
namespace Markus.Service.StationController.ViewModel
18
{
19
    //세미
20
    public class DataBaseItemsModel : Mvvm.ToolKit.ViewModelBase
21
    {
22
        BackgroundWorker backgroundWorker;
23

    
24
        Random rnd = new Random();
25

    
26
        private System.Collections.ObjectModel.ObservableCollection<ConvertItem> _FilterConvertSource;
27
        private ConvertItem _SelectRealConvert;
28
        private ConvertItem _SelectFilterConvert;
29

    
30
        private StatusTypeList _StatusType;
31
        private bool _IsLoading;
32

    
33
        private Telerik.Windows.Data.EnumMemberViewModel _SelectedStatus;
34

    
35
        public Telerik.Windows.Data.EnumMemberViewModel SelectedStatus
36
        {
37
            get => _SelectedStatus;
38
            set
39
            {
40
                _SelectedStatus = value;
41
                OnPropertyChanged(() => SelectedStatus);
42
            }
43
        }
44

    
45

    
46
        private SelectedCountItem _SelectedCount;
47

    
48
        public SelectedCountItem SelectedCount
49
        {
50
            get => _SelectedCount;
51
            set
52
            {
53
                _SelectedCount = value;
54
                OnPropertyChanged(() => SelectedCount);
55
            }
56
        }
57

    
58

    
59
        public DelegateCommand ConvertCommand { get; private set; }
60
        public DelegateCommand DeleteCommand { get; private set; }
61

    
62

    
63
        private void DataConvert(object obj)
64
        {
65
            ConvertDatabase _DataConvert = new ConvertDatabase(App.MarkusDataBaseConnecitonString);
66

    
67
            var resultRealConvert = _DataConvert.SetCleanUpItem(SelectRealConvert.ConvertID, SelectRealConvert.ReConverter);
68
            var resultFiltertConvert = _DataConvert.SetCleanUpItem(SelectFilterConvert.ConvertID, SelectFilterConvert.ReConverter);
69
            System.Diagnostics.Debug.WriteLine(resultRealConvert + "  " + resultFiltertConvert);
70
        }
71

    
72
        private void DataDelete(object obj)
73
        {
74
            ConvertDatabase _DataConvert = new ConvertDatabase(App.MarkusDataBaseConnecitonString);
75

    
76
            var resultRealConvert = _DataConvert.RemoveItem(SelectRealConvert.ConvertID);
77
            var resultFiltertConvert = _DataConvert.RemoveItem(SelectFilterConvert.ConvertID);
78
            System.Diagnostics.Debug.WriteLine(resultRealConvert + "  " + resultFiltertConvert);
79

    
80
        }
81

    
82

    
83
        public System.Collections.ObjectModel.ObservableCollection<ConvertItem> FilterConvertSource
84
        {
85
            get => _FilterConvertSource;
86
            set
87
            {
88
                _FilterConvertSource = value;
89
                OnPropertyChanged(() => FilterConvertSource);
90
            }
91
        }
92

    
93

    
94
        private System.Collections.ObjectModel.ObservableCollection<ConvertItem> _RealConvertSource;
95
        public System.Collections.ObjectModel.ObservableCollection<ConvertItem> RealConvertSource
96
        {
97
            get => _RealConvertSource;
98
            set
99
            {
100
                _RealConvertSource = value;
101
                OnPropertyChanged(() => RealConvertSource);
102
            }
103
        }
104

    
105

    
106

    
107
        public ConvertItem SelectFilterConvert
108
        {
109
            get => _SelectFilterConvert;
110
            set
111
            {
112
                _SelectFilterConvert = value;
113
                OnPropertyChanged(() => SelectFilterConvert);
114
            }
115
        }
116
        public ConvertItem SelectRealConvert
117
        {
118
            get => _SelectRealConvert;
119
            set
120
            {
121
                _SelectRealConvert = value;
122
                OnPropertyChanged(() => SelectRealConvert);
123
            }
124
        }
125

    
126
        public StatusTypeList StatusType
127
        {
128
            get => _StatusType;
129
            set
130
            {
131
                _StatusType = value;
132
                OnPropertyChanged(() => StatusType);
133
            }
134
        }
135

    
136
        public bool IsLoading
137
        {
138
            get => _IsLoading;
139
            set
140
            {
141
                if (_IsLoading != value)
142
                {
143
                    _IsLoading = value;
144
                    OnPropertyChanged(() => IsLoading);
145
                }
146
            }
147
        }
148

    
149
        List<SelectedCountItem> _SelectedCountList;
150

    
151
        public List<SelectedCountItem> SelectedCountList
152
        {
153
            get
154
            {
155
                if (_SelectedCountList == null)
156
                {
157
                    _SelectedCountList = new List<SelectedCountItem>
158
                    {
159
                        new SelectedCountItem{DisplayMember = "50",ValueMember = 50},
160
                        new SelectedCountItem{DisplayMember = "100",ValueMember = 100},
161
                        new SelectedCountItem{DisplayMember = "150",ValueMember = 150},
162
                        new SelectedCountItem{DisplayMember = "200",ValueMember = 200}
163
                    };
164
                }
165

    
166
                return _SelectedCountList;
167
            }
168
        }
169

    
170
        public DataBaseItemsModel()
171
        {
172

    
173
            DataSaveFileGemBoxCommand = new DelegateCommand(DataExport);
174
            ConvertCommand = new DelegateCommand(DataConvert);
175
            DeleteCommand = new DelegateCommand(DataDelete);
176
            //Loaded();
177
        }
178

    
179
        // 진행률에 변화가 있을때 이벤트가 발생
180
        private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
181
        {
182
            MessageBox.Show("진행률에 변화");
183
        }
184

    
185
        // 일이 모두 마쳤을때 수행되어야할 코드
186
        private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
187
        {
188
            MessageBox.Show("임무마침");
189
        }
190

    
191
        IEnumerable<Telerik.Windows.Data.EnumMemberViewModel> _StatusCodeList;
192

    
193
        public IEnumerable<Telerik.Windows.Data.EnumMemberViewModel> StatusCodeList
194
        {
195
            get
196
            {
197
                if (_StatusCodeList == null)
198
                {
199
                    _StatusCodeList = Telerik.Windows.Data.EnumDataSource.FromType<StatusCodeType>();
200
                }
201

    
202
                return _StatusCodeList;
203
            }
204
        }
205

    
206
        // BackgroundWorker에서 수행할 일을 정의.
207
        private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
208
        {
209
            while (IsAcitve)
210
            {
211
                if (FilterConvertSource == null)
212
                {
213
                    FilterConvertSource = new System.Collections.ObjectModel.ObservableCollection<ConvertItem>();
214
                }
215

    
216
                if (RealConvertSource == null)
217
                {
218
                    RealConvertSource = new System.Collections.ObjectModel.ObservableCollection<ConvertItem>();
219
                }
220

    
221
                /// combobox 에서 선택된 items
222
                if (SelectedStatus != null)
223
                {
224
                    DataSelect(new[] { (StatusCodeType)(SelectedStatus.Value) }, FilterConvertSource);
225
                }
226

    
227
                /// 컨버터중인 items
228
                DataSelect(new[] { StatusCodeType.None, StatusCodeType.Wait, StatusCodeType.PageLoading, StatusCodeType.Saving }, RealConvertSource);
229
            }
230
        }
231

    
232
        //<>쓸때는 IEnumerable 
233
        private void DataSelect(IEnumerable<StatusCodeType> statusCodeTypeList, System.Collections.ObjectModel.ObservableCollection<ConvertItem> collection)
234
        {
235
      
236
            try
237
            {
238
                using (Markus.Service.DataBase.ConvertDatabase database = new Markus.Service.DataBase.ConvertDatabase(App.MarkusDataBaseConnecitonString))
239
                {
240
                    var items = database.GetConvertProjects(x => statusCodeTypeList.Count(y => (int)y == x.STATUS) > 0)
241
                                                .OrderByDescending(x => x.CreateTime).Take(SelectedCount.ValueMember).ToList();
242

    
243
                    if (collection.Count() == 0)
244
                    {
245
                        items.ForEach(x => collection.Add(x));
246
                    }
247
                    else
248
                    {
249
                        // 데이터 업데이트
250
                        items.ForEach(newitem =>//디비 포문
251
                        {
252
                            collection.UpdateWhere(changeitem =>
253
                            {
254
                                ConvertItemEx.ChangeValues(changeitem, newitem);
255
                                System.Threading.Thread.Sleep(new TimeSpan(0, 0, 0, 0, 10));
256

    
257
                            }, x => x.ConvertID == newitem.ConvertID);//UpdateWhere의  where절
258
                        });
259

    
260
                        foreach (var item in items)
261
                        {
262
                            //  System.Threading.Thread.Sleep(1);
263
                            if (collection.Count(x => x.ConvertID == item.ConvertID && x.ProjectNumber == item.ProjectNumber) == 0)
264
                            {
265
                                collection.Add(item);
266
                            }
267

    
268
                        }
269

    
270
                        //삭제
271
                        for (int i = collection.Count() - 1; i > -1; --i)
272
                        {
273
                            var item = collection[i];
274

    
275
                            if (items.Count(x => x.ConvertID == item.ConvertID && x.ProjectNumber == item.ProjectNumber) == 0)//디비에서 가져온 값과 마지막값부터 차례대로 비교
276
                            {//참=> 0제외한 모든 수
277
                                collection.RemoveAt(i);
278
                            }
279
                            // System.Threading.Thread.Sleep(new TimeSpan(0, 0, 0, 0, 1));
280
                        }
281
                    }
282
                }
283
            }
284
            catch (Exception ex)
285
            {
286
                MessageBox.Show(ex.ToString());
287
            }
288

    
289

    
290
        }
291

    
292
        public override void Loaded()
293
        {
294
            base.Loaded();
295

    
296
            if (!App.IsDesignMode)
297
            {
298
                backgroundWorker = new BackgroundWorker();
299
                backgroundWorker.DoWork += backgroundWorker_DoWork;
300
                backgroundWorker.RunWorkerCompleted += backgroundWorker_RunWorkerCompleted;
301
                backgroundWorker.WorkerReportsProgress = false;
302
                backgroundWorker.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker_ProgressChanged);
303

    
304
                backgroundWorker.RunWorkerAsync();
305
            }
306
        }
307

    
308

    
309
        public override void Closed()
310
        {
311

    
312
            if (backgroundWorker != null)
313
            {
314
                backgroundWorker.DoWork -= backgroundWorker_DoWork;
315
                backgroundWorker.RunWorkerCompleted -= backgroundWorker_RunWorkerCompleted;
316
                backgroundWorker.WorkerReportsProgress = false;
317
                backgroundWorker.ProgressChanged -= new ProgressChangedEventHandler(backgroundWorker_ProgressChanged);
318

    
319
            }
320

    
321
            base.Closed();
322
        }
323

    
324

    
325
        public DelegateCommand DataSaveFileGemBoxCommand { get; private set; }
326

    
327
        public class HeaderMember
328
        {
329
            public string HeaderName { get; set; }
330
            public string Property { get; set; }
331
        }
332
        //public void DataExport<T>(IEnumerable<T> AliveItems)
333
        public void DataExport(object obj)
334
        {
335
            SaveFileDialog saveFileDialog = new SaveFileDialog();
336

    
337
            saveFileDialog.FileName = "Document"; // Default file name
338
            saveFileDialog.DefaultExt = ".txt"; // Default file extension
339
            saveFileDialog.Filter = "Csv documents (.Csv)|*.csv|Excel(2017~2019)Worksheets|*.xlsx"; // Filter files by extension
340

    
341

    
342
            if (saveFileDialog.ShowDialog() == true)
343
            {
344

    
345

    
346
                if (!string.IsNullOrWhiteSpace(saveFileDialog.FileName))
347
                {
348

    
349
                    var extension = new System.IO.FileInfo(saveFileDialog.FileName).Extension;
350

    
351
                    if (extension == ".xlsx" || extension == ".csv")
352
                    {
353

    
354
                        var headers = new List<HeaderMember>
355
                        {
356
                            new HeaderMember{HeaderName = "ServiceID", Property = "ServiceID" },
357
                            new HeaderMember{HeaderName = "ConvertID", Property = "ConvertID" },
358
                            new HeaderMember{HeaderName = "ProjectNumber", Property = "ProjectNumber" },
359
                            new HeaderMember{HeaderName = "ConvertState", Property = "ConvertState" },
360
                            new HeaderMember{HeaderName = "CurrentPageNo", Property = "CurrentPageNo" },
361
                            new HeaderMember{HeaderName = "TotalPage", Property = "TotalPage" },
362
                            new HeaderMember{HeaderName = "OriginfilePath", Property = "OriginfilePath" },
363
                            new HeaderMember{HeaderName = "ConvertPath", Property = "ConvertPath" },
364
                            new HeaderMember{HeaderName = "CreateTime", Property = "CreateTime" },
365
                            new HeaderMember{HeaderName = "Exception", Property = "Exception" },
366
                            new HeaderMember{HeaderName = "ProcessorAffinity", Property = "ProcessorAffinity" },
367
                            new HeaderMember{HeaderName = "ReConverter", Property = "ReConverter" },
368
                            new HeaderMember{HeaderName = "UniqueKey", Property = "UniqueKey" }
369
                        };
370

    
371

    
372

    
373
                        DataExportExcel(saveFileDialog.FileName, "Hello world", FilterConvertSource, headers);
374
                        //_dataExport.DataExportExcel(saveFileDialog.FileName, saveFileDialog.FileName.ToString(),  Projectsource, headers);
375
                        //GemBoxFileSave(obj);
376
                    }
377
                }
378
            }
379
        }
380

    
381

    
382
        public void DataExportExcel<T>(string SaveFile, string SheetName, IEnumerable<T> collections, List<HeaderMember> headerMembers)
383
        {
384

    
385
            try
386
            {
387
                SpreadsheetInfo.SetLicense("EXK0-W4HZ-N518-IMEW");
388
                // SpreadsheetInfo.SetLicense("FREE-LIMITED-KEY");//프리버전은 15줄까지만 가능
389

    
390
                var workbook = new ExcelFile();
391
                var worksheet = workbook.Worksheets.Add(SheetName);
392

    
393
                // IEnumerable<T> collections를 for문
394
                for (int rowNumber = 0; rowNumber < collections.Count(); rowNumber++)//1857  양이 너무 많아서 빨리 엑셀출력 누르면 숫자가 감소됨 차분히 기다리면 숫자 늘어남
395
                {
396
                    // index에 해당하는 row를 가져온다.
397
                    object row = collections.ElementAt(rowNumber);//우왕좌왕하게 모든 프로퍼티 있음 생성자 프로퍼티도 있음
398

    
399
                    //row의 properties를 가져옴.
400
                    var rowPropInfos = row.GetType().GetProperties();//행렬로 보기좋게 프로퍼티 나옴
401

    
402
                    /// 지정된 header에 대해서 프로퍼티에 해당하는 값을 가져와서 cell에 출력
403
                    for (int i = 0; i < headerMembers.Count(); i++)//13
404
                    {
405
                        var prop = rowPropInfos.Where(x => x.Name == headerMembers[i].Property);//prop 0으로 나옴
406
                        if (headerMembers[i].Property == "CreateTime")
407
                        {
408
                            worksheet.Cells[rowNumber + 1, i].Value = prop.First().GetValue(row).ToString();
409
                        }
410
                        else if (prop.Count() > 0)
411
                        {
412
                            worksheet.Cells[rowNumber + 1, i].Value = prop.First().GetValue(row);
413
                        }
414
                    }
415
                }
416

    
417
                int k = 0;
418
                foreach (var HeadInfo in headerMembers)
419
                {
420
                    worksheet.Cells[0, k].Value = HeadInfo.HeaderName;
421
                    k++;
422
                }
423

    
424
                int columnCount = worksheet.CalculateMaxUsedColumns();
425
                for (int i = 0; i < columnCount; i++)
426
                {
427
                    worksheet.Columns[i].AutoFit();
428
                }
429

    
430

    
431

    
432
                var header = new CellStyle();//헤더
433

    
434
                header.FillPattern.SetSolid(SpreadsheetColor.FromArgb(0, 100, 220));
435
                header.Font.Weight = ExcelFont.BoldWeight;
436
                header.HorizontalAlignment = HorizontalAlignmentStyle.Center;
437
                header.VerticalAlignment = VerticalAlignmentStyle.Center;
438
                //worksheet.Cells.GetSubrange("A1:M1").Style = header;
439
                worksheet.Cells.GetSubrangeAbsolute(0, 0, collections.Count(), headerMembers.Count() - 1).Style = header;
440

    
441

    
442

    
443
                var style = new CellStyle();
444
                //style.Borders.SetBorders(MultipleBorders.Right | MultipleBorders.Top | MultipleBorders.Left | MultipleBorders.Bottom, SpreadsheetColor.FromArgb(140, 120, 50), LineStyle.Thick);//바깥쪽 border 두껍게 성공
445
                style.Borders.SetBorders(MultipleBorders.Outside, SpreadsheetColor.FromArgb(140, 120, 50), LineStyle.Thick);//바깥쪽 border 두껍게 성공
446

    
447

    
448

    
449
                style.HorizontalAlignment = HorizontalAlignmentStyle.Center;
450
                style.VerticalAlignment = VerticalAlignmentStyle.Center;
451
                style.Font.Color = SpreadsheetColor.FromArgb(75, 60, 50);//글자 색갈
452
                style.FillPattern.SetSolid(SpreadsheetColor.FromArgb(126, 239, 239));//cell 색갈
453
                style.Font.Name = "맑은 고딕";
454
                style.Font.Size = 9 * 20;
455
                worksheet.Cells.GetSubrangeAbsolute(0, 0, collections.Count(), headerMembers.Count() - 1).Style = style;
456
                //worksheet.Cells.GetSubrange("A1:M1858").Style = style;
457

    
458
                for (int line = 0; line < collections.Count() - 1; line++) //바깥border과 안쪽 얇은 border 같이 쓰면 안됨
459
                {
460
                    //for (int j = 0; j < 14 - 1 - 1; j++)
461
                    for (int j = 0; j < headerMembers.Count() - 1 - 1; j++)
462
                    {
463
                        worksheet.Cells[line + 1, j + 1].Style.Borders.SetBorders(MultipleBorders.Outside, SpreadsheetColor.FromArgb(140, 120, 50), LineStyle.Thin);//안쪽 (1,1) ~ (마지막-1,마지막-1) 가운데 성공
464
                    }
465
                }
466

    
467

    
468
                for (int line = 0; line < collections.Count(); line++) //바깥border과 안쪽 얇은 border 같이 쓰면 안됨
469
                {//Projectsource.Count() = 761개 ( 0 ~ 760 )
470
                    for (int j = 0; j < headerMembers.Count() - 1; j++)
471
                    {
472
                        worksheet.Cells[0, j].Style.Borders.SetBorders(MultipleBorders.Right, SpreadsheetColor.FromArgb(140, 120, 50), LineStyle.Thin);//(0,0) ~ (0,마지막-1) 위 성공
473

    
474
                        worksheet.Cells[collections.Count(), j].Style.Borders.SetBorders(MultipleBorders.Right, SpreadsheetColor.FromArgb(140, 120, 50), LineStyle.Thin);//(마지막,0) ~ (마지막,마지막-1) 아래 성공
475
                    }
476

    
477
                    worksheet.Cells[line, 0].Style.Borders.SetBorders(MultipleBorders.Bottom, SpreadsheetColor.FromArgb(140, 120, 50), LineStyle.Thin);//(0,0) ~ (마지막-1,0) 왼쪽 성공
478

    
479
                    worksheet.Cells[line, headerMembers.Count() - 1].Style.Borders.SetBorders(MultipleBorders.Bottom, SpreadsheetColor.FromArgb(140, 120, 50), LineStyle.Thin);//(0,마지막) ~ (마지막-1,마지막) 오른쪽 성공
480

    
481
                }
482

    
483
                workbook.Save(SaveFile);//파일 열었던 파일로 저장 성공
484
                MessageBox.Show("성공");
485
            }
486

    
487
            catch (Exception ex)
488
            {
489
                Console.WriteLine("예외 발생!! 메세지: {0}", ex.Message);
490
            }
491
        }
492

    
493
    }
494

    
495
    public class SelectedCountItem
496
    {
497
        public string DisplayMember { get; set; }
498
        public int ValueMember { get; set; }
499
    }
500
}
클립보드 이미지 추가 (최대 크기: 500 MB)