프로젝트

일반

사용자정보

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

markus / KCOM / App.xaml.cs @ 92c9cab8

이력 | 보기 | 이력해설 | 다운로드 (20.8 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
    /// <summary>
30
    /// App.xaml에 대한 상호 작용 논리
31
    /// </summary>
32
    public partial class App : Application
33
    {
34
        public static PageManager.PageStorage PageStorage;
35
        public static string MarkusVersion = "";
36
        public static string BaseAddress;
37
        public static string FileUploadUri;
38
        public static System.ServiceModel.Channels.Binding _binding;
39
        public static EndpointAddress _EndPoint;
40
        public static EndpointAddress _EndPoint_SaveLoad;
41
        public static EndpointAddress _EndPoint_Symbol;
42
        public static string UserName;
43
        public static IKCOM.ViewInfo ViewInfo;
44
        public static string urlHost;
45
        public static string urlPort;
46
        public static string urlHost_DB;
47
        public static string urlPort_DB;
48
        public static string Custom_ViewInfoId;
49
        public static bool ParameterMode = false;
50
        public static bool isExternal = false;
51
        public static bool isAuthenticate = false;
52
        public static string AuthenticateToken = null;
53

    
54
        /// <summary>
55
        /// logger
56
        /// </summary>
57
        public static ILog FileLogger = null;
58
        
59
        public static StreamResourceInfo DefaultArrowCursor;
60

    
61
        public static Stream DefaultArrowCursorStream
62
        {
63
            get {
64
                return Application.GetResourceStream(new Uri(@"pack://application:,,,/Resources/Cursor/customCursor2.cur", UriKind.Absolute)).Stream;
65
                //DefaultArrowCursor.Stream.Position = 0;
66
                //return DefaultArrowCursor.Stream;
67
            }
68
        }
69

    
70
        public static kr.co.devdoftech.cloud.FileUpload FileUploader
71
        {
72
            get { return new kr.co.devdoftech.cloud.FileUpload{ Url = FileUploadUri }; }
73

    
74
            private set {; }
75
        }
76

    
77
        /// <summary>
78
        /// VisualStudio Design Time여부
79
        /// </summary>
80
        public static bool IsDesignMode
81
        {
82
            get
83
            {
84
                try
85
                {
86
                    return DesignerProperties.GetIsInDesignMode(new DependencyObject());
87
                }
88
                catch (Exception)
89
                {
90
                    return false;
91
                }
92
            }
93
            private set { }
94
        }
95

    
96
        /// <summary>
97
        /// Application Data Folder
98
        /// </summary>
99
        public static string AppDataFolder
100
        {
101
            get
102
            {
103
                return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "MARKUS");
104
            }
105
        }
106

    
107
        public static IKCOM.KCOM_SystemInfo SystemInfo { get; set; }
108

    
109

    
110
        private static OpenProperties ParamDecoding(string DecodingText, System.Text.Encoding oEncoding = null)
111
        {
112
            if (oEncoding == null)
113
                oEncoding = System.Text.Encoding.UTF8;
114

    
115
            byte[] byteArray = Convert.FromBase64String(DecodingText);
116

    
117
            string jsonBack = oEncoding.GetString(byteArray);
118

    
119
            return Newtonsoft.Json.JsonConvert.DeserializeObject<OpenProperties>(jsonBack);
120
        }
121

    
122
        private string versionPath = null;
123
        //public SplashScreen splash = new SplashScreen("splash.png");
124
        public static SplashScreenWindow splashScreen = new SplashScreenWindow();
125

    
126
        public App()
127
        {
128
            Telerik.Windows.Controls.StyleManager.ApplicationTheme = new Telerik.Windows.Controls.VisualStudio2013Theme();
129

    
130
            App.FileLogger = LogManager.GetLogger(typeof(App));
131
        }
132

    
133
        protected override void OnExit(ExitEventArgs e)
134
        {
135
            try
136
            {
137
                if (App.PageStorage != null)
138
                {
139
                    App.PageStorage.Clear();
140
                }
141
            }
142
            catch (Exception)
143
            {
144
            }
145

    
146
            base.OnExit(e);
147
        }
148

    
149
        protected override async void OnStartup(StartupEventArgs e)
150
        {
151
            try
152
            {
153
                DefaultArrowCursor = Application.GetResourceStream(new Uri(@"pack://application:,,,/Resources/Cursor/customCursor2.cur", UriKind.Absolute));
154

    
155
                splashScreen.Show();
156

    
157
                App.Current.DispatcherUnhandledException += Current_DispatcherUnhandledException;
158
                /// up to here
159
                //AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
160

    
161
                #region  //  DNS 체크
162

    
163
                string localdomain = CommonLib.Common.GetConfigString("HOST_DOMAIN", "DOMAIN", "");
164

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

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

    
183

    
184
                if (e.Args.Count() > 0)
185
                {
186
                    var result = ParamDecoding(e.Args[0].Replace(@"kcom://", "").Replace(@"/", ""));
187
                    
188
                    App.ViewInfo = new IKCOM.ViewInfo
189
                    {
190
                        DocumentItemID = result.DocumentItemID,
191
                        EnsembleID = result.DocumentItemID,
192
                        //DocumentItemID = "10001",
193
                        bPartner = result.bPartner,
194
                        CreateFinalPDFPermission = result.CreateFinalPDFPermission,
195
                        NewCommentPermission = result.NewCommentPermission,
196
                        ProjectNO = result.ProjectNO,
197
                        UserID = result.UserID,
198
                        isAdmin = Convert.ToBoolean(result.Mode)
199
                        //UserID = "H2009115",
200
                        //Mode = result.Mode
201
                    };
202
                    ParameterMode = true; 
203
                } 
204
                else
205
                {
206
                    string[] strArg = Environment.GetCommandLineArgs();
207
                    if (strArg.Length > 1)
208
                    {
209
                        var result = ParamDecoding(strArg[1].Replace(@"kcom://", "").Replace(@"/", ""));
210
                        App.ViewInfo = new IKCOM.ViewInfo
211
                        {
212
                            DocumentItemID = result.DocumentItemID,
213
                            EnsembleID = result.DocumentItemID,
214
                            //DocumentItemID = "10001",
215
                            bPartner = result.bPartner,
216
                            CreateFinalPDFPermission = result.CreateFinalPDFPermission,
217
                            NewCommentPermission = result.NewCommentPermission,
218
                            ProjectNO = result.ProjectNO,
219
                            UserID = result.UserID,
220
                            //UserID = "H2009115",
221
                            //Mode = 0 , 1 , 2
222
                        };
223
                        ParameterMode = true;
224
                    }
225
                    else
226
                    {
227
                        MessageBox.Show("문서 정보가 입력되지 않았습니다.\n프로그램이 종료됩니다.", "안내");
228
                        throw new ArgumentException("문서 정보가 입력되지 않았습니다.");
229
                    }
230
                }
231

    
232
                //App.ViewInfo.CreateFinalPDFPermission = false;
233
                //App.ViewInfo.NewCommentPermission = false;
234
                //GetQueryStringParameters();
235
                //_binding = new WSHttpBinding();
236
                //_binding.Security = new WSHttpSecurity { Transport = new HttpTransportSecurity { ClientCredentialType = HttpClientCredentialType.None }, Mode = SecurityMode.Transport };
237
                //_binding.MaxReceivedMessageSize = 2147483647;
238
                //_binding.OpenTimeout = new TimeSpan(0, 1, 0);
239
                //_binding.ReceiveTimeout = new TimeSpan(0, 10, 0);
240
                //_binding.CloseTimeout = new TimeSpan(0, 5, 0);
241
                //_binding.SendTimeout = new TimeSpan(0, 5, 0);
242
#if BASIC_BINDING
243

    
244
                #region 기본 binding
245
                BasicHttpBinding basicHttpBinding = new BasicHttpBinding(BasicHttpSecurityMode.None);
246
                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 } };
247
                basicHttpBinding.MaxBufferSize = 2147483647;
248
                basicHttpBinding.MaxBufferPoolSize = 2147483647;
249
                basicHttpBinding.MaxReceivedMessageSize = 2147483647;
250
                basicHttpBinding.OpenTimeout = new TimeSpan(4, 30, 0);
251
                basicHttpBinding.ReceiveTimeout = new TimeSpan(4, 30, 0);
252
                basicHttpBinding.CloseTimeout = new TimeSpan(4, 30, 0);
253
                basicHttpBinding.SendTimeout = new TimeSpan(4, 30, 0);
254
                basicHttpBinding.TextEncoding = System.Text.Encoding.UTF8;
255
                basicHttpBinding.TransferMode = TransferMode.Buffered;
256
                basicHttpBinding.MessageEncoding = WSMessageEncoding.Text;
257
                basicHttpBinding.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;
258

    
259

    
260
                System.ServiceModel.Channels.ReliableSessionBindingElement reliableSession = new System.ServiceModel.Channels.ReliableSessionBindingElement();
261
                reliableSession.Ordered = true;
262
                reliableSession.MaxRetryCount = 3;
263
                basicHttpBinding.CreateBindingElements().Add(reliableSession);
264
                //basicHttpBinding.ProxyAddress = null;
265
                //basicHttpBinding.AllowCookies = false;
266
                //basicHttpBinding.BypassProxyOnLocal = false;
267
                //basicHttpBinding.UseDefaultWebProxy = false;
268
                //basicHttpBinding.ProxyAddress = new Uri("Http://localhost:8888");
269

    
270
                _binding = basicHttpBinding;
271

    
272
                //System.ServiceModel.Channels.ReliableSessionBindingElement reliableSession = new System.ServiceModel.Channels.ReliableSessionBindingElement();
273
                //reliableSession.Ordered = true;
274

    
275
                //System.ServiceModel.Channels.HttpTransportBindingElement httpTransport = new System.ServiceModel.Channels.HttpTransportBindingElement();
276
                //httpTransport.AuthenticationScheme = System.Net.AuthenticationSchemes.Anonymous;
277
                //httpTransport.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;
278
                //System.ServiceModel.Channels.CustomBinding binding = new System.ServiceModel.Channels.CustomBinding(reliableSession, httpTransport);
279
                #endregion
280
#elif CUSTOM_BINDING
281
                #region custombinding
282
                var customBinding = new System.ServiceModel.Channels.CustomBinding()
283
                {
284
                    OpenTimeout = new TimeSpan(0, 15, 0),
285
                    ReceiveTimeout = new TimeSpan(0, 15, 0),
286
                    CloseTimeout = new TimeSpan(0, 15, 0),
287
                    SendTimeout = new TimeSpan(0, 15, 0),
288
                };
289

    
290
                var messageEncoding = new WcfExtensions.ServiceModel.Channels.CompressionBindingElement();
291
                messageEncoding.Level = WcfExtensions.ServiceModel.Channels.CompressionLevel.Fast;
292

    
293
                var httpTranport = new System.ServiceModel.Channels.HttpTransportBindingElement
294
                {
295
                    MaxBufferPoolSize = Int32.MaxValue,
296
                    MaxBufferSize = Int32.MaxValue,
297
                    MaxReceivedMessageSize = Int32.MaxValue,
298
                    RequestInitializationTimeout = new TimeSpan(0, 10, 0),
299
                    //UseDefaultWebProxy = false,
300
                    //ProxyAddress = new Uri("Http://127.0.0.1:8888")
301
                };
302

    
303

    
304
                customBinding.CreateBindingElements();
305
                customBinding.Elements.Add(messageEncoding);
306
                customBinding.Elements.Add(httpTranport);
307

    
308

    
309
                _binding = customBinding;
310
                #endregion
311

    
312
#else
313

    
314
                #region 기본 binding
315
                BasicHttpBinding basicHttpBinding = new BasicHttpBinding(BasicHttpSecurityMode.None);
316
                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 } };
