프로젝트

일반

사용자정보

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

markus / KCOM / App.xaml.cs @ 8cec2027

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

1

2
using KCOM.Common;
3
using KCOM.Views;
4
using License.Validator;
5
using log4net;
6
using System;
7
using System.ComponentModel;
8
using System.IO;
9
using System.Linq;
10
using System.Net;
11
using System.ServiceModel;
12
using System.Threading.Tasks;
13
using System.Windows;
14
using System.Windows.Input;
15
using System.Windows.Resources;
16

    
17
namespace KCOM
18
{
19
    public class OpenProperties
20
    {
21
        public string DocumentItemID { get; set; }
22
        public bool bPartner { get; set; }
23
        public bool CreateFinalPDFPermission { get; set; }
24
        public bool NewCommentPermission { get; set; }
25
        public string ProjectNO { get; set; }
26
        public string UserID { get; set; }
27
        public int Mode { get; set; }
28
    }
29

    
30
    /// <summary>
31
    /// App.xaml에 대한 상호 작용 논리
32
    /// </summary>
33
    public partial class App : Application
34
    {
35
        public static PageManager.PageStorage PageStorage;
36
        public static string MarkusVersion = "";
37
        public static string BaseAddress;
38
        public static string FileUploadUri;
39
        public static System.ServiceModel.Channels.Binding _binding;
40
        public static EndpointAddress _EndPoint;
41
        public static EndpointAddress _EndPoint_SaveLoad;
42
        public static EndpointAddress _EndPoint_Symbol;
43
        public static string UserName;
44
        public static IKCOM.ViewInfo ViewInfo;
45
        public static string urlHost;
46
        public static string urlPort;
47
        public static string urlHost_DB;
48
        public static string urlPort_DB;
49
        
50
        /// <summary>
51
        /// 현재 활성화된 MarkupInfo의 Id
52
        /// </summary>
53
        public static string Custom_ViewInfoId { get; set; }
54

    
55
        public static bool ParameterMode = false;
56
        public static bool isExternal = false;
57
        public static bool isAuthenticate = false;
58
        public static string AuthenticateToken = null;
59

    
60
        /// <summary>
61
        /// logger
62
        /// </summary>
63
        public static ILog FileLogger = null;
64
        
65
        public static StreamResourceInfo DefaultArrowCursor;
66

    
67
        public static Stream DefaultArrowCursorStream
68
        {
69
            get {
70
                return Application.GetResourceStream(new Uri(@"pack://application:,,,/Resources/Cursor/customCursor2.cur", UriKind.Absolute)).Stream;
71
                //DefaultArrowCursor.Stream.Position = 0;
72
                //return DefaultArrowCursor.Stream;
73
            }
74
        }
75

    
76
        public static kr.co.devdoftech.cloud.FileUpload FileUploader
77
        {
78
            get { return new kr.co.devdoftech.cloud.FileUpload{ Url = FileUploadUri }; }
79

    
80
            private set {; }
81
        }
82

    
83
        /// <summary>
84
        /// VisualStudio Design Time여부
85
        /// </summary>
86
        public static bool IsDesignMode
87
        {
88
            get
89
            {
90
                try
91
                {
92
                    return DesignerProperties.GetIsInDesignMode(new DependencyObject());
93
                }
94
                catch (Exception)
95
                {
96
                    return false;
97
                }
98
            }
99
            private set { }
100
        }
101

    
102
        /// <summary>
103
        /// Application Data Folder
104
        /// </summary>
105
        public static string AppDataFolder
106
        {
107
            get
108
            {
109
                return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "MARKUS");
110
            }
111
        }
112

    
113
        public static IKCOM.KCOM_SystemInfo SystemInfo { get; set; }
114

    
115
        public static OpenProperties ParamDecoding(string DecodingText, System.Text.Encoding oEncoding = null)
116
        {
117
            if (oEncoding == null)
118
                oEncoding = System.Text.Encoding.UTF8;
119

    
120
            byte[] byteArray = Convert.FromBase64String(DecodingText);
121

    
122
            string jsonBack = oEncoding.GetString(byteArray);
123

    
124
            return Newtonsoft.Json.JsonConvert.DeserializeObject<OpenProperties>(jsonBack);
125
        }
126

    
127
        private string versionPath = null;
128
        //public SplashScreen splash = new SplashScreen("splash.png");
129
        public static SplashScreenWindow splashScreen = new SplashScreenWindow();
130

    
131
        public App()
132
        {
133
            Telerik.Windows.Controls.StyleManager.ApplicationTheme = new Telerik.Windows.Controls.VisualStudio2013Theme();
134

    
135
            App.FileLogger = LogManager.GetLogger(typeof(App));
136
        }
137

    
138
        protected override void OnExit(ExitEventArgs e)
139
        {
140
            try
141
            {
142
                if (App.PageStorage != null)
143
                {
144
                    App.PageStorage.Clear();
145
                }
146
            }
147
            catch (Exception)
148
            {
149
            }
150

    
151
            base.OnExit(e);
152
        }
153

    
154
        protected override async void OnStartup(StartupEventArgs e)
155
        {
156
            try
157
            {
158
                DefaultArrowCursor = Application.GetResourceStream(new Uri(@"pack://application:,,,/Resources/Cursor/customCursor2.cur", UriKind.Absolute));
159

    
160
                splashScreen.Show();
161

    
162
                App.Current.DispatcherUnhandledException += Current_DispatcherUnhandledException;
163
                /// up to here
164
                //AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
165

    
166
                #region  //  DNS 체크
167

    
168
                string localdomain = CommonLib.Common.GetConfigString("HOST_DOMAIN", "DOMAIN", "");
169

    
170
                ViewerDataModel.Instance.IsDocumentHistory = Convert.ToBoolean(CommonLib.Common.GetConfigString("COMMON","IsDocumentHistory", "true"));
171

    
172
                var hostEntry = CommonLib.DNSHelper.GetHostEntryTask();
173
                
174
                if (hostEntry == null)
175
                {
176
                    System.Diagnostics.Debug.WriteLine("(hostEntry == null");
177
                    //App.FileLogger.Debug("hostEntry == null");
178
                    isExternal = true;
179
                }
180
                else if (!string.IsNullOrEmpty(localdomain) && !hostEntry.HostName.ToUpper().EndsWith(localdomain.ToUpper()))
181
                {
182
                    // 외부 사용자
183
                     App.FileLogger.Debug(string.Format("You are external user because located out side of given domain({0})\nYour domain is {1}", localdomain, hostEntry.HostName));
184
                    isExternal = true;
185
                }
186
                #endregion
187

    
188

    
189
                if (e.Args.Any())
190
                {
191
                    var result = ParamDecoding(e.Args[0].Replace(@"kcom://", "").Replace(@"/", ""));
192
#if DEBUG
193
                    /*
194
                    ViewerDataModel.Instance.IsDocumentHistory = true;
195
                    result.DocumentItemID = "3712215963";
196
                    result.ProjectNO = "00000";
197
                    result.UserID = "user1";
198
                    doftech
199
                     * humkyung
200
                     P190111_qa03
201
                        P190111_qa04
202
                        P190111_sa03
203
                        P190111_sa04
204
                        P190111_sa05
205
                        user1
206
                    */
207
#endif
208

    
209
                    App.ViewInfo = new IKCOM.ViewInfo
210
                    {
211
                        DocumentItemID = result.DocumentItemID,
212
                        EnsembleID = result.DocumentItemID,
213
                        //DocumentItemID = "10001",
214
                        bPartner = result.bPartner,
215
                        CreateFinalPDFPermission = result.CreateFinalPDFPermission,
216
                        NewCommentPermission = result.NewCommentPermission,
217
                        ProjectNO = result.ProjectNO,
218
                        UserID = result.UserID,
219
                        isAdmin = Convert.ToBoolean(result.Mode)
220
                        //UserID = "H2009115",
221
                        //Mode = result.Mode
222
                    };
223
                    ParameterMode = true; 
224
                } 
225
                else
226
                {
227
                    string[] strArg = Environment.GetCommandLineArgs();
228
                    if (strArg.Length > 1)
229
                    {
230
                        var result = ParamDecoding(strArg[1].Replace(@"kcom://", "").Replace(@"/", ""));
231
                        App.ViewInfo = new IKCOM.ViewInfo
232
                        {
233
                            DocumentItemID = result.DocumentItemID,
234
                            EnsembleID = result.DocumentItemID,
235
                            //DocumentItemID = "10001",
236
                            bPartner = result.bPartner,
237
                            CreateFinalPDFPermission = result.CreateFinalPDFPermission,
238
                            NewCommentPermission = result.NewCommentPermission,
239
                            ProjectNO = result.ProjectNO,
240
                            UserID = result.UserID,
241
                            //UserID = "H2009115",
242
                            //Mode = 0 , 1 , 2
243
                        };
244
                        ParameterMode = true;
245
                    }
246
                    else
247
                    {
248
                        MessageBox.Show("문서 정보가 입력되지 않았습니다.\n프로그램이 종료됩니다.", "안내");
249
                        throw new ArgumentException("문서 정보가 입력되지 않았습니다.");
250
                    }
251
                }
252

    
253
                BaseAddress = CommonLib.Common.GetConfigString("BaseClientAddress", "URL", "", isExternal);
254
                _EndPoint = new EndpointAddress(string.Format("{0}/ServiceDeepView.svc", BaseAddress));
255

    
256
                if (_EndPoint.Uri.Scheme == Uri.UriSchemeHttps)
257
                {
258
                    #region custombinding
259
                    var customBinding = new System.ServiceModel.Channels.CustomBinding()
260
                    {
261
                        OpenTimeout = new TimeSpan(0, 30, 0),
262
                        ReceiveTimeout = new TimeSpan(0, 30, 0),
263
                        CloseTimeout = new TimeSpan(0, 30, 0),
264
                        SendTimeout = new TimeSpan(0, 30, 0),
265
                    };
266

    
267
                    //var messageEncoding = new WcfExtensions.ServiceModel.Channels.CompressionBindingElement();
268
                    //messageEncoding.Level = WcfExtensions.ServiceModel.Channels.CompressionLevel.Maximum;
269

    
270
                    var httpTranport = new System.ServiceModel.Channels.HttpsTransportBindingElement
271
                    {
272
                        MaxBufferPoolSize = Int32.MaxValue,
273
                        MaxBufferSize = Int32.MaxValue,
274
                        MaxReceivedMessageSize = Int32.MaxValue,
275
                        RequestInitializationTimeout = new TimeSpan(0, 30, 0),
276
                        //UseDefaultWebProxy = false,
277
                        //ProxyAddress = new Uri("Http://127.0.0.1:8888")
278
                    };
279

    
280
                    customBinding.CreateBindingElements();
281

    
282
                    var reliableSession = new System.ServiceModel.Channels.ReliableSessionBindingElement();
283

    
284
                    var encoding = new System.ServiceModel.Channels.TextMessageEncodingBindingElement
285
                    {
286
                        MaxReadPoolSize = Int32.MaxValue,
287
                        MaxWritePoolSize = Int32.MaxValue,
288
                        MessageVersion = System.ServiceModel.Channels.MessageVersion.Soap12WSAddressing10,
289
                        WriteEncoding = System.Text.Encoding.UTF8,
290
                        ReaderQuotas = new System.Xml.XmlDictionaryReaderQuotas
291
                        {
292
                            MaxArrayLength = Int32.MaxValue,
293
                            MaxBytesPerRead = Int32.MaxValue,
294
                            MaxDepth = Int32.MaxValue,
295
                            MaxNameTableCharCount = Int32.MaxValue,
296
                            MaxStringContentLength = Int32.MaxValue
297
                        }
298
                    };
299
                    //reliableSession.Ordered = true; // Set other properties as needed
300
                    customBinding.Elements.Add(reliableSession);
301
                    //customBinding.Elements.Add(messageEncoding);
302
                    //customBinding.Elements.Add(encoding);
303
                    customBinding.Elements.Add(httpTranport);
304

    
305
                    _binding = customBinding;
306
                    #endregion
307
                }
308
                else
309
                {
310
                    #region 기본 binding
311
                    BasicHttpBinding basicHttpBinding = new BasicHttpBinding(BasicHttpSecurityMode.None);
312
                    basicHttpBinding.Security = new BasicHttpSecurity { Transport = new HttpTransportSecurity { ClientCredentialType = HttpClientCredentialType.None, ProxyCredentialType = HttpProxyCredentialType.None }, Mode = BasicHttpSecurityMode.None, Message = new BasicHttpMessageSecurity { AlgorithmSuite = System.ServiceModel.Security.SecurityAlgorithmSuite.Basic256, ClientCredentialType = BasicHttpMessageCredentialType.UserName } };
313
                    basicHttpBinding.MaxBufferSize = 2147483647;
314
                    basicHttpBinding.MaxBufferPoolSize = 2147483647;
315
                    basicHttpBinding.MaxReceivedMessageSize = 2147483647;
316
                    basicHttpBinding.OpenTimeout = new TimeSpan(4, 30, 0);
317
                    basicHttpBinding.ReceiveTimeout = new TimeSpan(4, 30, 0);
318
                    basicHttpBinding.CloseTimeout = new TimeSpan(4, 30, 0);
319
                    basicHttpBinding.SendTimeout = new TimeSpan(4, 30, 0);
320
                    basicHttpBinding.TextEncoding = System.Text.Encoding.UTF8;
321
                    basicHttpBinding.TransferMode = TransferMode.Buffered;
322
                    basicHttpBinding.MessageEncoding = WSMessageEncoding.Text;
323
                    basicHttpBinding.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;
324

    
325

    
326
                    //System.ServiceModel.Channels.ReliableSessionBindingElement reliableSession = new System.ServiceModel.Channels.ReliableSessionBindingElement();
327
                    //reliableSession.Ordered = true;
328
                    //reliableSession.MaxRetryCount = 3;
329
                    //basicHttpBinding.CreateBindingElements().Add(reliableSession);
330
                    //basicHttpBinding.ProxyAddress = null;
331
                    //basicHttpBinding.AllowCookies = false;
332
                    //basicHttpBinding.BypassProxyOnLocal = false;
333
                    //basicHttpBinding.UseDefaultWebProxy = false;
334
                    //basicHttpBinding.ProxyAddress = new Uri("Http://localhost:8888");
335

    
336
                    _binding = basicHttpBinding;
337

    
338
                    //System.ServiceModel.Channels.ReliableSessionBindingElement reliableSession = new System.ServiceModel.Channels.ReliableSessionBindingElement();
339
                    //reliableSession.Ordered = true;
340

    
341
                    //System.ServiceModel.Channels.HttpTransportBindingElement httpTransport = new System.ServiceModel.Channels.HttpTransportBindingElement();
342
                    //httpTransport.AuthenticationScheme = System.Net.AuthenticationSchemes.Anonymous;
343
                    //httpTransport.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;
344
                    //System.ServiceModel.Channels.CustomBinding binding = new System.ServiceModel.Channels.CustomBinding(reliableSession, httpTransport);
345
                    #endregion
346
                }
347

    
348
                if (isAuthenticate)
349
                {
350
                    App.AuthenticateToken = Authenticate(BaseAddress);
351
                }
352

    
353
                var UploadAddress = CommonLib.Common.GetConfigString("KCOM_kr_co_devdoftech_cloud_FileUpload", "URL", "");
354

    
355
                if (!string.IsNullOrWhiteSpace(UploadAddress) && !string.IsNullOrWhiteSpace(BaseAddress))
356
                {
357
                    var uploadUri = new UriBuilder(UploadAddress);
358
                    var baseUri = new UriBuilder(BaseAddress);
359

    
360
                    uploadUri.Host = baseUri.Host;
361
                    uploadUri.Port = baseUri.Port;
362

    
363
                    FileUploadUri = uploadUri.ToString();
364
                }
365

    
366
                App.FileLogger.Debug(_EndPoint.Uri);
367

    
368
#if !DEBUG
369
#endif
370
                //var license = new License.Validator.Valid(BaseAddress + "/License");
371

    
372
                //license.ValidateError += License_ValidateError;
373

    
374
                //license.GetLicense("public.xml");
375

    
376
                //if (license.Activate())
377
                //{
378

    
379
                //}
380
                //else
381
                //{
382

    
383
                //}
384

    
385

    
386
                await SplashScreenAsnyc();
387

    
388
                base.OnStartup(e);
389
                System.Windows.Input.Keyboard.AddPreviewKeyDownHandler(this.MainWindow, KeyDownEvent);
390

    
391

    
392
                //System.Windows.Input.Keyboard.AddKeyDownHandler(this.MainWindow, KeyDownEvent);
393
            }
394
            catch (Exception ex)
395
            {
396
                Logger.sendReqLog("OnStartUp",ex.ToString() + " " + ex.InnerException?.ToString(),1);
397
            }
398
            finally
399
            {
400
                await SplashScreenAsnyc();
401
            }
402
        }
403

    
404

    
405
        private string Authenticate(string baseUri)
406
        {
407
            string result = null;
408

    
409
            try
410
            {
411
                Uri uri = new Uri(baseUri);
412
                string baseUrl = uri.Scheme + "://" + uri.Host + (uri.IsDefaultPort ? "" : ":" + uri.Port);
413

    
414
                using (System.Net.WebClient client = new System.Net.WebClient())
415
                {
416
                    client.Headers.Add(HttpRequestHeader.Authorization, "!dsfadsfa@@~");
417
                    var response = client.DownloadString(baseUrl + "/Authenticate");
418

    
419
                    if (response != null)
420
                    {
421
                        result = response;
422
                    }
423
                }
424
            }
425
            catch (Exception)
426
            {
427

    
428
                throw;
429
            }
430

    
431
            return result;
432
        }
433

    
434
        private void License_ValidateError(object sender, ValidateErrorArgs e)
435
        {
436
            e.Received = true;
437

    
438
            Telerik.Windows.Controls.RadWindow.Alert(new Telerik.Windows.Controls.DialogParameters
439
            {
440
                Content = "License Error : " + e.Message,
441
                Owner = splashScreen
442
            });
443
            ///MessageBox.Show(e.Message);
444
            Application.Current.Shutdown();
445
        }
446

    
447
        private void Current_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
448
        {
449
            Logger.sendReqLog("App Error ",e.Exception.ToString() + " " + e.Exception.InnerException?.ToString(), 1);
450
        }
451

    
452
        private void KeyDownEvent(object sender, KeyEventArgs e)
453
        {
454
            //if (e.Key == Key.Escape || e.Key == Key.Delete)
455
            //{
456
                System.Diagnostics.Debug.WriteLine("app key Event");
457
                Common.ViewerDataModel.Instance.SystemMain.KeyEventDownAction(sender, e);
458
            //}
459
        }
460

    
461
        private async Task<bool> SplashScreenAsnyc()
462
        {
463
            int value = 100 / ISplashMessage.SplashMessageCnt;
464

    
465
            for (int i = 1; i < ISplashMessage.SplashMessageCnt; i++)
466
            {
467
                await Task.Delay(1);
468
                await splashScreen.Dispatcher.InvokeAsync(() => splashScreen.Progress = i * value);
469
            }
470

    
471
            //splashScreen.Close();
472

    
473
            return true;
474
        }
475

    
476
        public static void splashString(string text)
477
        {
478
            Task.Factory.StartNew(() =>
479
            {
480
                splashScreen.Dispatcher.Invoke(() => splashScreen.SplashText = text);
481
            }).ConfigureAwait(false);
482
        }
483

    
484

    
485
        /// <summary>
486
        /// log unhandled exception
487
        /// </summary>
488
        /// <author>humkyung</author>
489
        /// <date>2019.05.21</date>
490
        /// <param name="sender"></param>
491
        /// <param name="e"></param>
492
        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
493
        {
494
            try
495
            {
496
                App.FileLogger.Fatal(e.ExceptionObject as Exception);
497
            }
498
            catch (Exception ex)
499
            {
500
                Console.WriteLine(ex.InnerException?.ToString());
501
            }
502
            finally
503
            {
504
#if RELEASE
505
                Environment.Exit(0);
506
#endif
507
            }
508
        }
509

    
510
        private void ErrorLogFileWrite(string Err)
511
        {
512
            App.FileLogger.Debug(Err);
513
        }
514
    }
515
}
클립보드 이미지 추가 (최대 크기: 500 MB)