void RefreshThread(object o)
            {
#if !PASSPORT_HEADER_ANALYSIS
                while (true)
                {
                    Thread.Sleep(50 * 60 * 1000);  // Wait 50 Minutes...
                    //Thread.Sleep(1 * 60 * 1000);  // Wait 1 Minute for test...
                    LiveAuthClient client = this.AuthClient;
                    if (client != null)
                    {
                        Traces.Main_TraceEvent(TraceEventType.Information, 1, "Try to refresh token!");
                        bool res = client.ForceRefreshToken(result =>
                        {
                            // Result of refresh token
                            Traces.Main_TraceEvent(TraceEventType.Information, 1, "RefreshToken Result: State: {0}, Status: {1}", result.State, result.Status);

                            // Inform the others that the accesstoken has changed...
                            // INFO: Do we need to synchronize the access to the token!?
                            OnSessionChanged();
                        }
                                                            );
                        if (res == false)
                        {
                            Traces.Main_TraceEvent(TraceEventType.Error, 1, "RefreshToken failed (false)");
                        }
                    }
                }
#endif
            }
 string GetString(RegistryKey key, string name)
 {
     try
     {
         var o = key.GetValue(name);
         if (o is string)
         {
             return((string)o);
         }
         var ic = o as IConvertible;
         if (ic != null)
         {
             try
             {
                 return(ic.ToString(System.Globalization.CultureInfo.InvariantCulture));
             }
             catch (Exception exp)
             {
                 Traces.Main_TraceEvent(TraceEventType.Critical, 1, "GetString.ToString: Error: {0}", NNTPServer.Traces.ExceptionToString(exp));
             }
         }
         if (o != null)
         {
             return(o.ToString());
         }
     }
     catch (Exception exp)
     {
         Traces.Main_TraceEvent(TraceEventType.Critical, 1, "GetString: Error: {0}", NNTPServer.Traces.ExceptionToString(exp));
     }
     return(null);
 }
        static public UICache Load(string fileName)
        {
            try
            {
                if (Directory.Exists(Path.GetDirectoryName(fileName)) == false)
                {
                    return(null);
                }
                if (File.Exists(fileName) == false)
                {
                    return(null);
                }

                var ser = new XmlSerializer(typeof(UICache));
                using (var sr = new StreamReader(fileName))
                {
                    var res = ser.Deserialize(sr) as UICache;
                    return(res);
                }
            }
            catch (Exception exp)
            {
                Traces.Main_TraceEvent(TraceEventType.Critical, 1, "Error while deserializing UICache: {0}\r\n{1}", fileName, NNTPServer.Traces.ExceptionToString(exp));
            }
            return(null);
        }
        public void Save()
        {
            try
            {
                if (IsPortable)
                {
                    SaveToXml(Path.Combine(BasePath, "Settings.xml"));
                    return;
                }

                using (var r = UserAppDataRegistryForWriting)
                {
                    SetBoolean(r, "AutoStart", AutoStart);

                    SetBoolean(r, "AutoMinimize", AutoMinimize);

                    SetBoolean(r, "BindToWorld", BindToWorld);

                    SetEnum(r, "UsePlainTextConverterEnum", UsePlainTextConverter);

                    SetBoolean(r, "PostsAreAlwaysFormatFlowed", PostsAreAlwaysFormatFlowed);

                    SetInt32(r, "Port", Port);

                    SetInt32(r, "MaxPagesOnGet", MaxPagesOnGet);

                    SetString(r, "UserEmail", UserEmail);

                    //SetString(r, "UserName", UserName);

                    SetString(r, "UserGuid", UserGuid == null ? string.Empty : UserGuid.Value.ToString());

#if LIVECONNECT
                    SetString(r, "RefreshToken", RefreshToken);
                    SetString(r, "Scopes", Scopes);
#else
                    SetString(r, "AuthenticationBlob", AuthenticationBlob);
#endif

                    SetInt32(r, "AutoLineWrap", AutoLineWrap);

                    SetString(r, "EncodingForClient", EncodingForClient);

                    SetEnum(r, "InMimeUse", InMimeUse);

                    SetBoolean(r, "DisableLISTGROUP", DisableLISTGROUP);

                    SetInt32(r, "TabAsSpace", TabAsSpace);

                    SetBoolean(r, "DisableArticleCache", DisableArticleCache);

                    SetBoolean(r, "AsyncGroupUpdate", AsyncGroupUpdate);
                }
            }
            catch (Exception exp)
            {
                Traces.Main_TraceEvent(TraceEventType.Critical, 1, "Error saving settings to the registry: {0}", NNTPServer.Traces.ExceptionToString(exp));
            }
        }
        private void StartBridgeAsync(Action <bool, string> onFinishedCallback)
        {
            int port = 119;
            int parsedPort;

            if (int.TryParse(txtPort.Text, out parsedPort))
            {
                port = parsedPort;
            }

            lblInfo.Text       = "Starting server... please wait...";
            cmdStart.IsEnabled = false;

            //System.Threading.ThreadPool.QueueUserWorkItem(delegate(object o)
            var thread = new System.Threading.Thread(
                delegate(object o)
            {
                var t     = o as MainWindow;
                var bRes  = false;
                var error = string.Empty;
                try
                {
                    StartBridgeInternal(t, port);
                    bRes = true;
                }
                catch (Exception exp)
                {
                    Traces.Main_TraceEvent(TraceEventType.Error, 1, "StartBridgeInternal: {0}", NNTPServer.Traces.ExceptionToString(exp));
                    error = exp.Message;
                }
                t.Dispatcher.Invoke(
                    System.Windows.Threading.DispatcherPriority.Normal,
                    new Action(
                        delegate
                {
                    if (bRes)
                    {
                        t.Started = true;
                    }
                    else
                    {
                        t.lblInfo.Text = error;
                        t.ApplySettings();              // for correcting the "LiveId auologin" menu entry
                    }
                    t.cmdStart.IsEnabled = true;
                    if (onFinishedCallback != null)
                    {
                        onFinishedCallback(bRes, error);
                    }
                }));
            });

            thread.IsBackground = true;
            thread.SetApartmentState(System.Threading.ApartmentState.STA);
            thread.Start(this);
        }
 void SetInt32(RegistryKey key, string name, int value)
 {
     try
     {
         key.SetValue(name, value, RegistryValueKind.DWord);
     }
     catch (Exception exp)
     {
         Traces.Main_TraceEvent(TraceEventType.Critical, 1, "SetInt32: Error: {0}", NNTPServer.Traces.ExceptionToString(exp));
     }
 }
        public MainWindow()
        {
            InitializeComponent();

            // Set Icon explizit, because of a Bug in WindowsXP:
            // https://communitybridge.codeplex.com/workitem/11374
            try
            {
                var logo = new BitmapImage();
                logo.BeginInit();
                logo.UriSource =
                    new Uri(
                        "pack://application:,,,/CommunityBridge3;component/Resources/CommunityBridge3.ico");
                logo.EndInit();

                Icon = logo;
            }
            catch (Exception exp)
            {
                Traces.Main_TraceEvent(TraceEventType.Error, 1, NNTPServer.Traces.ExceptionToString(exp));
            }

            if (Icon == null)
            {
                // Fallback fo XP:
                var logo = new BitmapImage();
                logo.BeginInit();
                logo.UriSource =
                    new Uri(
                        "pack://application:,,,/CommunityBridge3;component/Resources/CommunityBridge3.png");
                logo.EndInit();
                Icon = logo;
            }

            this.DataContext = this;

            var v = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;

            Title = Title + " (" + v + ")";

            ApplySettings();

            cmdLoadNewsgroupList.IsEnabled = false;

#if LIVECONNECT
            mnuCreateLiveAutoLogin.Visibility = Visibility.Collapsed;
#endif


            Loaded += MainWindow_Loaded;
        }
 private void OnAuthCompleted(AuthResult result)  // async
 {
     Traces.Main_TraceEvent(TraceEventType.Information, 1, string.Format("AuthResult: {0} - {1} - {2}",
                                                                         result.ErrorCode, result.ErrorDescription, result.AuthorizeCode));
     this.CleanupAuthForm();
     if (result.AuthorizeCode != null)
     {
         Task task = this.AuthClient.ExchangeAuthCodeAsync(result.AuthorizeCode).ContinueWith(t =>
         {
             if (t.Exception != null)
             {
                 return(t.Exception);
             }
             return(null);
         });
         task.Wait();
     }
 }
 private void DoLogin()
 {
     //if (_liveConnectHelper == null)
     {
         _liveConnectHelper = new LiveConnectHelper();
         {
             // Notify about Session changes...
             _liveConnectHelper.SessionChanged += delegate(string accessToken, string refreshToken)
             {
                 Traces.Main_TraceEvent(TraceEventType.Information, 1,
                                        "Authenticated: Session changed! AccessToken: {0}, RefreshToken: {1}",
                                        accessToken, refreshToken);
                 AccessToken  = accessToken;
                 RefreshToken = refreshToken;
             };
         }
     }
     _liveConnectHelper.DoLogin(Win32Wnd);
 }
 bool?GetBoolean(RegistryKey key, string name)
 {
     try
     {
         var iv = GetInt32(key, name);
         if (iv.HasValue)
         {
             if (iv.Value != 0)
             {
                 return(true);
             }
             return(false);
         }
     }
     catch (Exception exp)
     {
         Traces.Main_TraceEvent(TraceEventType.Critical, 1, "GetBoolean: Error: {0}", NNTPServer.Traces.ExceptionToString(exp));
     }
     return(null);
 }
