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
            }
 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)
     {
         AppInsights.TrackException(exp, true);
         Traces.Main_TraceEvent(TraceEventType.Critical, 1, "Error while serializing UICache: {0}", NNTPServer.Traces.ExceptionToString(exp));
     }
 }
 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)
            {
                AppInsights.TrackException(exp, true);
                Traces.Main_TraceEvent(TraceEventType.Critical, 1, "Error while deserializing UICache: {0}\r\n{1}", fileName, NNTPServer.Traces.ExceptionToString(exp));
            }
            return(null);
        }
 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:,,,/CommunityForumsNNTPServer;component/Resources/CommunityForumsNNTPServer.ico");
                logo.EndInit();

                Icon = logo;
            }
            catch (Exception exp)
            {
                AppInsights.TrackException(exp, true);
                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:,,,/CommunityForumsNNTPServer;component/Resources/CommunityForumsNNTPServer.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;
        }
Example #7
0
        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            var exp = e.ExceptionObject as Exception;

            if (exp == null)
            {
                exp = new ApplicationException("<Unknown Exception>");
            }
            AppInsights.TrackException(exp);
            string expMsg = NNTPServer.Traces.ExceptionToString(exp);

            Traces.Main_TraceEvent(System.Diagnostics.TraceEventType.Critical, 1, "UnhandledException: {0}",
                                   expMsg);

            MessageBox.Show(string.Format("UnhandledException occured: {0}", NNTPServer.Traces.ExceptionToString(e.ExceptionObject as Exception)));
        }
 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);
 }
        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 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)
     {
         AppInsights.TrackException(exp, true);
         Traces.Main_TraceEvent(TraceEventType.Error, 1, "Error in mnuDebugWindow_click: {0}", NNTPServer.Traces.ExceptionToString(exp));
     }
 }
            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);
                    }
                }
            }
        void Load()
        {
            try
            {
                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, "DetailedErrorResponse");
                    //if (b.HasValue)
                    //    DetailedErrorResponse = 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, "ListPageSize");
                    if (i.HasValue)
                    {
                        ListPageSize = i.Value;
                    }

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

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

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

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

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

                    s = GetString(r, "ClientId");
                    if (string.IsNullOrEmpty(s) == false)
                    {
                        this.ClientId = 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;

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

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

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

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

                    ArticleConverter.UserDefinedTagCollection.PreCompileXmlSerializer();
                    s = GetString(r, "UserDefinedTags");
                    if (string.IsNullOrEmpty(s) == false)
                    {
                        var u = ArticleConverter.UserDefinedTagCollection.FromString(s);
                        if (u != null)
                        {
                            _userDefinedTags = u;
                        }
                    }

                    ArticleConverter.UserMappingCollection.PreCompileXmlSerializer();
                    s = GetString(r, "UserMappings");
                    if (string.IsNullOrEmpty(s) == false)
                    {
                        var u = ArticleConverter.UserMappingCollection.FromString(s);
                        if (u != null)
                        {
                            _userMappings = u;
                        }
                    }

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

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

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

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

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

                    AppInsightsLevel?ail = GetEnum <AppInsightsLevel>(r, "UseAppInsights");
                    if (ail.HasValue)
                    {
                        UseAppInsights = ail.Value;
                    }

                    s = GetString(r, "AppAccountId");
                    if (string.IsNullOrEmpty(s))
                    {
                        // Create a unique id for this installation
                        s = Guid.NewGuid().ToString();
                        try
                        {
                            using (var rw = UserAppDataRegistryForWriting)
                            {
                                SetString(rw, "AppAccountId", s);
                            }
                        }
                        catch { }
                    }
                    AppAccountId = s;
                }
            }
            catch (Exception exp)
            {
                Traces.Main_TraceEvent(TraceEventType.Critical, 1, "Error loading settings from the registry: {0}", NNTPServer.Traces.ExceptionToString(exp));
            }
        }
        public void Save()
        {
            try
            {
                using (var r = UserAppDataRegistryForWriting)
                {
                    SetBoolean(r, "AutoStart", AutoStart);

                    SetBoolean(r, "AutoMinimize", AutoMinimize);

                    //SetBoolean(r, "DetailedErrorResponse", DetailedErrorResponse);

                    SetBoolean(r, "BindToWorld", BindToWorld);

                    SetEnum(r, "UsePlainTextConverterEnum", UsePlainTextConverter);

                    SetBoolean(r, "PostsAreAlwaysFormatFlowed", PostsAreAlwaysFormatFlowed);

                    SetInt32(r, "Port", Port);

                    SetInt32(r, "ListPageSize", ListPageSize);

                    SetInt32(r, "ArticlePageSize", ArticlePageSize);

                    SetString(r, "DomainName", DomainName);

                    SetString(r, "UserEmail", UserEmail);

                    SetString(r, "UserName", UserName);

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

                    SetInt32(r, "AutoLineWrap", AutoLineWrap);

                    SetString(r, "EncodingForClient", EncodingForClient);

                    SetString(r, "UserGuid", UserGuid.ToString());

                    SetEnum(r, "InMimeUse", InMimeUse);

                    SetBoolean(r, "UseAnswersForums", UseAnswersForums);

                    SetBoolean(r, "UseSocialForums", UseSocialForums);

                    SetString(r, "UserDefinedTags", UserDefinedTags.GetString());

                    SetString(r, "UserMappings", UserMappings.GetString());

                    SetBoolean(r, "DisableUserAgentInfo", DisableUserAgentInfo);

                    SetBoolean(r, "DisableLISTGROUP", DisableLISTGROUP);

                    SetBoolean(r, "ShowUserNamePostfix", ShowUserNamePostfix);

                    SetInt32(r, "TabAsSpace", TabAsSpace);

                    SetBoolean(r, "AddHistoryToArticle", AddHistoryToArticle);

                    SetEnum(r, "UseAppInsights", UseAppInsights);
                }
            }
            catch (Exception exp)
            {
                Traces.Main_TraceEvent(TraceEventType.Critical, 1, "Error saving settings to the registry: {0}", NNTPServer.Traces.ExceptionToString(exp));
            }
        }
        private static void StartBridgeInternal(MainWindow t, int port, string domainName)
        {
            //var services = new[] { "social", "answers" };
            var services = new[] { "social" };

            //var serviceModel = System.Configuration.ConfigurationManager.GetSection("system.serviceModel");

            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

            t._forumsProviders = new MicrosoftForumsServiceProvider[services.Length];
            for (var i = 0; i < services.Length; i++)
            {
                // Create the forums-ServiceProvider
                Traces.Main_TraceEvent(TraceEventType.Verbose, 1, "Create forums service provider: {0}", services[i]);
                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 ForumDataSource(t._forumsProviders, domainName);
            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.UserDefinedTags            = UserSettings.Default.UserDefinedTags;
            t._forumsDataSource.ShowUserNamePostfix        = UserSettings.Default.ShowUserNamePostfix;
            t._forumsDataSource.PostsAreAlwaysFormatFlowed = UserSettings.Default.PostsAreAlwaysFormatFlowed;
            t._forumsDataSource.TabAsSpace          = UserSettings.Default.TabAsSpace;
            t._forumsDataSource.UseCodeColorizer    = UserSettings.Default.UseCodeColorizer;
            t._forumsDataSource.AddHistoryToArticle = UserSettings.Default.AddHistoryToArticle;

            // 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;
            //t._nntpServer.DetailedErrorResponse = detailedErrorResponse;
            string errorMessage;
            t._nntpServer.Start(port, 64, UserSettings.Default.BindToWorld, out errorMessage);
            if (errorMessage != null)
            {
                throw new ApplicationException(errorMessage);
            }
        }
 private void OnAuthNavigatedUrl(string url)
 {
     Traces.Main_TraceEvent(TraceEventType.Information, 1, string.Format("AuthNavigatedUrl: {0}", url));
 }