317
                basicHttpBinding.MaxBufferSize = 2147483647;
318
                basicHttpBinding.MaxBufferPoolSize = 2147483647;
319
                basicHttpBinding.MaxReceivedMessageSize = 2147483647;
320
                basicHttpBinding.OpenTimeout = new TimeSpan(4, 30, 0);
321
                basicHttpBinding.ReceiveTimeout = new TimeSpan(4, 30, 0);
322
                basicHttpBinding.CloseTimeout = new TimeSpan(4, 30, 0);
323
                basicHttpBinding.SendTimeout = new TimeSpan(4, 30, 0);
324
                basicHttpBinding.TextEncoding = System.Text.Encoding.UTF8;
325
                basicHttpBinding.TransferMode = TransferMode.Buffered;
326
                basicHttpBinding.MessageEncoding = WSMessageEncoding.Text;
327
                basicHttpBinding.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;
328

    
329

    
330
                System.ServiceModel.Channels.ReliableSessionBindingElement reliableSession = new System.ServiceModel.Channels.ReliableSessionBindingElement();
331
                reliableSession.Ordered = true;
332
                reliableSession.MaxRetryCount = 3;
333
                basicHttpBinding.CreateBindingElements().Add(reliableSession);
334

    
335
                _binding = basicHttpBinding;
