Statistics
| Branch: | Revision:

root / trunk / Pithos.Client.WPF / App.xaml.cs @ 46426dbd

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.Drawing;
45
using System.IO;
46
using System.Linq;
47
using System.Reflection;
48
using System.Text;
49
using System.Threading;
50
using System.Threading.Tasks;
51
using System.Windows;
52
using System.Windows.Media;
53
using System.Windows.Media.Imaging;
54
using AppLimit.NetSparkle;
55
using Caliburn.Micro;
56
using Pithos.Client.WPF.Properties;
57
using log4net.Appender;
58
using log4net.Repository.Hierarchy;
59

    
60

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

    
70
        private Sparkle _sparkle;
71

    
72

    
73
        public App()
74
        {
75

    
76
            InitializeLogging();
77

    
78

    
79
            DispatcherUnhandledException += OnDispatcherUnhandledException;
80
            AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;
81
            TaskScheduler.UnobservedTaskException += OnUnobservedException;
82

    
83
            _sparkle = new Sparkle(Settings.Default.UpdateUrl);
84
            _sparkle.updateDetected += OnUpdateDetected;
85
            _sparkle.ShowDiagnosticWindow = true;
86
            
87
//            _sparkle.ApplicationIcon=Image.
88
            _sparkle.StartLoop(true,true);
89

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

    
97
            InitializeComponent();            
98
        }
99

    
100
        private void OnUpdateDetected(object sender, UpdateDetectedEventArgs e)
101
        {
102
            Log.InfoFormat("Update Detected {0}",e.LatestVersion.Version);    
103
        }
104

    
105
        private static void InitializeLogging()
106
        {
107
            log4net.Config.XmlConfigurator.Configure();
108

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

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

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

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

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

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

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

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

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

    
187

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

    
198

    
199
            ShowMessages("Oops!", message,messages);
200
        }
201

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

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

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

    
238
            Log.Error(logMessage);
239
        }
240

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

    
255
}