Exemple #11
0
        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            string expMsg = NNTPServer.Traces.ExceptionToString(e.ExceptionObject as Exception);

            if (string.IsNullOrEmpty(expMsg))
            {
                expMsg = "<Unknown Exception>";
            }
            Traces.Main_TraceEvent(System.Diagnostics.TraceEventType.Critical, 1, "UnhandledException: {0}",
                                   expMsg);

            var    exp = e.ExceptionObject as Exception;
            string msg = "<Unknown>";

            if (exp != null)
            {
                msg = exp.Message;
            }

            var dlg = new SendDebugDataWindow();

            dlg.UnhandledExceptionMessage = msg;
            if (dlg.ShowDialog() == true)
            //MessageBoxResult res = MessageBox.Show(
            //  string.Format("UnhandledException occured: {0}\r\n\r\nDo you want to send debug data to the developer?", msg),
            //  "Error", MessageBoxButton.YesNo, MessageBoxImage.Stop);
            //if (res == MessageBoxResult.Yes)
            {
                try
                {
                    var app = (App)Current;
                    app.SendLogs(expMsg, dlg.UsersEMail, dlg.UsersDescription, dlg.UserSendEmail);
                }
                catch { }
                // Terminate...
                //Current.Shutdown(-1);
                Environment.Exit(-1);
            }
        }
 private void mnuDebugWindow_Click(object sender, RoutedEventArgs e)
 {
     try
     {
         if (mnuDebugWindow.IsChecked)
         {
             _debugWindow       = new DebugWindow();
             _debugWindow.Owner = this;
             _debugWindow.Show();
             _debugWindow.Closed += new EventHandler(_debugWindow_Closed);
         }
         else
         {
             _debugWindow.Close();
             _debugWindow = null;
         }
     }
     catch (Exception exp)
     {
         Traces.Main_TraceEvent(TraceEventType.Error, 1, "Error in mnuDebugWindow_click: {0}", NNTPServer.Traces.ExceptionToString(exp));
     }
 }
        void SetEnum(RegistryKey key, string name, Enum value)
        {
            int iVal = 0;

            try
            {
                var ic = value as IConvertible;
                if (ic != null)
                {
                    iVal = ic.ToInt32(System.Globalization.CultureInfo.InvariantCulture);
                }
                else
                {
                    throw new NotSupportedException("Could not convert enum to int");
                }
            }
            catch (Exception exp)
            {
                Traces.Main_TraceEvent(TraceEventType.Critical, 1, "SetEnum {0}: Error: {1}", value, NNTPServer.Traces.ExceptionToString(exp));
                return;
            }
            SetInt32(key, name, iVal);
        }
            private void OnSessionChanged()
            {
                LiveConnectSession session = this.AuthClient.Session;

                //bool isSignedIn = session != null;
                if (session != null)
                {
                    Traces.Main_TraceEvent(TraceEventType.Error, 1, "Session changed: Expires: {0}, AccessToken: {1}", session.Expires.ToString("u", System.Globalization.CultureInfo.InvariantCulture), session.AccessToken);

                    if (_RefreshThread == null)
                    {
                        _RefreshThread = new Thread(RefreshThread);
                        _RefreshThread.IsBackground = true;
                        _RefreshThread.Name         = "RefreshThread";
                        _RefreshThread.Start(null);
                    }

                    var handler = SessionChanged;
                    if (handler != null)
                    {
                        handler(session.AccessToken, session.RefreshToken);
                    }
                }
            }
 public void Save(string filename)
 {
     try
     {
         var path = Path.GetDirectoryName(filename);
         if (Directory.Exists(Path.GetDirectoryName(path)) == false)
         {
             Directory.CreateDirectory(path);
         }
         if (Directory.Exists(path) == false)
         {
             Directory.CreateDirectory(path);
         }
         var ser = new XmlSerializer(typeof(UICache));
         using (var sw = new StreamWriter(filename))
         {
             ser.Serialize(sw, this);
         }
     }
     catch (Exception exp)
     {
         Traces.Main_TraceEvent(TraceEventType.Critical, 1, "Error while serializing UICache: {0}", NNTPServer.Traces.ExceptionToString(exp));
     }
 }
        void Load()
        {
            try
            {
                if (IsPortable)
                {
                    UserSettings u = LoadFromXml(Path.Combine(BasePath, "Settings.xml"));
                    if (u != null)
                    {
                        u.AssignTo(this);
                    }
                    return;
                }

                using (var r = UserAppDataRegistryForReading)
                {
                    if (r == null)
                    {
                        return;
                    }

                    int?   i;
                    bool?  b;
                    string s;

                    b = GetBoolean(r, "AutoStart");
                    if (b.HasValue)
                    {
                        AutoStart = b.Value;
                    }

                    b = GetBoolean(r, "AutoMinimize");
                    if (b.HasValue)
                    {
                        AutoMinimize = b.Value;
                    }

                    b = GetBoolean(r, "BindToWorld");
                    if (b.HasValue)
                    {
                        BindToWorld = b.Value;
                    }

                    UsePlainTextConverters?ptc = GetEnum <UsePlainTextConverters>(r, "UsePlainTextConverterEnum");
                    if (ptc.HasValue)
                    {
                        UsePlainTextConverter = ptc.Value;
                    }
                    else
                    {
                        // Fallback for old setting (until V35)
                        b = GetBoolean(r, "UsePlainTextConverter");
                        if (b.HasValue)
                        {
                            UsePlainTextConverter = UsePlainTextConverters.SendAndReceive;
                        }
                    }

                    b = GetBoolean(r, "PostsAreAlwaysFormatFlowed");
                    if (b.HasValue)
                    {
                        PostsAreAlwaysFormatFlowed = b.Value;
                    }

                    i = GetInt32(r, "Port");
                    if (i.HasValue)
                    {
                        Port = i.Value;
                    }

                    i = GetInt32(r, "MaxPagesOnGet");
                    if (i.HasValue)
                    {
                        MaxPagesOnGet = i.Value;
                    }

                    s         = GetString(r, "UserEmail");
                    UserEmail = s;

                    //s = GetString(r, "UserName");
                    //UserName = s;

                    s = GetString(r, "UserGuid");
                    if (string.IsNullOrEmpty(s) == false)
                    {
                        try
                        {
                            UserGuid = new Guid(s);
                        }
                        catch { }
                    }

#if LIVECONNECT
                    s = GetString(r, "RefreshToken");
                    this.RefreshToken = s;

                    s = GetString(r, "Scopes");
                    if (string.IsNullOrEmpty(s) == false)
                    {
                        this.Scopes = s;
                    }
#else
                    s = GetString(r, "AuthenticationBlob");
                    AuthenticationBlob = s;
#endif

                    i = GetInt32(r, "AutoLineWrap");
                    if (i.HasValue)
                    {
                        AutoLineWrap = i.Value;
                    }

                    s = GetString(r, "EncodingForClient");
                    EncodingForClient = s;

                    MimeContentType?mt = GetEnum <MimeContentType>(r, "InMimeUse");
                    if (mt.HasValue)
                    {
                        InMimeUse = mt.Value;
                    }

                    b = GetBoolean(r, "DisableLISTGROUP");
                    if (b.HasValue)
                    {
                        DisableLISTGROUP = b.Value;
                    }

                    i = GetInt32(r, "TabAsSpace");
                    if (i.HasValue)
                    {
                        TabAsSpace = i.Value;
                    }

                    b = GetBoolean(r, "DisableArticleCache");
                    if (b.HasValue)
                    {
                        DisableArticleCache = b.Value;
                    }

                    b = GetBoolean(r, "AsyncGroupUpdate");
                    if (b.HasValue)
                    {
                        AsyncGroupUpdate = b.Value;
                    }
                }
            }
            catch (Exception exp)
            {
                Traces.Main_TraceEvent(TraceEventType.Critical, 1, "Error loading settings from the registry: {0}", NNTPServer.Traces.ExceptionToString(exp));
            }
        }
