using BeWoLauncher.Components; using BeWoLauncher.Logic.Controller; using BeWoLauncher.Logic.Utils; using BeWoLauncher.Models; using BeWoLauncher.ServiceProxy; using BeWoLauncher.WindowImp; using BS.SharedLauncher.Enums; using BS.SharedLauncher.Information; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.IO; using System.Linq; using System.Net; using System.Net.Security; using System.Reflection; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Navigation; using System.Windows.Threading; namespace BeWoLauncher.View { /// /// Interaktionslogik für LoginView.xaml /// public partial class LoginView : UserControl, INotifyPropertyChanged { public event EventHandler LoginSuccessful; public event PropertyChangedEventHandler PropertyChanged; private static String PUB_KEY_X3 = "3082010A02820101009CD30CF05AE52E47B7725D3783B3686330EAD735261925E1BDBE35F170922FB7B84B4105ABA99E350858ECB12AC468870BA3E375E4E6F3A76271BA7981601FD7919A9FF3D0786771C8690E9591CFFEE699E9603C48CC7ECA4D7712249D471B5AEBB9EC1E37001C9CAC7BA705EACE4AEBBD41E53698B9CBFD6D3C9668DF232A42900C867467C87FA59AB8526114133F65E98287CBDBFA0E56F68689F3853F9786AFB0DC1AEF6B0D95167DC42BA065B299043675806BAC4AF31B9049782FA2964F2A20252904C674C0D031CD8F31389516BAA833B843F1B11FC3307FA27931133D2D36F8E3FCF2336AB93931C5AFC48D0D1D641633AAFA8429B6D40BC0D87DC3930203010001"; private static String PUB_KEY_R3 = "3082010A0282010100BB021528CCF6A094D30F12EC8D5592C3F882F199A67A4288A75D26AAB52BB9C54CB1AF8E6BF975C8A3D70F4794145535578C9EA8A23919F5823C42A94E6EF53BC32EDB8DC0B05CF35938E7EDCF69F05A0B1BBEC094242587FA3771B313E71CACE19BEFDBE43B45524596A9C153CE34C852EEB5AEED8FDE6070E2A554ABB66D0E97A540346B2BD3BC66EB66347CFA6B8B8F572999F830175DBA726FFB81C5ADD286583D17C7E709BBF12BF786DCC1DA715DD446E3CCAD25C188BC60677566B3F118F7A25CE653FF3A88B647A5FF1318EA9809773F9D53F9CF01E5F5A6701714AF63A4FF99B3939DDC53A706FE48851DA169AE2575BB13CC5203F5ED51A18BDB150203010001"; private static String PUB_KEY_E1 = "04245C2DA22AFD1C4BA65D97732731ACB2A06962EF65E8A6B0F0AC4B9FFF1C0B700FD3982F4DFC0F009B37F074055732972E05EF2A4325A3FB6E342713F64F7E69D302995EEB244792C1249BE6B1218FC12481FC68CC1F69BA58F51922F774C616"; private readonly Stack _ModalPopUpControls; private string _ProfilesFilePath; private string _ConfigFilePath; private bool isNet45OrNewer = false; private bool pwvViewOffen; private double lineYCoordTo; private double lineYCoordFrom; private double heightFrom; private double heightTo; private string GETSERVER_URL = "https://support.bewoplaner.de/api/getserver.php?k={0}&t=1"; private string GETSTATUSMESSAGE_URL = "https://support.bewoplaner.de/api/getstate.php?k={0}&t=1&v={1}"; private string GETNETMESSAGE_URL = "https://support.bewoplaner.de/api/getxmlstate.php?k={0}&t=1"; public LoginView() { InitializeComponent(); _ModalPopUpControls = new Stack(); ViewController.LaunchBehavior.UninstallMode = false; DoTooMuchInitStuffIDontHaveANameForThisMethod(); } public List ProfileList { get; set; } public double HeightFrom { get { return heightFrom; } set { heightFrom = value; OnPropertyChanged("HeightFrom"); } } public double HeightTo { get { return heightTo; } set { heightTo = value; OnPropertyChanged("HeightTo"); } } public double LineYCoordFrom { get { return lineYCoordFrom; } set { lineYCoordFrom = value; OnPropertyChanged("LineYCoordFrom"); } } public double LineYCoordTo { get { return lineYCoordTo; } set { lineYCoordTo = value; OnPropertyChanged("LineYCoordTo"); } } private void button_login_Click(object sender, RoutedEventArgs e) { if (!String.IsNullOrEmpty(SessionInformation.Connection.ProxyName)) { var webProxy = WebProxy.GetDefaultProxy(); webProxy.UseDefaultCredentials = true; System.Net.WebRequest.DefaultWebProxy = new WebProxy(SessionInformation.Connection.ProxyName, true); if (String.IsNullOrEmpty(SessionInformation.Connection.ProxyUsername)) { WebRequest.DefaultWebProxy.Credentials = CredentialCache.DefaultNetworkCredentials; } else { WebRequest.DefaultWebProxy.Credentials = new NetworkCredential(SessionInformation.Connection.ProxyUsername, SessionInformation.Connection.ProxyPassword); } } if (ProfileList.Count == 0 || profileSelectionComboBox.SelectedItem == null) { MessageBox.Show( "Es wurde kein gültiges Profil gefunden. Bitte erstellen Sie zunächst ein Profil. Klicken Sie dazu auf 'Erweitert' und anschließend auf den Button 'Profile bearbeiten'", "Ungültiges Profil", MessageBoxButton.OK, MessageBoxImage.Warning); } else { var profile = profileSelectionComboBox.SelectedItem as ConnectionProfile; isNet45OrNewer = IsNet45OrNewer(); if (!isNet45OrNewer) { if (!CheckStatusMessage(profile, String.Format(GETNETMESSAGE_URL, profile.Tenant, LauncherApp.Version))) { return; } } #if DEBUG if (!CheckStatusMessage(profile, String.Format(GETSTATUSMESSAGE_URL, profile.Tenant, LauncherApp.ShortVersion))) { return; } #else if (!CheckStatusMessage(profile, String.Format(GETSTATUSMESSAGE_URL, profile.Tenant, LauncherApp.ShortVersion))) { return; } #endif ChangeServerAndTenant(profile); //var lWaitLayer = new WaitLayer2(); //grid_root.Children.Add(lWaitLayer); ViewController.StartWaiting(); SessionInformation.Login.Username = TextBox_Username.Text; SessionInformation.Login.Password = PasswordBox_Password.Password; SessionInformation.Login.Pin = PINTextBox.Text; if (!String.IsNullOrEmpty(SessionInformation.Login.Pin)) { SessionInformation.Login.Pin += "_" + System.Environment.MachineName; } Action action = Login; action.BeginInvoke(cb => { }, null); } } private void Hyperlink_OnRequestNavigate(object sender, RequestNavigateEventArgs e) { System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo((sender as Hyperlink).NavigateUri.ToString())); } private void TextBox_Username_OnGotFocus(object sender, RoutedEventArgs e) { TextBox_Username.SelectAll(); } private void PasswordBox_Password_OnGotFocus(object sender, RoutedEventArgs e) { PasswordBox_Password.SelectAll(); } private void button_addProfile_Click(object sender, RoutedEventArgs rea) { var newProfileList = new ObservableCollection(ProfileList); try { Mouse.OverrideCursor = Cursors.Wait; var p = new ProfileEditView() { Profiles = newProfileList }; profileEditPopUp.Child = p; if (p.CommandBindings.Count != 0) return; p.CommandBindings.Add( new CommandBinding( ApplicationCommands.Close, (s, e) => { profileEditPopUp.Child = null; })); p.CommandBindings.Add( new CommandBinding( ApplicationCommands.Save, (s, e) => { ProfileList = p.Profiles.ToList(); SaveProfileListToFile(); profileEditPopUp.Child = null; //BeWoProfile profile = profileSelectionComboBox.SelectedItem as BeWoProfile; //ChangeServerAndTenant(profile); })); } catch (Exception e) { } finally { Mouse.OverrideCursor = null; } } private void button_configureProxy_Click(object sender, RoutedEventArgs rea) { ProxyLoginView proxyLogin = new ProxyLoginView(); proxyLogin.WindowStartupLocation = WindowStartupLocation.CenterScreen; proxyLogin.ShowDialog(); ReadProxyName(); } private void PasswortVergessenLinkOnRequestNavigate(object sender, RequestNavigateEventArgs e) { if (pwvViewOffen) return; var p = new PwVergessenView(); p.Closed += (s, ex) => { pwvViewOffen = false; }; p.Show(); pwvViewOffen = true; } private void UIElement_OnKeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.P) { if (Keyboard.IsKeyDown(Key.LeftCtrl) || Keyboard.IsKeyDown(Key.RightCtrl) && Keyboard.IsKeyDown(Key.LeftAlt)) { PinEinblenden(); } } } private void AnimationComplete(object sender, EventArgs e) { double tmp = HeightFrom; HeightFrom = HeightTo; HeightTo = tmp; if (HeightFrom > HeightTo) { showProfileSelectionBtn.Content = "Ausblenden"; profileLabel.Visibility = Visibility.Visible; profileStackPanel.Visibility = Visibility.Visible; proxyLabel.Visibility = Visibility.Visible; proxyStackPanel.Visibility = Visibility.Visible; //installLabel.Visibility = Visibility.Visible; //installStackPanel.Visibility = Visibility.Visible; } else { showProfileSelectionBtn.Content = "Erweitert"; } } private void Animation2Complete(object sender, EventArgs e) { double tmp2 = LineYCoordFrom; LineYCoordFrom = LineYCoordTo; LineYCoordTo = tmp2; } private void ShowProfileStackPanel(object sender, RoutedEventArgs e) { if (profileLabel.Visibility == Visibility.Visible) { profileLabel.Visibility = Visibility.Collapsed; profileStackPanel.Visibility = Visibility.Collapsed; proxyLabel.Visibility = Visibility.Collapsed; proxyStackPanel.Visibility = Visibility.Collapsed; //installLabel.Visibility = Visibility.Collapsed; //installStackPanel.Visibility = Visibility.Collapsed; } } private void UserControl_Loaded(object sender, RoutedEventArgs e) { double top = (this.ActualHeight - 400) / 3; //this.gridLogin.Margin = new Thickness(0, top, 0, 0); if (TextBox_Username != null && String.IsNullOrEmpty(TextBox_Username.Text)) { TextBox_Username.Focus(); } } public void DoTooMuchInitStuffIDontHaveANameForThisMethod() { ConnectionProfile selectedProfile = null; ProfileList = new List(); HeightFrom = gridLogin.Height; HeightTo = gridLogin.Height + (32 * 2); LineYCoordFrom = linkLine.Y1; LineYCoordTo = linkLine.Y1 + (32 * 2); DataContext = this; DateTime dt = new DateTime(2017, 1, 1); if (DateTime.Now > dt) dt = DateTime.Now; txtCopyright.Text = String.Format("Copyright {0:yyyy} | beyondSoft GmbH", dt); var checkPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\profiles.txt"; if (File.Exists(checkPath)) //Nimm lokalen Profilpfad wenn er existiert. Wird z.B. bei Kunden mit Citrix Server genutzt, die keine Clickonce Installation vornehmen _ProfilesFilePath = checkPath; else _ProfilesFilePath = Path.Combine(LauncherUtils.GetAndCreateUserAppDataPath(), "profiles.txt"); _ConfigFilePath = Path.Combine(LauncherUtils.GetAndCreateUserAppDataPath(), "bwp.config"); ReadProxyName(); try { ReadProfileList(); #if DEBUG var uri = new Uri("http://localhost/Host/?k=demo&s=localhost/service"); var paramDic = LauncherUtils.ParseQuery(uri.Query); string v1, v2; paramDic.TryGetValue("k", out v1); paramDic.TryGetValue("s", out v2); SessionInformation.Login.Tenant = v1; SessionInformation.Connection.Servername = v2; if (ProfileList.Count > 0) ProfileList.Insert(0, new ConnectionProfile(v1, v2, SessionInformation.Login.Tenant)); else ProfileList.Add(new ConnectionProfile(v1, v2, SessionInformation.Login.Tenant)); SaveProfileListToFile(); #else if (ApplicationDeployment.IsNetworkDeployed && ApplicationDeployment.CurrentDeployment.ActivationUri != null) { //Start über IE //MessageBox.Show(String.Format("Start über IE.\nActivationUri: {0}\nUpdateLocation: {1}", ApplicationDeployment.CurrentDeployment.ActivationUri, ApplicationDeployment.CurrentDeployment.UpdateLocation)); ConnectionProfile p = GenerateProfileFromUri(ApplicationDeployment.CurrentDeployment.ActivationUri); if (!String.IsNullOrEmpty(p.Tenant) && !String.IsNullOrEmpty(p.Server)) { ConnectionInformation.Tenant = p.Tenant; if (ProfileList.Count > 0) { selectedProfile = ProfileList.Find(ip => ip.Tenant == p.Tenant); } if (selectedProfile == null) { if (ProfileList.Count > 0) ProfileList.Insert(0, p); else ProfileList.Add(p); } else { ProfileList.Remove(selectedProfile); selectedProfile.Server = p.Server; ProfileList.Insert(0, selectedProfile); } SaveProfileListToFile(); } else if (!String.IsNullOrEmpty(p.Tenant) && p.Tenant.ToLower() == "demo") { p.Server = "1"; ProfileList.Add(p); } } else { //MessageBox.Show(String.Format("Start über Firefox oder über installiertes Desktop Icon.\nActivationUri: {0}\nUpdateLocation: {1}", ApplicationDeployment.CurrentDeployment.ActivationUri, ApplicationDeployment.CurrentDeployment.UpdateLocation)); } #endif } catch (Exception) { } UpdateIpAddress(); if (ProfileList.Count == 0 || String.IsNullOrEmpty(ProfileList[0].Tenant)) ShowEnterTenantDialog(); ConnectionProfile firstProfile = null; if (ProfileList.Count > 0) firstProfile = ProfileList[0]; ProfileList.Sort((a, b) => a.Name.CompareTo(b.Name)); profileSelectionComboBox.ItemsSource = ProfileList; if (ProfileList.Count > 0) { #if DEBUG selectedProfile = ReadSelectedProfile(); #else selectedProfile = ReadSelectedProfile(); #endif if (selectedProfile == null || !ProfileList.Contains(selectedProfile)) { //selectedProfile = profileSelectionComboBox.SelectedItem as BeWoProfile; selectedProfile = firstProfile; } } //if (profileSelectionComboBox.SelectedItem == null) profileSelectionComboBox.SelectedItem = selectedProfile; TextBox_Username.Focus(); if (selectedProfile != null && selectedProfile.Tenant == "demo") { TextBox_Username.Text = "demo"; PasswordBox_Password.Password = "demo"; } lblVersion.Content = LauncherApp.Version; Loaded += UserControl_Loaded; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; PinCertificate(); ChangeServerAndTenant(profileSelectionComboBox.SelectedItem as ConnectionProfile); if (!String.IsNullOrEmpty(SessionInformation.Connection.ProxyName)) { var webProxy = WebProxy.GetDefaultProxy(); webProxy.UseDefaultCredentials = true; System.Net.WebRequest.DefaultWebProxy = new WebProxy(SessionInformation.Connection.ProxyName, true); if (String.IsNullOrEmpty(SessionInformation.Connection.ProxyUsername)) { WebRequest.DefaultWebProxy.Credentials = CredentialCache.DefaultNetworkCredentials; } else { WebRequest.DefaultWebProxy.Credentials = new NetworkCredential(SessionInformation.Connection.ProxyUsername, SessionInformation.Connection.ProxyPassword); } } } private ConnectionProfile ReadSelectedProfile() { try { if (File.Exists(_ConfigFilePath)) { using (var myFile = new StreamReader(_ConfigFilePath, Encoding.Default)) { while (!myFile.EndOfStream) { var data = myFile.ReadLine(); if (!String.IsNullOrEmpty(data)) { if (data.Contains("selected")) { var pos = data.IndexOf("="); if (pos > 0) { var pData = data.Substring(pos + 1).Trim().Split('|'); if (pData.Length >= 3) { if (!String.IsNullOrEmpty(pData[1]) && !String.IsNullOrEmpty(pData[2])) return new ConnectionProfile(pData[0], pData[1], pData[2]); } } } } } } } } catch (Exception e) { } return null; } private ConnectionProfile GenerateProfileFromUri(Uri uri) { var paramDic = LauncherUtils.ParseQuery(uri.Query); string v1, v2; paramDic.TryGetValue("k", out v1); paramDic.TryGetValue("s", out v2); //if (String.IsNullOrEmpty(v1)) //{ // v1 = "demo"; //} //if (String.IsNullOrEmpty(v2)) //{ // v2 = "Ungültiger Server"; // String uriStr = uri.ToString(); // if (!String.IsNullOrEmpty(uriStr)) // { // v2 = uriStr; // if (uriStr.IndexOf("://") >= 0) // v2 = uriStr.Substring(uriStr.IndexOf("://") + 3); // if (v2.ToLower().IndexOf("/bewo.application") > 0) // v2 = v2.Substring(0, v2.ToLower().IndexOf("/bewo.application")); // } //} return new ConnectionProfile(v1, v2, v1); } private void PinCertificate() { ServicePointManager.ServerCertificateValidationCallback = PinPublicKey; } private bool PinPublicKey(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslpolicyerrors) { try { if (certificate == null || chain == null) return false; bool chainContainsPk = false; foreach (var element in chain.ChainElements) { String pk = element.Certificate.GetPublicKeyString(); if (pk == PUB_KEY_X3 || pk == PUB_KEY_R3 || pk == PUB_KEY_E1) { chainContainsPk = true; } } bool subjectAccepted = certificate.Subject.Trim().ToLower().EndsWith(".bewoplaner.de") || certificate.Subject.Trim().ToLower().EndsWith(".ownchat.de"); return chainContainsPk && subjectAccepted; } catch (Exception) { return false; } } protected virtual void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } private void ShowEnterTenantDialog() { ConnectionProfile p = null; var cancel = false; var tenant = String.Empty; while (p == null && !cancel) { var dlg = new EnterTenantDialog { Tenant = tenant }; var result = dlg.ShowDialog(); if (result.HasValue && result.Value) { tenant = dlg.Tenant; if (!String.IsNullOrWhiteSpace(tenant)) { tenant = tenant.Trim(); } var server = GetServerFromTenant(tenant); if (!String.IsNullOrEmpty(server)) { p = new ConnectionProfile(tenant, server, tenant); if (ProfileList.Count > 0) ProfileList.Insert(0, p); else ProfileList.Add(p); SaveProfileListToFile(); } else { MessageBox.Show("Unbekannte Kundennummer '" + tenant + "'", "BeWoPlaner"); } } else { cancel = true; } } } private void UpdateIpAddress() { try { var adminUrl = GetAdminUrl(); if (!String.IsNullOrEmpty(adminUrl)) { using (var wc = new WebClient()) { Uri path = new Uri(adminUrl); SessionInformation.Connection.IpAddress = Encoding.UTF8.GetString(wc.DownloadData(path)); } } } catch (Exception) { SessionInformation.Connection.IpAddress = String.Empty; } } private string GetAdminUrl() { String address = String.Empty; #if DEBUG if (true) { address = "http://localhost/Host"; //Uri uri = new Uri("http://app.beyondsoft.de/bewo.application"); //hostAddress = String.Format("{0}://{1}", uri.Scheme, uri.Host); #else if (ApplicationDeployment.IsNetworkDeployed && ApplicationDeployment.CurrentDeployment.UpdateLocation != null) { Uri uri = ApplicationDeployment.CurrentDeployment.UpdateLocation; address = String.Format("{0}://{1}", uri.Scheme, uri.Host); #endif } if (String.IsNullOrEmpty(address)) { return null; } return String.Format("{0}/{1}", address, "Admin.aspx"); } private void PinEinblenden() { PINTextBox.Visibility = Visibility.Visible; lblPin.Visibility = Visibility.Visible; linkLine.Margin = new Thickness(linkLine.Margin.Left, linkLine.Margin.Top + 25, linkLine.Margin.Right, linkLine.Margin.Bottom); gridLogin.Height += 25; PINTextBox.Focus(); } private bool IsNet45OrNewer() { // Class "ReflectionContext" exists from .NET 4.5 onwards. return Type.GetType("System.Reflection.ReflectionContext", false) != null; } private void ReadProxyName() { int counter = 0; string line; string[] datai = new string[3]; try { var filePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\proxy.dat"; if (!File.Exists(filePath)) { filePath = Path.Combine(LauncherUtils.GetAndCreateUserAppDataPath(), "proxy.dat"); } var file = new System.IO.StreamReader(filePath); while ((line = file.ReadLine()) != null) { byte[] decbuff = Convert.FromBase64String(line); var x = System.Text.Encoding.UTF8.GetString(decbuff); datai[counter] = x; counter++; } file.Close(); SessionInformation.Connection.ProxyName = datai[0]; SessionInformation.Connection.ProxyUsername = datai[1]; SessionInformation.Connection.ProxyPassword = datai[2]; proxyTextBox.Text = SessionInformation.Connection.ProxyName; } catch (IOException) { //Fehlermeldung } } private void ReadProfileList() { try { if (File.Exists(_ProfilesFilePath)) { var myFile = new StreamReader(_ProfilesFilePath, Encoding.Default); while (!myFile.EndOfStream) { var data = myFile.ReadLine().Split('|'); if (data.Length >= 3) { if (!String.IsNullOrEmpty(data[1]) && !String.IsNullOrEmpty(data[2])) ProfileList.Add(new ConnectionProfile(data[0], data[1], data[2])); } } myFile.Close(); } } catch (Exception) { } } private void SaveSelectedProfile(ConnectionProfile profile) { try { using (var sw = new StreamWriter(new FileStream(_ConfigFilePath, FileMode.Create), Encoding.UTF8)) { #if DEBUG sw.WriteLine("selected={0}|{1}|{2}", profile.Name, profile.Server, profile.Tenant); #else if (profile.Tenant != "demo") { sw.WriteLine("selected={0}|{1}|{2}", profile.Name, profile.Server, profile.Tenant); } #endif } } catch (Exception) { //ignore read/write errors } } private void SaveProfileListToFile() { try { var sw = new StreamWriter(new FileStream(_ProfilesFilePath, FileMode.Create), Encoding.UTF8); foreach (var profile in ProfileList) { if (profile.Tenant != "demo") { if (!String.IsNullOrWhiteSpace(profile.Tenant)) { profile.Tenant = profile.Tenant.Trim(); } sw.WriteLine("{0}|{1}|{2}", profile.Name, profile.Server, profile.Tenant); } } sw.Flush(); sw.Close(); profileSelectionComboBox.ItemsSource = ProfileList; profileSelectionComboBox.Items.Refresh(); // Workaround, um profileSelectionComboBox.SelectedItem zu aktualisieren if (profileSelectionComboBox.ItemsSource == null) return; //ChangeServerAndTenant(profileSelectionComboBox.SelectedItem as BeWoProfile); //int itemssourcecount = ((List) profileSelectionComboBox.ItemsSource).Count; //int si = profileSelectionComboBox.SelectedIndex; //profileSelectionComboBox.SelectedIndex = (si + 1) % itemssourcecount; //profileSelectionComboBox.SelectedIndex = itemssourcecount == 1 || si == -1 ? 0 : si; } catch (Exception) { //ignore read/write errors } } private void ChangeServerAndTenant(ConnectionProfile profile) { try { //button_login.IsEnabled = false; if (profile != null) { if (String.IsNullOrEmpty(profile.Server)) { MessageBox.Show( String.Format("Das gewählte Profil '{0}' enthält einen ungültigen Servernamen.", profile.Name), "Ungültiges Profil", MessageBoxButton.OK, MessageBoxImage.Warning); return; } if (String.IsNullOrEmpty(profile.Tenant)) { MessageBox.Show( String.Format("Das gewählte Profil '{0}' enthält eine ungültige Kundennummer.", profile.Name), "Ungültiges Profil", MessageBoxButton.OK, MessageBoxImage.Warning); return; } profile.Tenant = profile.Tenant.Trim(); //if (ConnectionInformation.Tenant == "7635986435") //{ // if (profile.Server != "3") // { // profile.Server = "3"; // SaveProfileListToFile(); // } //} var server = GetServerFromTenant(profile.Tenant); if (!String.IsNullOrEmpty(server) && server != profile.Server) { profile.Server = server; SaveProfileListToFile(); } SessionInformation.Login.Tenant = profile.Tenant; SessionInformation.Connection.Servername = GetNumericServerName(profile.Server); SessionInformation.Connection.CoreServerAddress = profile.Server; SessionInformation.Connection.DownloadServerAddress = profile.Server; #if DEBUG SessionInformation.Connection.DownloadServerAddress = SessionInformation.GetDebugConnection(1); SessionInformation.Connection.CoreServerAddress = SessionInformation.GetDebugConnection(2); //CB ZUM TESTEN //ConnectionInformation.Tenant = "9876543210"; //ConnectionInformation.ServerName = "4"; //MainSession.ServerAddress = "app4.bewoplaner.de"; #endif SaveSelectedProfile(profile); //button_login.IsEnabled = true; } } catch (UriFormatException) { MessageBox.Show( "Die angegebene Serveradresse ist nicht korrekt. Bitte bearbeiten Sie das verwendete Profil. Klicken Sie dazu auf 'Erweitert' und anschließend auf den Button 'Profile bearbeiten'", "Ungültiges Profil", MessageBoxButton.OK, MessageBoxImage.Warning); } } private string GetServerFromTenant(string tenant) { try { if (tenant == "demo") { return "app1.bewoplaner.de"; } //Server URL über Kundennummer: //https://bewoplaner.beyondsoft.de/getserver.php?CustomerID=1234567890 //Lizenzstatus über Kundennummer (Lizenzzahlen und aktivierte Module) //Nur Testdaten. Weiß gar nicht mehr so genau wofür das gut war… //https://bewoplaner.beyondsoft.de/getcontractstate.php?CustomerID=1234567890 var url = string.Format(GETSERVER_URL, tenant); using (WebClient client = new WebClient()) { //MessageBox.Show(hostAddress); byte[] response = client.UploadValues(url, "POST", new NameValueCollection()); String server = System.Text.Encoding.ASCII.GetString(response); return server; } } catch (Exception) { //MessageBox.Show(String.Format("Fehler beim Prüfen der Kundennummer: {0}\n\n{1}", ex.Message, ex.StackTrace)); return null; } } private string GetNumericServerName(string serverName) { if (!String.IsNullOrEmpty(serverName)) { int snOut = 0; if (!Int32.TryParse(serverName, out snOut)) { String nname = serverName.Replace("app", ""); if (nname.IndexOf('.') > 0) { return nname.Substring(0, nname.IndexOf('.')); } } } return serverName; } private bool CheckStatusMessage(ConnectionProfile profile, string url) { #if DEBUG //String message = @"Sehr geehrte Kundin, sehr geehrter Kunde, // Ihr BeWoPlaner Nutzungszeitraum endet automatisch am 31.01.2020. // Bitte wenden Sie sich an den BeWoPlaner - Support, sofern Sie den Nutzungszeitraum verlängern möchten. // Vielen Dank. // Ihr BeWoPlaner-Team;1"; //if (!String.IsNullOrWhiteSpace(message) && message.Trim().Length > 2) //{ // String ende = message.Substring(message.Length - 2); // message = message.Replace("\\n", "\n"); // message = message.Substring(0, message.Length - 2); // MessageDialog dlg = new MessageDialog(); // if (message.Contains("<") && message.Contains(">")) // { // dlg.SetXaml(message); // } // else // { // dlg.Message = message; // } // dlg.Visibility = Visibility.Visible; // dlg.ShowDialog(); // if (ende.EndsWith(";0")) // { // return false; // } //} return true; #else try { using (WebClient client = new WebClient()) { //MessageBox.Show(hostAddress); byte[] response = client.UploadValues(url, "POST", new NameValueCollection()); String message = System.Text.Encoding.UTF8.GetString(response); //zum testen: //using (var myFile = new StreamReader("C:\\temp\\testxaml.txt", Encoding.Default)) //{ // message = myFile.ReadToEnd(); // myFile.Close(); //} if (!String.IsNullOrWhiteSpace(message) && message.Trim().Length > 2) { String ende = message.Substring(message.Length - 2); message = message.Replace("\\n", "\n"); message = message.Substring(0, message.Length - 2); MessageDialog dlg = new MessageDialog(); if (message.Contains("<") && message.Contains(">")) { dlg.SetXaml(message); } else { dlg.Message = message; } dlg.ShowDialog(); if (ende.EndsWith(";0")) { return false; } } } } catch (Exception ex) { //MessageBox.Show(String.Format("Fehler beim Prüfen der Kundennummer: {0}\n\n{1}", ex.Message, ex.StackTrace)); } return true; #endif } private void Login() { try { //1. Versuch UserValidationResult result = TryLogin(); //2. Versuch if (result == UserValidationResult.UnknownError) { LauncherServiceFacade.DoLauncherServiceAsync(op => op.ResetTenant(SessionInformation.Login.Tenant), delegate { result = TryLogin(); if (result == UserValidationResult.UnknownError) { //3. Versuch LauncherServiceFacade.DoLauncherServiceAsync(op => op.ResetAllTenant(), delegate { result = TryLogin(); if (result == UserValidationResult.UnknownError) { this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)delegate { ViewController.EndWaiting(); MessageBox.Show("Fehler beim Verbinden mit dem Server. Bitte überprüfen Sie Ihre Internetverbindung oder schreiben Sie eine E-Mail an den Support support@bewoplaner.de.", "Fehler bei der Anmeldung", MessageBoxButton.OK, MessageBoxImage.Exclamation); }); } }); } }); } if (result == UserValidationResult.UserUnknown) { this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)delegate { ViewController.EndWaiting(); MessageBox.Show("Anmeldeinformationen nicht bekannt. Bitte überprüfen Sie den Benutzernamen und das Passwort!", "Fehler bei der Anmeldung", MessageBoxButton.OK, MessageBoxImage.Exclamation); }); } if (result == UserValidationResult.TenantUnknown) { this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)delegate { ViewController.EndWaiting(); MessageBox.Show("Die Kundennummer '" + SessionInformation.Login.Tenant + "' ist ungültig.", "Fehler bei der Anmeldung", MessageBoxButton.OK, MessageBoxImage.Exclamation); }); } String pin = SessionInformation.Login.Pin; if (!String.IsNullOrEmpty(SessionInformation.Login.Pin) && SessionInformation.Login.Pin.IndexOf('_') >= 0) { pin = SessionInformation.Login.Pin.Substring(0, SessionInformation.Login.Pin.IndexOf('_')); } if (result == UserValidationResult.IncorrectPin) { this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)delegate { ViewController.EndWaiting(); MessageBox.Show("Die Pin '" + pin + "' ist unbekannt!", "Fehler bei der Anmeldung", MessageBoxButton.OK, MessageBoxImage.Exclamation); }); } if (result == UserValidationResult.PinAlreadyUsed) { this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)delegate { ViewController.EndWaiting(); MessageBox.Show("Die Pin '" + pin + "' wurde bereits verwendet!", "Fehler bei der Anmeldung", MessageBoxButton.OK, MessageBoxImage.Exclamation); }); } if (result == UserValidationResult.PinExpired) { this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)delegate { ViewController.EndWaiting(); MessageBox.Show("Die Pin '" + pin + "' ist bereits abgelaufen!", "Fehler bei der Anmeldung", MessageBoxButton.OK, MessageBoxImage.Exclamation); }); } if (result == UserValidationResult.PasswordExpired) { //this.Dispatch(delegate //{ // grid_root.Children.Remove(lWaitLayer); // //MessageBox.Show("Das Passwort ist abgelaufen!", "Fehler bei der Anmeldung", MessageBoxButton.OK, MessageBoxImage.Exclamation); // //var pav = new PasswortAenderungsView(); // //pav.ShowDialog(); //}); } // Wegen fehlerhaftem Profil, sonst wird lWaitLayer nicht entfernt und eine Korrektur des Profils ist unmöglich ohne den BeWoPlaner neuzustarten. if (result == UserValidationResult.UnknownError) { Thread.Sleep(2000); this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)delegate { ViewController.EndWaiting(); }); } } catch (Exception ex) { LauncherApp.ShowError(ex); //MessageBox.Show(ex.Message); } } private UserValidationResult TryLogin() { UserValidationResult? result = null; if (!string.IsNullOrEmpty(SessionInformation.Login.Username) && !string.IsNullOrEmpty(SessionInformation.Login.Password)) { String version = "unbekannt"; String clr = "unbekannt"; var bewoVersion = LauncherApp.Version; try { version = Environment.OSVersion.VersionString; } catch (Exception e) { version = e.Message; } try { clr = Environment.Version.ToString(); } catch (Exception e) { clr = e.Message; } SessionInformation.Login.TempUsername = $"{SessionInformation.Login.Username}" + $"//Version={version};CLRVersion={clr};BeWoVersion={bewoVersion};IsNet45OrNewer={isNet45OrNewer}"; try { LauncherServiceFacade.DoLauncherServiceAsync(s => { try { SessionInformation.Login.ClientId = "BeWoClient"; var t = s.IsUserValid(SessionInformation.Login.TempUsername, SessionInformation.Login.Password, SessionInformation.Login.Pin, SessionInformation.Login.ClientId, true); return t; } catch (Exception e) { return UserValidationResult.UnknownError; } }, r => { result = r; Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)delegate { LoginResult(r); }); }, true); } catch (Exception e) { result = UserValidationResult.UnknownError; } } else { if (result == null) result = UserValidationResult.UserUnknown; } while (!result.HasValue) { Thread.Sleep(100); } return result.Value; } private void LoginResult(UserValidationResult result) { if (result == UserValidationResult.UserValid) { LoginSuccessful.Invoke(this, new EventArgs()); } else if (result == UserValidationResult.PasswordExpired) { Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)delegate { PopUpWindow window = null; PasswortAenderungsView view = new PasswortAenderungsView(window); window = new PopUpWindow(view); window.ShowDialog(); if (!window.Abbruch) { LoginSuccessful.Invoke(this, new EventArgs()); } }); } } public void ClickLogin() => button_login_Click(this, new RoutedEventArgs()); } }