336
  #endregion
337
#endif
338

    
339
                //Support.SetLicense();
340

    
341
#if DEBUG
342
                //sBaseServiceURL = CommonLib.Common.GetConfigString("BaseClientAddress", "URL", "", isExternal);
343
                System.Diagnostics.Debug.WriteLine("sBaseServiceURL");
344
                BaseAddress = CommonLib.Common.GetConfigString("BaseClientAddress", "URL", "", isExternal);
345
#else
346
                BaseAddress = CommonLib.Common.GetConfigString("BaseClientAddress", "URL", "", isExternal);
347
#endif
348

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

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

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

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

    
364
                    FileUploadUri = uploadUri.ToString();
365
                }
366
#if BASIC_BINDING
367
                _EndPoint = new EndpointAddress(string.Format("{0}/ServiceDeepView.svc", BaseAddress));
368
#elif CUSTOM_BINDING
369
                _EndPoint = new EndpointAddress(string.Format("{0}/ServiceDeepView.svc/gzip", BaseAddress));
370
#else
371
                _EndPoint = new EndpointAddress(string.Format("{0}/ServiceDeepView.svc", BaseAddress));
372
#endif
373

    
374
                App.FileLogger.Debug(_EndPoint.Uri);
375

    
376
#if !DEBUG
377
#endif
378
                //var license = new License.Validator.Valid(BaseAddress + "/License");
