Statistics
| Branch: | Revision:

root / trunk / Pithos.Client.WPF / App.xaml.cs @ 79f92570

History | View | Annotate | Download (9.9 kB)

1
#region
2
/* -----------------------------------------------------------------------
3
 * <copyright file="App.xaml.cs" company="GRNet">
4
 * 
5
 * Copyright 2011-2012 GRNET S.A. All rights reserved.
6
 *
7
 * Redistribution and use in source and binary forms, with or
8
 * without modification, are permitted provided that the following
9
 * conditions are met:
10
 *
11
 *   1. Redistributions of source code must retain the above
12
 *      copyright notice, this list of conditions and the following
13
 *      disclaimer.
14
 *
15
 *   2. Redistributions in binary form must reproduce the above
16
 *      copyright notice, this list of conditions and the following
17
 *      disclaimer in the documentation and/or other materials
18
 *      provided with the distribution.
19
 *
20
 *
21
 * THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
22
 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
23
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
24
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
25
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
27
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
28
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
29
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
31
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32
 * POSSIBILITY OF SUCH DAMAGE.
33
 *
34
 * The views and conclusions contained in the software and
35
 * documentation are those of the authors and should not be
36
 * interpreted as representing official policies, either expressed
37
 * or implied, of GRNET S.A.
38
 * </copyright>
39
 * -----------------------------------------------------------------------
40
 */
