Files
BeWoPlaner/BeWo/LoginControl.xaml.cs
2020-08-17 15:50:00 +02:00

1450 lines
50 KiB
C#

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Deployment.Application;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using System.ServiceModel;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Navigation;
using System.Windows.Threading;
using BS.Shared;
using BS.Shared.Extensions;
using BeWo.Core;
using BeWo.ServiceProxy;
using BeWo.View;
using BeWo.View.Detail;
using Path = System.IO.Path;
namespace BeWo
{
/// <summary>
/// Interaktionslogik für LoginControl.xaml
/// </summary>
public partial class LoginControl : UserControl, INotifyPropertyChanged
{
private readonly Stack<Control> _ModalPopUpControls = new Stack<Control>();
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";
private String GETNETMESSAGE_URL = "https://support.bewoplaner.de/api/getxmlstate.php?k={0}&t=1";
private bool _IsTechSupport;
public bool IsTechSupport
{
get { return _IsTechSupport; }
set { _IsTechSupport = value; OnPropertyChanged("IsTechSupport"); }
}
private Control _CurrentModalPopUp;
private Grid _ModalPopUpBackGround;
private readonly string _ProfilesFilePath;
private readonly string _ConfigFilePath;
public event EventHandler LoginSuccessful;
private bool isNet45OrNewer = false;
//proxy anmeldedaten
public string proxyname;
public string proxyUsername;
public string proxypasswd;
private List<BeWoProfile> _ProfileList;
public List<BeWoProfile> ProfileList
{
get { return _ProfileList; }
set { _ProfileList = value; }
}
public LoginControl()
{
InitializeComponent();
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(BeWoApp.GetAndCreateUserAppDataPath(), "profiles.txt");
}
_ConfigFilePath = Path.Combine(BeWoApp.GetAndCreateUserAppDataPath(), "bwp.config");
ProfileList = new List<BeWoProfile>();
BeWoProfile selectedProfile = null;
HeightFrom = gridLogin.Height;
HeightTo = gridLogin.Height + 64;
LineYCoordFrom = linkLine.Y1;
LineYCoordTo = linkLine.Y1 + 64;
DataContext = this;
ReadProxyName();
try
{
ReadProfileList();
#if DEBUG
var uri = new Uri("https://localhost/Host/?k=demo&s=localhost/service");
var paramDic = BeWoUtils.ParseQuery(uri.Query);
string v1, v2;
paramDic.TryGetValue("k", out v1);
paramDic.TryGetValue("s", out v2);
BeWoApp.Tenant = v1;
BeWoApp.ServerName = v2;
if (ProfileList.Count > 0)
ProfileList.Insert(0, new BeWoProfile(v1, v2, BeWoApp.Tenant));
else
ProfileList.Add(new BeWoProfile(v1, v2, BeWoApp.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));
BeWoProfile p = GenerateProfileFromUri(ApplicationDeployment.CurrentDeployment.ActivationUri);
if (!String.IsNullOrEmpty(p.Tenant) && !String.IsNullOrEmpty(p.Server))
{
BeWoApp.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 ex)
{
}
// IP-Adresse holen
try
{
var adminUrl = GetAdminUrl();
if (!String.IsNullOrEmpty(adminUrl))
{
using (var wc = new WebClient())
{
Uri path = new Uri(adminUrl);
BeWoApp.IpAddress = Encoding.UTF8.GetString(wc.DownloadData(path));
}
}
}
catch (Exception e)
{
BeWoApp.IpAddress = String.Empty;
}
//string ipaddress = "";
#if DEBUG
IsTechSupport = true;
#else
IsTechSupport = !String.IsNullOrEmpty(BeWoApp.IpAddress) && BeWoApp.IpAddress.Equals("87.79.89.65");
#endif
// --------------
if (ProfileList.Count == 0 || String.IsNullOrEmpty(ProfileList[0].Tenant))
ShowEnterTenantDialog();
//if (ProfileList.Count == 0)
//ProfileList.Add(new BeWoProfile("Ungültiges Profil", "Bitte geben Sie hier einen gültigen Server an. Z.B. app1", "Kundennummer"));
BeWoProfile 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;
if (selectedProfile != null && selectedProfile.Tenant == "demo")
{
TextBox_Username.Text = "demo";
PasswordBox_Password.Password = "demo";
button_login.Focus();
}
else
{
TextBox_Username.Focus();
}
//this.lblTenant.Content = BeWoApp.Tenant;
lblVersion.Content = BeWoApp.Version;
Loaded += LoginControl_Loaded;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
PinCertificate();
if (!IsTechSupport)
return;
linkLine.Margin = new Thickness(linkLine.Margin.Left, linkLine.Margin.Top + 25, linkLine.Margin.Right, linkLine.Margin.Bottom);
gridLogin.Height += 25;
}
private void PinCertificate()
{
ServicePointManager.ServerCertificateValidationCallback = PinPublicKey;
}
private static String PUB_KEY = "3082010A02820101009CD30CF05AE52E47B7725D3783B3686330EAD735261925E1BDBE35F170922FB7B84B4105ABA99E350858ECB12AC468870BA3E375E4E6F3A76271BA7981601FD7919A9FF3D0786771C8690E9591CFFEE699E9603C48CC7ECA4D7712249D471B5AEBB9EC1E37001C9CAC7BA705EACE4AEBBD41E53698B9CBFD6D3C9668DF232A42900C867467C87FA59AB8526114133F65E98287CBDBFA0E56F68689F3853F9786AFB0DC1AEF6B0D95167DC42BA065B299043675806BAC4AF31B9049782FA2964F2A20252904C674C0D031CD8F31389516BAA833B843F1B11FC3307FA27931133D2D36F8E3FCF2336AB93931C5AFC48D0D1D641633AAFA8429B6D40BC0D87DC3930203010001";
private bool PinPublicKey(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslpolicyerrors)
{
try
{
if (null == certificate || chain == null)
return false;
;
bool chainContainsPk = false;
foreach (var element in chain.ChainElements)
{
String pk = element.Certificate.GetPublicKeyString();
if (pk == PUB_KEY)
{
chainContainsPk = true;
}
}
//bool subjectAccepted = Regex.IsMatch(certificate.Subject, @"app[\d]*.bewoplaner.de");
bool subjectAccepted = certificate.Subject.Trim().ToLower().EndsWith(".bewoplaner.de") ||
certificate.Subject.Trim().ToLower().EndsWith(".ownchat.de");
return chainContainsPk && subjectAccepted;
}
catch (Exception e)
{
return false;
}
}
private bool IsNet45OrNewer()
{
// Class "ReflectionContext" exists from .NET 4.5 onwards.
return Type.GetType("System.Reflection.ReflectionContext", false) != null;
}
private bool CheckStatusMessage(BeWoProfile 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;
// }
// var test = this.GetRootParent() as Window;
// if (test != null)
// {
// dlg.Owner = test;
// dlg.WindowStartupLocation = WindowStartupLocation.CenterOwner;
// }
// var result = 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 BeWoProfile 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 BeWoProfile(pData[0], pData[1], pData[2]);
}
}
}
}
}
}
}
}
catch (Exception e)
{
}
return null;
}
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 BeWoProfile(data[0], data[1], data[2]));
}
}
myFile.Close();
}
}
catch (Exception e)
{
}
}
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 void ShowEnterTenantDialog()
{
BeWoProfile 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 BeWoProfile(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 string GetServerFromTenantAlt(string tenant)
{
try
{
using (WebClient client = new WebClient())
{
//MessageBox.Show(hostAddress);
byte[] response = client.UploadValues(GetAdminUrl(), "POST", new NameValueCollection()
{
{"k", tenant},
{"p", "6ca793d9e460"}
});
String server = System.Text.Encoding.ASCII.GetString(response);
return server;
}
}
catch (Exception ex)
{
MessageBox.Show(String.Format("Fehler beim Prüfen der Kundennummer: {0}\n\n{1}", ex.Message, ex.StackTrace));
}
return null;
}
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
String 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 ex)
{
//MessageBox.Show(String.Format("Fehler beim Prüfen der Kundennummer: {0}\n\n{1}", ex.Message, ex.StackTrace));
return null;
}
return null;
}
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 BeWoProfile GenerateProfileFromUri(Uri uri)
{
var paramDic = BeWoUtils.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 BeWoProfile(v1, v2, v1);
}
public void CloseCurrentPopUp()
{
if (this._ModalPopUpBackGround != null)
{
this.Dispatcher.BeginInvoke(
DispatcherPriority.Normal,
(Action)delegate
{
this.grid_root.Children.Remove(this._CurrentModalPopUp);
this._CurrentModalPopUp = null;
if (this._ModalPopUpControls.Count == 0)
{
this.grid_root.Children.Remove(this._ModalPopUpBackGround);
this._ModalPopUpBackGround = null;
}
else
{
var control = this._ModalPopUpControls.Pop();
this._CurrentModalPopUp = control;
this.grid_root.Children.Add(control);
Panel.SetZIndex(control, int.MaxValue);
}
});
}
}
public void ShowControlAsModalPopUp(Control control)
{
this.ShowControlAsModalPopUp(control, HorizontalAlignment.Center, VerticalAlignment.Center);
}
public void ShowControlAsModalPopUp(Control control, HorizontalAlignment ha, VerticalAlignment va)
{
this.Dispatcher.BeginInvoke(
DispatcherPriority.Normal,
(Action)delegate
{
if (this._CurrentModalPopUp != null)
{
this.grid_root.Children.Remove(this._CurrentModalPopUp);
this._ModalPopUpControls.Push(this._CurrentModalPopUp);
}
else
{
this.ShowModalBackground();
}
this._CurrentModalPopUp = control;
control.HorizontalAlignment = ha;
control.VerticalAlignment = va;
Grid.SetColumnSpan(control, 3);
Grid.SetRowSpan(control, 3);
this.grid_root.Children.Add(control);
Panel.SetZIndex(control, int.MaxValue);
});
}
private void LoginControl_Loaded(object sender, RoutedEventArgs e)
{
double top = (this.ActualHeight - 400) / 3;
this.gridLogin.Margin = new Thickness(0, top, 0, 0);
BeWoApp.LoginControl = this;
if (TextBox_Username != null && String.IsNullOrEmpty(TextBox_Username.Text))
{
TextBox_Username.Focus();
}
}
private void ShowModalBackground()
{
this._ModalPopUpBackGround = new Grid();
this._ModalPopUpBackGround.IsHitTestVisible = true;
this._ModalPopUpBackGround.Background = Brushes.White;
this._ModalPopUpBackGround.Opacity = .5;
Grid.SetColumnSpan(this._ModalPopUpBackGround, 3);
Grid.SetRowSpan(this._ModalPopUpBackGround, 3);
this.grid_root.Children.Add(this._ModalPopUpBackGround);
Panel.SetZIndex(this._ModalPopUpBackGround, int.MaxValue - 1);
}
private void button_login_Click(object sender, RoutedEventArgs e)
{
if (!String.IsNullOrEmpty(proxyname))
{
var webProxy = WebProxy.GetDefaultProxy();
webProxy.UseDefaultCredentials = true;
System.Net.WebRequest.DefaultWebProxy = new WebProxy(proxyname, true);
if (String.IsNullOrEmpty(proxyUsername))
{
WebRequest.DefaultWebProxy.Credentials = CredentialCache.DefaultNetworkCredentials;
}
else
{
WebRequest.DefaultWebProxy.Credentials = new NetworkCredential(proxyUsername, proxypasswd);
}
}
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 BeWoProfile;
isNet45OrNewer = IsNet45OrNewer();
if (!isNet45OrNewer)
{
if (!CheckStatusMessage(profile, String.Format(GETNETMESSAGE_URL, profile.Tenant)))
{
return;
}
}
#if DEBUG
//if (!CheckStatusMessage(profile, String.Format(GETNETMESSAGE_URL, profile.Tenant)))
//{
// return;
//}
#else
if (!CheckStatusMessage(profile, String.Format(GETSTATUSMESSAGE_URL, profile.Tenant)))
{
return;
}
#endif
ChangeServerAndTenant(profile);
var lWaitLayer = new WaitLayer2();
grid_root.Children.Add(lWaitLayer);
string lUserName = TextBox_Username.Text;
string lPassword = PasswordBox_Password.Password;
string lPIN = PINTextBox.Text;
string lTenant = BeWoApp.Tenant;
if (!String.IsNullOrEmpty(lPIN))
{
lPIN += "_" + System.Environment.MachineName;
}
Action<WaitLayer2, String, String, String, String> action = Login;
action.BeginInvoke(lWaitLayer, lUserName, lPassword, lTenant, lPIN, cb => {}, null);
}
}
private void Login(WaitLayer2 lWaitLayer, String lUserName, String lPassword, String lTenant, String lPIN)
{
try
{
//1. Versuch
UserValidationResult result = TryLogin(lWaitLayer, lUserName, lPassword, lPIN );
//2. Versuch
if (result == UserValidationResult.UnkownError)
{
ServiceFacade.DoOperationsServiceAsync(op => op.ResetTenant(lTenant),
delegate
{
result = TryLogin(lWaitLayer ,lUserName, lPassword, lPIN);
if (result == UserValidationResult.UnkownError)
{
//3. Versuch
ServiceFacade.DoOperationsServiceAsync(op => op.ResetAllTenants(),
delegate
{
result = TryLogin(lWaitLayer,lUserName, lPassword, lPIN);
if (result == UserValidationResult.UnkownError)
{
this.Dispatch(delegate
{
grid_root.Children.Remove(lWaitLayer);
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.Dispatch(delegate
{
grid_root.Children.Remove(lWaitLayer);
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.Dispatch(delegate
{
grid_root.Children.Remove(lWaitLayer);
MessageBox.Show("Die Kundennummer '" + lTenant + "' ist ungültig.", "Fehler bei der Anmeldung", MessageBoxButton.OK, MessageBoxImage.Exclamation);
});
}
String pin = lPIN;
if (!String.IsNullOrEmpty(lPIN) && lPIN.IndexOf('_') >= 0)
{
pin = lPIN.Substring(0, lPIN.IndexOf('_'));
}
if (result == UserValidationResult.IncorrectPin)
{
this.Dispatch(delegate
{
grid_root.Children.Remove(lWaitLayer);
MessageBox.Show("Die Pin '" + pin + "' ist unbekannt!", "Fehler bei der Anmeldung", MessageBoxButton.OK, MessageBoxImage.Exclamation);
});
}
if (result == UserValidationResult.PinAlreadyUsed)
{
this.Dispatch(delegate
{
grid_root.Children.Remove(lWaitLayer);
MessageBox.Show("Die Pin '" + pin + "' wurde bereits verwendet!", "Fehler bei der Anmeldung", MessageBoxButton.OK, MessageBoxImage.Exclamation);
});
}
if (result == UserValidationResult.PinExpired)
{
this.Dispatch(delegate
{
grid_root.Children.Remove(lWaitLayer);
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.UnkownError)
{
Thread.Sleep(2000);
this.Dispatch(delegate { grid_root.Children.Remove(lWaitLayer); });
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private UserValidationResult TryLogin(WaitLayer2 lWaitLayer, string lUserName, string lPassword, string lPIN = "")
{
UserValidationResult? result = null;
if (!string.IsNullOrEmpty(lUserName) && !string.IsNullOrEmpty(lPassword))
{
String tempUsername = lUserName;
String version = "unbekannt";
String clr = "unbekannt";
var bewoVersion = BeWoApp.Version;
try
{
version = Environment.OSVersion.VersionString;
}
catch (Exception e)
{
version = e.Message;
}
try
{
clr = Environment.Version.ToString();
}
catch (Exception e)
{
clr = e.Message;
}
tempUsername = String.Format("{0}//Version={1};CLRVersion={2};BeWoVersion={3};IsNet45OrNewer={4}", lUserName, version, clr, bewoVersion, isNet45OrNewer);
try
{
ServiceFacade.DoUserServiceAsync(s =>
{
try
{
return s.IsUserValid(tempUsername, lPassword, lPIN);
}
catch (Exception)
{
return UserValidationResult.UnkownError;
}
},
r =>
{
result = r;
LoginResult(lWaitLayer,r, lUserName, lPassword, lPIN );
}, true);
}
catch (FaultException<BeWoFault>)
{
result = UserValidationResult.UnkownError;
}
}
else
{
if(result == null)
result = UserValidationResult.UserUnknown;
}
while (!result.HasValue)
{
Thread.Sleep(100);
}
return result.Value;
}
private void LoginResult( WaitLayer2 lWaitLayer, UserValidationResult result, String lUserName, String lPassword, String lPIN = "")
{
//
// GetState hierhin
//
//
if (result == UserValidationResult.UserValid)
{
//this.Dispatch(delegate
//{
// if (BeWoApp.Tenant == "demo")
// {
// var dlg = new ConfirmDemoDialog();
// dlg.Topmost = true;
// dlg.Show();
// }
//});
BeWoApp.UserName = lUserName;
BeWoApp.UserPassword = lPassword;
BeWoApp.PasswortStrength = BeWoUtils.CheckPasswordSecurity(lPassword);
ServiceFacade.DoUserServiceAsync(s2 => s2.LoadUserByLoginName(lUserName),
r2 =>
{
BeWoApp.LoggedOnUser = r2;
ServiceFacade.DoOperationsServiceAsync(s => s.GetMandator(),
m =>
{
BeWoApp.Mandator = m;
this.Dispatch(delegate
{
LoginSuccessful?.Invoke(this, new EventArgs());
});
});
}, true);
}
else if (result == UserValidationResult.PasswordExpired)
{
BeWoApp.UserName = lUserName;
BeWoApp.UserPassword = lPassword;
ServiceFacade.DoUserServiceAsync(s2 => s2.LoadUserByLoginName(lUserName),
r2 =>
{
BeWoApp.LoggedOnUser = r2;
ServiceFacade.DoOperationsServiceAsync(s => s.GetMandator(),
m =>
{
BeWoApp.Mandator = m;
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();
if (pav.abr == 1)
{
}
else {
LoginSuccessful?.Invoke(this, new EventArgs());
}
});
});
}, true);
}
}
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 List<BeWoProfile>();
newProfileList.AddRange(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;
SaveProfileListToFile();
profileEditPopUp.Child = null;
//BeWoProfile profile = profileSelectionComboBox.SelectedItem as BeWoProfile;
//ChangeServerAndTenant(profile);
}));
}
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 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(BeWoApp.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();
proxyname = datai[0];
proxyUsername = datai[1];
proxypasswd = datai[2];
proxyTextBox.Text = proxyname;
}catch(IOException i){
//Fehlermeldung
}
}
private void SaveSelectedProfile(BeWoProfile 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 ex)
{
//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<BeWoProfile>) profileSelectionComboBox.ItemsSource).Count;
//int si = profileSelectionComboBox.SelectedIndex;
//profileSelectionComboBox.SelectedIndex = (si + 1) % itemssourcecount;
//profileSelectionComboBox.SelectedIndex = itemssourcecount == 1 || si == -1 ? 0 : si;
}
catch (Exception ex)
{
//ignore read/write errors
}
}
private void ChangeServerAndTenant(BeWoProfile 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 (BeWoApp.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();
}
BeWoApp.Tenant = profile.Tenant;
BeWoApp.ServerName = GetNumericServerName(profile.Server);
BeWoApp.ServerAddress = profile.Server;
#if DEBUG
//CB ZUM TESTEN
//BeWoApp.Tenant = "9876543210";
//BeWoApp.ServerName = "4";
//BeWoApp.ServerAddress = "app4.bewoplaner.de";
#endif
SaveSelectedProfile(profile);
//button_login.IsEnabled = true;
}
}
catch (UriFormatException ex)
{
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 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;
}
}
private double lineYCoordTo;
private double lineYCoordFrom;
private double heightFrom;
private double heightTo;
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 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;
}
else
{
showProfileSelectionBtn.Content = "Erweitert";
}
}
private void Animation2Complete(object sender, EventArgs e)
{
double tmp2 = LineYCoordFrom;
LineYCoordFrom = LineYCoordTo;
LineYCoordTo = tmp2;
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
private bool pwvViewOffen;
private void PasswortVergessenLinkOnRequestNavigate(object sender, RequestNavigateEventArgs e)
{
if (pwvViewOffen) return;
var p = new PwVergessenView();
p.Closed += (s, ex) => { pwvViewOffen = false; };
p.Show();
pwvViewOffen = true;
}
}
public class BeWoProfile
{
public string Name { get; set; }
public string Server { get; set; }
public string Tenant { get; set; }
public BeWoProfile(string pname, string pserver, string ptenant)
{
Name = pname;
Server = pserver;
Tenant = ptenant;
if (Name == null)
Name = String.Empty;
}
public override string ToString()
{
return Name;
}
public override int GetHashCode()
{
String key = String.Format("{0}_{1}_{2}", Name, Server, Tenant);
return key.GetHashCode();
}
public override bool Equals(object obj)
{
var profile = obj as BeWoProfile;
if (profile == null)
{
return false;
}
String key1 = String.Format("{0}_{1}_{2}", Name, Server, Tenant);
String key2 = String.Format("{0}_{1}_{2}", profile.Name, profile.Server, profile.Tenant);
return key1.Equals(key2);
}
}
}