379

    
380
                //license.ValidateError += License_ValidateError;
381

    
382
                //license.GetLicense("public.xml");
383

    
384
                //if (license.Activate())
385
                //{
386

    
387
                //}
388
                //else
389
                //{
390

    
391
                //}
392

    
393

    
394
                await SplashScreenAsnyc();
395

    
396
                base.OnStartup(e);
397
                System.Windows.Input.Keyboard.AddPreviewKeyDownHandler(this.MainWindow, KeyDownEvent);
398

    
399

    
400
                //System.Windows.Input.Keyboard.AddKeyDownHandler(this.MainWindow, KeyDownEvent);
401
            }
402
            catch (Exception ex)
403
            {
404
                Logger.sendReqLog("OnStartUp",ex.ToString() + " " + ex.InnerException?.ToString(),1);
405
            }
406
            finally
407
            {
408
                await SplashScreenAsnyc();
409
            }
410
        }
411
        private string Authenticate(string baseUri)
412
        {
413
            string result = null;
414

    
415
            try
416
            {
417
                Uri uri = new Uri(baseUri);
418
                string baseUrl = uri.Scheme + "://" + uri.Host + (uri.IsDefaultPort ? "" : ":" + uri.Port);
419

    
420
                using (System.Net.WebClient client = new System.Net.WebClient())
421
                {
422
                    client.Headers.Add(HttpRequestHeader.Authorization, "!dsfadsfa@@~");
423
                    var response = client.DownloadString(baseUrl + "/Authenticate");
424

    
425
                    if (response != null)
426
                    {
427
                        result = response;
428
                    }
429
                }
430
            }
431
            catch (Exception)
432
            {
433

    
434
                throw;
435
            }
436

    
437
            return result;
438
        }
439

    
440
        private void License_ValidateError(object sender, ValidateErrorArgs e)
441
        {
442
            e.Received = true;
443

    
444
            Telerik.Windows.Controls.RadWindow.Alert(new Telerik.Windows.Controls.DialogParameters
445
            {
446
                Content = "License Error : " + e.Message,
447
                Owner = splashScreen
448
            });
449
            ///MessageBox.Show(e.Message);
450
            Application.Current.Shutdown();
451
        }
452

    
453
        private void Current_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
454
        {
455
            Logger.sendReqLog("App Error ",e.Exception.ToString() + " " + e.Exception.InnerException?.ToString(), 1);
456
        }
457

    
458
        private void KeyDownEvent(object sender, KeyEventArgs e)
459
        {
460
            //if (e.Key == Key.Escape || e.Key == Key.Delete)
461
            //{
462
                System.Diagnostics.Debug.WriteLine("app key Event");
463
                Common.ViewerDataModel.Instance.SystemMain.KeyEventDownAction(sender, e);
464
            //}
465
        }
466

    
467
        private async Task<bool> SplashScreenAsnyc()
468
        {
469
            int value = 100 / ISplashMessage.SplashMessageCnt;
470

    
471
            for (int i = 1; i < ISplashMessage.SplashMessageCnt; i++)
472
            {
473
                await Task.Delay(3);
474
                await splashScreen.Dispatcher.InvokeAsync(() => splashScreen.Progress = i * value);
475
            }
476

    
477
            //splashScreen.Close();
478

    
479
            return true;
480
        }
481

    
482
        public static void splashString(string text)
483
        {
484
            Task.Factory.StartNew(() =>
485
            {
486
                splashScreen.Dispatcher.Invoke(() => splashScreen.SplashText = text);
487
            }).ConfigureAwait(false);
488
        }
489

    
490

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

    
516
        private void ErrorLogFileWrite(string Err)
517
        {
518
            App.FileLogger.Debug(Err);
519
        }
520
    }
521
}
클립보드 이미지 추가 (최대 크기: 500 MB)