41
#endregion
42
using System;
43
using System.Collections.Generic;
44
using System.IO;
45
using System.Linq;
46
using System.Reflection;
47
using System.Text;
48
using System.Threading;
49
using System.Threading.Tasks;
50
using System.Windows;
51
using Caliburn.Micro;
52
using Pithos.Client.WPF.Properties;
53
using log4net.Appender;
54
using log4net.Repository.Hierarchy;
55

    
56

    
57
namespace Pithos.Client.WPF
58
{
59
    /// <summary>
60
    /// Interaction logic for App.xaml
61
    /// </summary>
62
    public partial class App : Application
63
    {
64
        private static readonly log4net.ILog Log = log4net.LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType );
65

    
66

    
67

    
68
        public App()
69
        {
70

    
71
            InitializeLogging();
72

    
73

    
74
            DispatcherUnhandledException += OnDispatcherUnhandledException;
75
            AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;
76
            TaskScheduler.UnobservedTaskException += OnUnobservedException;
77

    
78
            //_sparkle = new Sparkle(Settings.Default.UpdateUrl);
79
            //_sparkle.updateDetected += OnUpdateDetected;
80
            //_sparkle.ShowDiagnosticWindow = true;
81
            
82
            //Must delay opening the upgrade window
83
            //to avoid Windows Messages sent by the TaskbarIcon
84
            //TaskEx.Delay(5000).ContinueWith(_=>_sparkle.StartLoop(true,true),TaskScheduler.FromCurrentSynchronizationContext());
85

    
86
            //Fix incorrect proxy settings by switching to default proxy, if the proxy server settings is empty
87
            if (Settings.Default.UseManualProxy && String.IsNullOrWhiteSpace(Settings.Default.ProxyServer))
88
            {
89
                Settings.Default.UseManualProxy = false;
90
                Settings.Default.UseDefaultProxy = true;
91
            }
92

    
93
            InitializeComponent();            
94
        }
95

    
96
/*
97
        private void OnUpdateDetected(object sender, UpdateDetectedEventArgs e)
98
        {
99
            Log.InfoFormat("Update Detected {0}",e.LatestVersion.Version);    
100
        }
101
*/
102

    
103
        private static void InitializeLogging()
104
        {
105
            log4net.Config.XmlConfigurator.Configure();
106

    
107
            try
108
            {
109
                var appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
110
                var pithosDataPath= Path.Combine(appDataPath , "GRNET");
111
                if (!Directory.Exists(pithosDataPath))
112
                    Directory.CreateDirectory(pithosDataPath);
113

    
114
                var loggerRepository = (Hierarchy)log4net.LogManager.GetRepository();
115
                
116
                var appenders = loggerRepository.GetAppenders();
117
                var lossyAppender = appenders.OfType<BufferingForwardingAppender>()
118
                    .First(appender => appender.Name == "LossyFileAppender");
119
                var dumpAppender = lossyAppender.Appenders.OfType<RollingFileAppender>().First();                
120
                dumpAppender.File = Path.Combine(pithosDataPath, "errorlog.txt");
121
                dumpAppender.ActivateOptions();
122
            }
123
            catch (Exception exc)
124
            {
125
                Log.Error("Dumpl appender initialization failed",exc);                
126
            }
127
        }
128

    
129
        protected override void OnStartup(StartupEventArgs e)
130
        {
131
            if (!Settings.Default.StartOnSystemStartup && e.Args.Contains("startup"))
132
            {
133
                Shutdown();
134
                return;
135
            }
136

    
137
            //Delay during startup
138
            if (e.Args.Contains("startup"))
139
            {
140
                if (Settings.Default.StartupDelay>TimeSpan.Zero)
141
                    Thread.Sleep(Settings.Default.StartupDelay);
142
            }
143

    
144
            var splashScreen = new SplashScreen("images/logo.png");
145
            splashScreen.Show(true);
146
            
147
            base.OnStartup(e);
148
        }
149

    
150
        private void OnUnobservedException(object sender, UnobservedTaskExceptionEventArgs e)
151
        {            
152
            var messages=new List<UserMessage>();
153
            e.Exception.Handle(exc=>{
154
                messages.Add(new UserMessage
155
                {
156
                    Message = "Unexpected Exception",
157
                    Details = exc.ToString(),
158
                    Severity = Severity.Error
159
                });
160
                return true;
161
            });
162

    
163
            Log.Error("Unobserved Task Exception",e.Exception);
164
            
165
            var message = String.Format(@"{0}\r\n{1}\r\n\r\n{2}", 
166
                WPF.Properties.Resources.Unexpected_Error,
167
                WPF.Properties.Resources.We_Apologize, 
168
                WPF.Properties.Resources.Please_Submit_Error);
169
            ShowMessages("Oops!",message, messages);
170
            e.SetObserved();
171
        }
172

    
173
        private void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
174
        {
175
            Log.Error("Unhandled exception", (Exception)e.ExceptionObject);
176

    
177
            var description = e.IsTerminating
178
                              ? WPF.Properties.Resources.Unexpected_Error_Terminating
179
                              : WPF.Properties.Resources.Unexpected_Error;
180
            var message = String.Format(@"{0}\r\n{1}\r\n\r\n{2}",
181
                description,
182
                WPF.Properties.Resources.We_Apologize,
183
                WPF.Properties.Resources.Please_Submit_Error);
184

    
185

    
186
            var exc = ((Exception) e.ExceptionObject);
187
            var messages = new[]{
188
                                   new UserMessage
189
                                       {
190
                                           Message = exc.Message,
191
                                           Details = exc.ToString(),
192
                                           Severity = Severity.Error
193
                                       }
194
                               };
195

    
196

    
197
            ShowMessages("Oops!", message,messages);
198
        }
199

    
200
        void OnDispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
201
        {
202
            Log.Error("Unhandled Dispatcher exception", e.Exception);
203
            
204
            var messages = new[]{
205
                                   new UserMessage
206
                                       {
207
                                           Message = e.Exception.Message, 
208
                                           Details = e.Exception.ToString(),
209
                                           Severity = Severity.Error
210
                                       }
211
                               };
212
            ShowMessages(WPF.Properties.Resources.Error_Title, 
213
                WPF.Properties.Resources.Unexpected_Error,
214
                messages);
215
            e.Handled=true;
216
        }
217

    
218
        void ShowMessages(string title,string message,IEnumerable<UserMessage> messages )
219
        {
220
            var messageList = messages.ToList();
221
            LogMessages(messageList);
222
            Execute.OnUIThread(()=>{
223
                                       var messageView = new MessageView(messageList)
224
                                                        {
225
                                                            Title = title, 
226
                                                            Message = message
227
                                                        };
228
                                       messageView.ShowDialog();
229
            });
230
        }
231

    
232
        private void LogMessages(IEnumerable<UserMessage> messages)
233
        {
234
            var logMessage = CreateMessage(messages);
235

    
236
            Log.Error(logMessage);
237
        }
238

    
239
        private static string CreateMessage(IEnumerable<UserMessage> messages)
240
        {
241
            var messageBuilder = messages.Aggregate(new StringBuilder("Unexpected Error\r\n"),
242
                                                    (builder, message) =>
243
                                                        {
244
                                                            builder.AppendFormat("\r\n[{0}] {1}\r\n{2}\r\n", message.Severity,
245
                                                                                 message.Message, message.Details);
246
                                                            return builder;
247
                                                        });
248
            var logMessage = messageBuilder.ToString();
249
            return logMessage;
250
        }
251
    }
252

    
253
}