Exemple #17
0
        internal void SendLogs(string unhandledException, string userEmail, string userComment, bool userSendEmail)
        {
            string zipFile = null;

            try
            {
                zipFile = _logFile.CreateZipFile();
            }
            catch (Exception exp)
            {
                Traces.Main_TraceEvent(TraceEventType.Error, 1, NNTPServer.Traces.ExceptionToString(exp));
            }

            if (zipFile == null)
            {
                if (string.IsNullOrEmpty(unhandledException) == false)
                {
                    MessageBox.Show("Failed to ZIP the debug data! Please restart the bridge!", "Error", MessageBoxButton.OK, MessageBoxImage.Warning);
                }
                else
                {
                    MessageBox.Show("Failed to ZIP the debug data!", "Error", MessageBoxButton.OK, MessageBoxImage.Warning);
                }
                return;
            }
            try
            {
                string err = UploadDiagnoseData.DoIt(zipFile, unhandledException, userEmail, userComment, userSendEmail);
                if (err == null)
                {
                    if (string.IsNullOrEmpty(unhandledException) == false)
                    {
                        MessageBox.Show("Debug data send... Thank your for helping to improve the bridge or find problems!\r\n\r\nPlease restart the bridge!");
                    }
                    else
                    {
                        MessageBox.Show("Debug data send... Thank your for helping to improve the bridge or find problems!");
                    }
                }
                else
                {
                    if (string.IsNullOrEmpty(unhandledException) == false)
                    {
                        MessageBox.Show("Failed to send debug data:\r\n" + err + "\r\n\r\nPlease restart the bridge!", "Error", MessageBoxButton.OK, MessageBoxImage.Warning);
                    }
                    else
                    {
                        MessageBox.Show("Failed to send debug data:\r\n" + err, "Error", MessageBoxButton.OK, MessageBoxImage.Warning);
                    }
                }
            }
            catch (Exception exp)
            {
                Traces.Main_TraceEvent(TraceEventType.Error, 1, NNTPServer.Traces.ExceptionToString(exp));
            }
            try
            {
                File.Delete(zipFile);
            }
            catch (Exception exp)
            {
                Traces.Main_TraceEvent(TraceEventType.Error, 1, NNTPServer.Traces.ExceptionToString(exp));
            }
        }
 private void OnAuthNavigatedUrl(string url)
 {
     Traces.Main_TraceEvent(TraceEventType.Information, 1, string.Format("AuthNavigatedUrl: {0}", url));
 }
        private static void StartBridgeInternal(MainWindow t, int port)
        {
            string authenticationTicket = null;

#if LIVECONNECT
            Traces.Main_TraceEvent(TraceEventType.Verbose, 1, "LiveConnect: Try authentication");
            t.DoLogin();
            authenticationTicket = t.AccessToken;
            if (string.IsNullOrEmpty(authenticationTicket))
            {
                // Reset the RefreshToken, if the authentication has failed...
                UserSettings.Default.RefreshToken = string.Empty;
                Traces.Main_TraceEvent(TraceEventType.Error, 1, "Could not authenticate with LiveConnect!");
                throw new ApplicationException("Could not authenticate with LiveConnect!");
            }
            Traces.Main_TraceEvent(TraceEventType.Information, 1, "Authenticated: AccessToken: {0}", authenticationTicket);
#else
            // Authenticate with Live Id
            var authenticationData = new AuthenticationInformation();

            Traces.Main_TraceEvent(TraceEventType.Verbose, 1, "LiveId: Try authentication");
            try
            {
                PassportHelper.TryAuthenticate(ref authenticationData, UserSettings.Default.AuthenticationBlob);
            }
            catch
            {
                // Reset the auto login, if the authentication has failed...
                UserSettings.Default.AuthenticationBlob = string.Empty;
                throw;
            }
            Traces.Main_TraceEvent(TraceEventType.Verbose, 1, "LiveId: UserName: {0}, Ticket: {1}", authenticationData.UserName, authenticationData.Ticket);

            if (authenticationData.Ticket == null)
            {
                // Reset the auto login, if the authentication has failed...
                UserSettings.Default.AuthenticationBlob = string.Empty;
                Traces.Main_TraceEvent(TraceEventType.Error, 1, "Could not authenticate with LiveId!");
                throw new ApplicationException("Could not authenticate with LiveId!");
            }
            authenticationTicket = authenticationData.Ticket;
#endif

            string baseUrl = System.Configuration.ConfigurationManager.AppSettings["BaseUrl"];

            var rest = new ForumsRestService.ServiceAccess("tZNt5SSBt1XPiWiueGaAQMnrV4QelLbm7eum1750GI4=", baseUrl);
            rest.AuthenticationTicket = authenticationTicket;
            //rest.GetForums();


            // Create the forums-ServiceProvider
            Traces.Main_TraceEvent(TraceEventType.Verbose, 1, "Create forums service provider");
            //var provider = new MicrosoftForumsServiceProvider(services[i]);
            //System.Diagnostics.Debug.WriteLine(string.Format("{0}: Uri: {1}", services[i], provider.Uri));

            // Assigne the authentication ticket
            //provider.AuthenticationTicket = authenticationTicket;
            //ApplyForumsDisabled(provider);

#if PASSPORT_HEADER_ANALYSIS
            // Register AuthError-Handler
            provider.AuthenticationError += t.provider_AuthenticationError;
#endif

            //t._forumsProviders[i] = provider;

            // Create our DataSource for the forums
            Traces.Main_TraceEvent(TraceEventType.Verbose, 1, "Creating datasource for NNTP server");
            t._forumsDataSource = new DataSourceMsdnRest(rest);
            t._forumsDataSource.UsePlainTextConverter      = UserSettings.Default.UsePlainTextConverter;
            t._forumsDataSource.AutoLineWrap               = UserSettings.Default.AutoLineWrap;
            t._forumsDataSource.HeaderEncoding             = UserSettings.Default.EncodingForClientEncoding;
            t._forumsDataSource.InMimeUseHtml              = (UserSettings.Default.InMimeUse == UserSettings.MimeContentType.TextHtml);
            t._forumsDataSource.PostsAreAlwaysFormatFlowed = UserSettings.Default.PostsAreAlwaysFormatFlowed;
            t._forumsDataSource.TabAsSpace       = UserSettings.Default.TabAsSpace;
            t._forumsDataSource.UseCodeColorizer = UserSettings.Default.UseCodeColorizer;
            t._forumsDataSource.ProgressData    += t._forumsDataSource_ProgressData;

            // Now start the NNTP-Server
            Traces.Main_TraceEvent(TraceEventType.Verbose, 1, "Starting NNTP server");
            t._nntpServer = new NNTPServer.NntpServer(t._forumsDataSource, true);
            t._nntpServer.EncodingSend      = UserSettings.Default.EncodingForClientEncoding;
            t._nntpServer.ListGroupDisabled = UserSettings.Default.DisableLISTGROUP;
            string errorMessage;
            t._nntpServer.Start(port, 64, UserSettings.Default.BindToWorld, out errorMessage);
            if (errorMessage != null)
            {
                throw new ApplicationException(errorMessage);
            }
        }