private VATRP.Core.Model.VATRPCredential GetAuthentication() { AuthenticationView _authForm = new AuthenticationView(); _authForm.ShowDialog(); if (!_authForm.Proceed) { return(null); } VATRPCredential tempCred = new VATRPCredential(); tempCred.username = _authForm.Username; tempCred.password = _authForm.Password; return(tempCred); }
public void SendXMLToServer(string xmlContents) { VATRPCredential credentials = GetAuthentication(); Task.Run(async() => { try { await PostLocationToServer(xmlContents, credentials, GeolocationPostURI); } catch (Exception ex) { } finally { await Dispatcher.BeginInvoke((Action)(() => Mouse.OverrideCursor = null)); } }); }
private async Task PostLocationToServer(string location, VATRPCredential credentials, string uri) { if (string.IsNullOrEmpty(uri)) { string msg = "No geolocation uri is set"; string caption = "Load failed"; MessageBoxButton button = MessageBoxButton.OK; System.Windows.MessageBox.Show(msg, caption, button, MessageBoxImage.Error); } try { await Utilities.JsonWebRequest.MakeXmlWebPostAuthenticatedAsync(uri, credentials, location); } catch (Utilities.JsonException ex) { string msg = String.Format("Failed to post location file to the web server: {0}.", uri); string caption = "Load failed"; MessageBoxButton button = MessageBoxButton.OK; System.Windows.MessageBox.Show(msg, caption, button, MessageBoxImage.Error); } }
/// <summary> /// Async authenticated XML POST request. /// </summary> /// <param name="webRequestUrl">string</param> /// <param name="cred">VATRPCredential</param> /// <param name="xml">string</param> /// <returns>void</returns> public static async Task MakeXmlWebPostAuthenticatedAsync(string webRequestUrl, VATRPCredential cred, string xml) { WebResponse response = null; try { // Specify TLS 1.2 ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications); // Build basic authentication header HttpWebRequest request = (HttpWebRequest)WebRequest.Create(webRequestUrl); request.Credentials = new NetworkCredential(cred.username, cred.password); request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(cred.username + ":" + cred.password)); // Specify the rerquest properties request.KeepAlive = false; request.Method = "POST"; request.Timeout = 30000; request.ContentType = "application/xml"; StreamWriter sw = new StreamWriter(request.GetRequestStream()); sw.WriteLine(xml); sw.Close(); response = await request.GetResponseAsync(); } catch (Exception ex) { throw ex; } }
/// <summary> /// Async authenticated XML GET request. /// </summary> /// <typeparam name="T">T</typeparam> /// <param name="webRequestUrl">string</param> /// <param name="cred">VATRPCredential</param> /// <returns>Task<T></returns> public static async Task <T> MakeXmlWebRequestAuthenticatedAsync <T>(string webRequestUrl, VATRPCredential cred) { WebResponse response = null; try { // Specify TLS 1.2 ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(webRequestUrl); request.Credentials = new NetworkCredential(cred.username, cred.password); request.PreAuthenticate = true; request.KeepAlive = false; request.ContentLength = 0; request.Method = "GET"; request.Timeout = 30000; response = await request.GetResponseAsync(); string xmlResults = string.Empty; XmlSerializer serializer = new XmlSerializer(typeof(T)); using (StreamReader sr = new StreamReader(response.GetResponseStream())) { try { T item = (T)serializer.Deserialize(sr); return(item); } catch (Exception ex) { throw ex; } finally { sr.Close(); if (response != null) { response.Close(); } } } } catch (Exception ex) { throw ex; } }
/// <summary> /// Method to export contacts to remote uri. Generates the /// xml format for the contacts and provides that to the /// method used to generate the POST request. /// </summary> /// <param name="uri">string</param> /// <param name="cred">VATRPCredential</param> /// <returns>void</returns> private async Task ExecuteRemoteExport(string uri, VATRPCredential cred) { var cardWriter = new vCardWriter(); this.MyContacts = new ContactList(); this.MyContacts.VCards = new List <vCard>(); foreach (var contactVM in this.Contacts) { var card = new vCard() { GivenName = contactVM.Contact.Fullname, FormattedName = contactVM.Contact.Fullname, Title = contactVM.Contact.RegistrationName }; card.Telephone.Uri = contactVM.Contact.RegistrationName; this.MyContacts.VCards.Add(card); } // Add the namespaces XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance"); ns.Add("xsd", "http://www.w3.org/2001/XMLSchema"); this.MyContacts.Namespaces = ns; // Serialize contacts into xml string if (this.MyContacts.VCards != null) { XmlAttributes atts = new XmlAttributes(); atts.Xmlns = true; XmlAttributeOverrides xover = new XmlAttributeOverrides(); xover.Add(typeof(List <vCard>), "Namespaces", atts); XmlSerializer xsSubmit = new XmlSerializer(typeof(List <vCard>), xover); var xml = ""; //XmlWriterSettings settings = new XmlWriterSettings(); //settings.OmitXmlDeclaration = true; // is this necessary? using (var sww = new StringWriter()) { using (XmlWriter writer = XmlWriter.Create(sww)) { xsSubmit.Serialize(writer, this.MyContacts.VCards); xml = sww.ToString(); // the final xml output xml = xml.Replace("ArrayOfVcard", "vcards"); // replace incorrect tag with correct one xml = xml.Replace("utf-16", "utf-8"); // TODO - fix this with formatting } } try { await JsonWebRequest.MakeXmlWebPostAuthenticatedAsync(uri, cred, xml); } catch (JsonException ex) { Debug.WriteLine($"ERROR -- Failed to POST contacts to {uri}."); } } }
/// <summary> /// Method called when the export button clicked. Prompts /// the user if they want to export the contacts to a /// remote location or local one and then calls the /// relevant methods to complete the request. /// </summary> /// <param name="obj">object</param> /// <returns>void</returns> private void ExecuteExportCommand(object obj) { //************************************************************************************************************** // Exporting Vcard contact from contact list. //************************************************************************************************************** if (ServiceManager.Instance.LinphoneService.VCardSupported && !ExportInProgress) { ExportInProgress = true; string msg = "To export your contacts to the Provider, please select Yes. Select No to export to local file system."; string caption = "Export Contacts"; MessageBoxButton button = MessageBoxButton.YesNoCancel; MessageBoxResult result = MessageBox.Show(msg, caption, button, MessageBoxImage.Question); Dispatcher Dispatcher = Dispatcher.CurrentDispatcher; switch (result) { // Remote Export case MessageBoxResult.Yes: string uri = App.CurrentAccount.ContactsURI; if (uri == string.Empty) { msg = "Valid URI required to export contacts. Please go to the Settings, Account menu to input a valid URI."; caption = "Import Contacts"; button = MessageBoxButton.OK; MessageBox.Show(msg, caption, button, MessageBoxImage.Error); ExportInProgress = false; break; } VATRPCredential contactsCredential = App.CurrentAccount.configuration.FindCredential("contacts", null) ?? GetAuthentication(); if (contactsCredential == null) { ExportInProgress = false; return; } exportTask = Task.Run(async() => { try { await Dispatcher.BeginInvoke((Action)(() => Mouse.OverrideCursor = Cursors.AppStarting)); await ExecuteRemoteExport(uri, contactsCredential); await Dispatcher.BeginInvoke((Action) delegate() { msg = "Upload Successful."; caption = "Export Status"; button = MessageBoxButton.OK; MessageBox.Show(msg, caption, button, MessageBoxImage.Information); }); } catch (Exception ex) { await Dispatcher.BeginInvoke((Action) delegate() { msg = "Upload failed."; caption = "Export Error"; button = MessageBoxButton.OK; MessageBox.Show(msg, caption, button, MessageBoxImage.Error); }); } finally { await Dispatcher.BeginInvoke((Action)(() => Mouse.OverrideCursor = null)); ExportInProgress = false; } }); break; // Local Export case MessageBoxResult.No: exportTask = Task.Run((Action) delegate() { try { Dispatcher.BeginInvoke((Action)(() => Mouse.OverrideCursor = Cursors.AppStarting)); ExecuteLocalExport(); } catch (Exception ex) { Dispatcher.BeginInvoke((Action) delegate() { msg = "Contacts export failed."; caption = "Export Error"; button = MessageBoxButton.OK; MessageBox.Show(msg, caption, button, MessageBoxImage.Error); }); } finally { Dispatcher.BeginInvoke((Action)(() => Mouse.OverrideCursor = null)); ExportInProgress = false; } }); break; case MessageBoxResult.Cancel: ExportInProgress = false; break; } } }
/// <summary> /// Method called when the import button clicked. Prompts /// the user if they want to import the contacts from a /// remote location or local one and then calls the /// relevant methods to complete the request. /// </summary> /// <param name="obj">object</param> /// <returns>void</returns> private void ExecuteImportCommand(object obj) { if (ServiceManager.Instance.LinphoneService.VCardSupported && !ImportInProgress) { ImportInProgress = true; string msg = "To download your contacts from the Provider, please select Yes. Select No to import from local file system."; string caption = "Import Contacts"; MessageBoxButton button = MessageBoxButton.YesNoCancel; MessageBoxResult result = MessageBox.Show(msg, caption, button, MessageBoxImage.Question); Dispatcher Dispatcher = Dispatcher.CurrentDispatcher; switch (result) { case MessageBoxResult.Yes: string uri = App.CurrentAccount.ContactsURI; if (uri == string.Empty) { msg = "Valid URI required to import contacts. Please go to the Settings, Account menu to input a valid URI."; caption = "Import Contacts"; button = MessageBoxButton.OK; MessageBox.Show(msg, caption, button, MessageBoxImage.Error); ImportInProgress = false; break; } importTask = Task.Run(async() => { try { await Dispatcher.BeginInvoke((Action)(() => Mouse.OverrideCursor = Cursors.AppStarting)); XmlDocument xDoc = new XmlDocument(); xDoc = await JsonWebRequest.MakeXmlWebRequestAsync <XmlDocument>(uri); var recordsImported = ServiceManager.Instance.ContactService.ImportVcardFromXdoc(xDoc); } catch (Exception ex) { try { System.Net.HttpWebResponse response = ((ex as System.Net.WebException).Response) as System.Net.HttpWebResponse; if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized) { await Dispatcher.BeginInvoke((Action)(() => Mouse.OverrideCursor = Cursors.AppStarting)); VATRPCredential creds = App.CurrentAccount.configuration.FindCredential("contacts", null); if (creds == null) { await Dispatcher.BeginInvoke((Action) delegate() { creds = GetAuthentication(); }); } XmlDocument xDoc = new XmlDocument(); xDoc = await JsonWebRequest.MakeXmlWebRequestAuthenticatedAsync <XmlDocument>(uri, creds); var recordsImported = ServiceManager.Instance.ContactService.ImportVcardFromXdoc(xDoc); } else { throw; } } catch { await Dispatcher.BeginInvoke((Action) delegate() { msg = ex.Message; caption = "Download failed"; button = MessageBoxButton.OK; MessageBox.Show(msg, caption, button, MessageBoxImage.Error); }); } } finally { await Dispatcher.BeginInvoke((Action)(() => Mouse.OverrideCursor = null)); ImportInProgress = false; } }); break; case MessageBoxResult.No: importTask = Task.Run((Action) delegate() { try { Dispatcher.BeginInvoke((Action)(() => Mouse.OverrideCursor = Cursors.AppStarting)); ExecuteLocalImport(); } catch (Exception ex) { Dispatcher.BeginInvoke((Action) delegate() { msg = "Contacts failed to load."; caption = "Import Error"; button = MessageBoxButton.OK; MessageBox.Show(msg, caption, button, MessageBoxImage.Error); }); } finally { Dispatcher.BeginInvoke((Action)(() => Mouse.OverrideCursor = null)); ImportInProgress = false; } }); break; case MessageBoxResult.Cancel: ImportInProgress = false; break; } } }
/// <summary> /// New login which handles remote configuration parsing. /// </summary> /// <param name="authId"></param> /// <param name="outboundProxy"></param> /// <param name="username"></param> /// <param name="addAccount"></param> private void Login_New(string authId, string outboundProxy, string username, bool addAccount) { //********************************************************************************************************************************* // Login in the VATRP application //********************************************************************************************************************************* VATRPCredential sipCredential = App.CurrentAccount.configuration.FindCredential("sip", username); if (sipCredential == null) { UserNameBox.Text = string.Empty; string msg = string.Format("VRS Account information is not present for {0}", Address); string caption = "Error finding your account"; MessageBoxButton button = MessageBoxButton.OK; MessageBox.Show(msg, caption, button, MessageBoxImage.Stop); return; } App.CurrentAccount.AuthID = sipCredential.username; App.CurrentAccount.OutboundProxy = outboundProxy; App.CurrentAccount.Username = sipCredential.username; App.CurrentAccount.RegistrationUser = sipCredential.username; App.CurrentAccount.Password = sipCredential.password; App.CurrentAccount.RegistrationPassword = sipCredential.password; App.CurrentAccount.ProxyHostname = Address; App.CurrentAccount.HostPort = HostPort; App.CurrentAccount.RememberPassword = RememberPasswordBox.IsChecked ?? false; bool autoLogin = AutoLoginBox.IsChecked ?? false; ServiceManager.Instance.ConfigurationService.Set(Configuration.ConfSection.GENERAL, Configuration.ConfEntry.AUTO_LOGIN, autoLogin); if (autoLogin) { App.CurrentAccount.StorePassword(ServiceManager.Instance.GetPWFile()); } var transportText = TransportComboBox.SelectedItem as TextBlock; if (transportText != null) { App.CurrentAccount.Transport = transportText.Text; } if (LoginWithOld) { App.CurrentAccount.LoginMethod = "Old"; } else { App.CurrentAccount.LoginMethod = "New"; } ServiceManager.Instance.ConfigurationService.Set(Configuration.ConfSection.GENERAL, Configuration.ConfEntry.ACCOUNT_IN_USE, App.CurrentAccount.AccountID); // cjm-aug17 if (addAccount) { ServiceManager.Instance.AccountService.AddAccount(App.CurrentAccount); } ServiceManager.Instance.AccountService.Save(); ServiceManager.Instance.RegisterNewAccount(App.CurrentAccount.AccountID); }