/// <summary> /// Creates a speaker profile /// </summary> /// <returns>A boolean indicating the success/failure of the process</returns> private async Task <bool> createProfile() { lblStatus.Content = "Creating Profile..."; try { //Stopwatch sw = Stopwatch.StartNew(); CreateProfileResponse response = await _serviceClient.CreateProfileAsync("en-us"); //sw.Stop(); //lblStatus.Content = "Profile Created, Elapsed Time: " + sw.Elapsed; _speakerId = response.ProfileId; Profile profile = await _serviceClient.GetProfileAsync(_speakerId); txtRemainingEnrollment.Text = profile.RemainingEnrollmentsCount.ToString(); lblStatus.Content = "Ready for recording."; return(true); } catch (CreateProfileException exception) { MessageBox.Show("Cannot create profile:", "Error", MessageBoxButton.OK); return(false); } catch (Exception gexp) { MessageBox.Show("Error: " + gexp.Message, "Error", MessageBoxButton.OK); return(false); } }
/// <summary> /// Function to create a new speaker profile /// </summary> /// <returns>Returns an ID (GUID) for the newly created speaker profile</returns> public async Task <Guid> CreateSpeakerProfile() { try { CreateProfileResponse response = await _speakerVerificationClient.CreateProfileAsync("en-US"); if (response == null) { RaiseOnVerificationError(new SpeakerVerificationErrorEventArgs("Failed to create speaker profile.")); return(Guid.Empty); } return(response.ProfileId); } catch (VerificationException ex) { RaiseOnVerificationError(new SpeakerVerificationErrorEventArgs($"Failed to create speaker profile: {ex.Message}")); return(Guid.Empty); } catch (Exception ex) { RaiseOnVerificationError(new SpeakerVerificationErrorEventArgs($"Failed to create speaker profile: {ex.Message}")); return(Guid.Empty); } }
/// <summary> /// Creates a speaker profile /// </summary> /// <returns>A boolean indicating the success/failure of the process</returns> private async Task <bool> createProfile() { setStatus("Creating Profile..."); try { Stopwatch sw = Stopwatch.StartNew(); CreateProfileResponse response = await _serviceClient.CreateProfileAsync("en-us"); sw.Stop(); setStatus("Profile Created, Elapsed Time: " + sw.Elapsed); IsolatedStorageHelper _storageHelper = IsolatedStorageHelper.getInstance(); _storageHelper.writeValue(MainWindow.SPEAKER_FILENAME, response.ProfileId.ToString()); _speakerId = response.ProfileId; Profile profile = await _serviceClient.GetProfileAsync(_speakerId); setDisplayText(profile.RemainingEnrollmentsCount.ToString(), ""); _storageHelper.writeValue(MainWindow.SPEAKER_ENROLLMENTS, profile.RemainingEnrollmentsCount.ToString()); _storageHelper.writeValue(MainWindow.SPEAKER_PHRASE_FILENAME, ""); _storageHelper.writeValue(MainWindow.SPEAKER_ENROLLMENT_STATUS, "Empty"); return(true); } catch (CreateProfileException exception) { setStatus("Cannot create profile: " + exception.Message); return(false); } catch (Exception gexp) { setStatus("Error: " + gexp.Message); return(false); } }
/// <summary> /// Creates a speaker profile /// </summary> /// <returns>A boolean indicating the success/failure of the process</returns> private async Task <bool> createProfile() { setStatus("Creating Profile..."); try { Stopwatch sw = Stopwatch.StartNew(); CreateProfileResponse response = await _serviceClient.CreateProfileAsync("en-us"); sw.Stop(); setStatus("Profile Created, Elapsed Time: " + sw.Elapsed); IsolatedStorageHelper _storageHelper = IsolatedStorageHelper.getInstance(); _storageHelper.writeValue(MainWindow.SPEAKER_FILENAME, response.ProfileId.ToString()); _speakerId = response.ProfileId; return(true); } catch (CreateProfileException exception) { setStatus("Cannot create profile: " + exception.Message); return(false); } catch (Exception gexp) { setStatus("Error: " + gexp.Message); return(false); } }
public async Task <Guid> CreateProfile() { try { //Create prifile for the specified language CreateProfileResponse response = await serviceClient.CreateProfileAsync("en-us"); speakerId = response.ProfileId; profile = await serviceClient.GetProfileAsync(speakerId); Debug.WriteLine("Profile Created with SpekaerID: " + speakerId); profileCreated = true; return(speakerId); } catch (Microsoft.ProjectOxford.SpeakerRecognition.Contract.CreateProfileException e) { Debug.WriteLine("Couldn't create Profile in createProfile(): " + e.Message); Synthesizer.Speak("Something went wrong. Go back and try again."); profileCreated = false; return(Guid.Empty); } catch (Exception e) { Debug.WriteLine("Couldn't create Profile in createProfile(). Error: " + e.Message); Synthesizer.Speak("Something went wrong. Go back an try again."); profileCreated = false; return(Guid.Empty); } }
private async void _addBtn_Click(object sender, RoutedEventArgs e) { MainWindow window = (MainWindow)Application.Current.MainWindow; try { window.Log("Creating Speaker Profile..."); CreateProfileResponse creationResponse = await _serviceClient.CreateProfileAsync(_localeCmb.Text); window.Log("Speaker Profile Created."); window.Log("Retrieving The Created Profile..."); Profile profile = await _serviceClient.GetProfileAsync(creationResponse.ProfileId); window.Log("Speaker Profile Retrieved."); SpeakersListPage.SpeakersList.AddSpeaker(profile); } catch (CreateProfileException ex) { window.Log("Profile Creation Error: " + ex.Message); } catch (GetProfileException ex) { window.Log("Error Retrieving The Profile: " + ex.Message); } catch (Exception ex) { window.Log("Error: " + ex.Message); } }
private bool CreateProfileSync(string scenario, out string profileResourceId) { //1. CreateProfile, create a new profile and return its resource id. MsnServiceState serviceState = new MsnServiceState(scenario, "CreateProfile", false); StorageService storageService = (StorageService)CreateService(MsnServiceType.Storage, serviceState); CreateProfileRequestType createRequest = new CreateProfileRequestType(); createRequest.profile = new CreateProfileRequestTypeProfile(); createRequest.profile.ExpressionProfile = new ExpressionProfile(); createRequest.profile.ExpressionProfile.PersonalStatus = ""; createRequest.profile.ExpressionProfile.RoleDefinitionName = "ExpressionProfileDefault"; try { ChangeCacheKeyAndPreferredHostForSpecifiedMethod(storageService, MsnServiceType.Storage, serviceState, createRequest); CreateProfileResponse createResponse = storageService.CreateProfile(createRequest); profileResourceId = createResponse.CreateProfileResult; NSMessageHandler.ContactService.Deltas.Profile.ResourceID = profileResourceId; NSMessageHandler.ContactService.Deltas.Save(true); } catch (Exception ex) { OnServiceOperationFailed(storageService, new ServiceOperationFailedEventArgs("CreateProfile", ex)); Trace.WriteLineIf(Settings.TraceSwitch.TraceError, "CreateProfile error: " + ex.Message, GetType().Name); profileResourceId = string.Empty; return(false); } return(true); }
private async void btnCreateProfile_Click(object sender, RoutedEventArgs e) { try { CreateProfileResponse response = await _serviceClient.CreateProfileAsync("en-us"); txtInfo.Text = "Profile Created: " + response.ProfileId; } catch { } await GetProfiles(); }
private void EnrollSpeaker(Stream stream) { // Reset pointer stream.Seek(0, SeekOrigin.Begin); SpeakerIdentificationServiceClient speakerIDClient = new SpeakerIdentificationServiceClient("c6b005dcf13e45b6a91485d38763277b"); //Creating Speaker Profile... CreateProfileResponse creationResponse = speakerIDClient.CreateProfileAsync("en-US").Result; //Speaker Profile Created. //Retrieving The Created Profile... Profile profile = speakerIDClient.GetProfileAsync(creationResponse.ProfileId).Result; //Speaker Profile Retrieved." //Enrolling Speaker OperationLocation processPollingLocation = speakerIDClient.EnrollAsync(stream, profile.ProfileId, false).Result; EnrollmentOperation enrollmentResult; int numOfRetries = 10; TimeSpan timeBetweenRetries = TimeSpan.FromSeconds(5.0); while (numOfRetries > 0) { Task.Delay(timeBetweenRetries); enrollmentResult = speakerIDClient.CheckEnrollmentStatusAsync(processPollingLocation).Result; if (enrollmentResult.Status == Status.Succeeded) { break; } else if (enrollmentResult.Status == Status.Failed) { throw new EnrollmentException(enrollmentResult.Message); } numOfRetries--; } if (numOfRetries <= 0) { throw new EnrollmentException("Enrollment operation timeout."); } //Enrollment Done. // Store profile in memory cache ObjectCache memCache = MemoryCache.Default; var profiles = memCache.Get("SpeakerProfiles") != null?memCache.Get("SpeakerProfiles") as List <Profile> : new List <Profile>(); memCache.Remove("SpeakerProfiles"); memCache.Add("SpeakerProfiles", profiles, DateTimeOffset.UtcNow.AddHours(2)); }
public async Task CreateProfileCommandTestAsync(string identityUserId, CreateProfileResponse result) { CreateProfileCommand request = new CreateProfileCommand { IdentityUserId = identityUserId, }; CreateProfileCommandHandler handler = new CreateProfileCommandHandler(_createFixture.Context); var expectedResult = await handler.Handle(request, new CancellationToken()); Assert.Equal(expectedResult.IsSuccessful, result.IsSuccessful); if (result.IsSuccessful) { Profile profile = _createFixture.Context.Profiles.Find(expectedResult.Id); Assert.Equal(profile?.IdentityUserId, identityUserId); } Assert.Equal(expectedResult.Message, result.Message); }
public async void voicetoprofile(byte[] data, string filename) { try { SpeakerIdentificationServiceClient _serviceClient = new SpeakerIdentificationServiceClient("xxxxxxxxxxxxxxxxxxxxxxx"); CreateProfileResponse creationResponse = await _serviceClient.CreateProfileAsync(name.Text.ToString()); Profile profile = await _serviceClient.GetProfileAsync(creationResponse.ProfileId); //SpeakersListPage.SpeakersList.AddSpeaker(profile); OperationLocation processPollingLocation; using (Stream audioStream = new MemoryStream(data)) { //_selectedFile = ""; processPollingLocation = await _serviceClient.EnrollAsync(audioStream, profile.ProfileId); } EnrollmentOperation enrollmentResult; int numOfRetries = 10; TimeSpan timeBetweenRetries = TimeSpan.FromSeconds(5.0); while (numOfRetries > 0) { await Task.Delay(timeBetweenRetries); enrollmentResult = await _serviceClient.CheckEnrollmentStatusAsync(processPollingLocation); if (enrollmentResult.Status == Status.Succeeded) { break; } else if (enrollmentResult.Status == Status.Failed) { throw new EnrollmentException(enrollmentResult.Message); } numOfRetries--; } if (numOfRetries <= 0) { throw new EnrollmentException("Enrollment operation timeout."); } } catch (Exception ex) { throw ex; } }
/// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context) { CreateProfileResponse response = new CreateProfileResponse(); context.Read(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("ProfileArn", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.ProfileArn = unmarshaller.Unmarshall(context); continue; } } return(response); }
/// <summary> /// Initialize the speaker information /// </summary> private async void initializeSpeaker() { try { CreateProfileResponse response = await verServiceClient.CreateProfileAsync("en-us"); Console.WriteLine("Profile id :" + response.ProfileId.ToString()); _speakerId = response.ProfileId; //_speakerId = Guid.Parse("72431ee5-d02a-4c6c-985c-1217088ed2ec"); Profile profile = await verServiceClient.GetProfileAsync(_speakerId); remEnrollText.Text = profile.RemainingEnrollmentsCount.ToString(); verPhraseText = null; refreshPhrases(); } catch (Exception ex) { Console.WriteLine("Error : " + ex.Message); } }
private async void CreateProfile() { progressbar.Visibility = Visibility.Visible; try { LoggingMsg("Creating Speaker Profile..."); CreateProfileResponse creationResponse = await _serviceClient.CreateProfileAsync("en-us"); LoggingMsg("Speaker Profile Created."); VoiceProfileId = creationResponse.verificationProfileId; settings.Values["voiceid"] = VoiceProfileId; string phrase = await GetPhrase(); PhraseTB.Text = phrase; if (phrase != null) { UpdateUserVoice(VoiceProfileId, phrase); } LoggingMsg("Voice Id: " + VoiceProfileId); LoggingMsg("Chosen phrase: " + phrase); LoggingMsg("Retreiving The Created Profile..."); UpdateProfileStatus(VoiceProfileId); LoggingMsg("Speaker Profile Retreived."); ProfileCB.IsChecked = true; progressbar.Visibility = Visibility.Collapsed; CreateProfileBtn.Visibility = Visibility.Collapsed; EnrollBtn.Visibility = Visibility.Visible; } catch (Exception ex) { progressbar.Visibility = Visibility.Collapsed; LoggingMsg("Create profile error: " + ex.Message); } }
//This Creates a new speaker in the database //INPUT: //OUTPUT: functionResult public async Task <functionResult> addSpeaker() { functionResult result = new functionResult(); //If the _serviceClient is null, create it with the subsciption key stored if (_serviceClient == null) { _serviceClient = new SpeakerIdentificationServiceClient(_subscriptionKey); } try { //Create the new profile and assign it to the Profile Tag CreateProfileResponse creationResponse = await _serviceClient.CreateProfileAsync("en-us"); Profile profile = await _serviceClient.GetProfileAsync(creationResponse.ProfileId); result.Result = true; result.Message = profile.ProfileId.ToString(); } catch (CreateProfileException ex) { result.Result = false; result.Message = "Error Creating The Profile: " + ex.Message.ToString(); } catch (GetProfileException ex) { result.Result = false; result.Message = "Error Retrieving The Profile: " + ex.Message.ToString(); } catch (Exception ex) { result.Result = false; result.Message = "Error: " + ex.Message.ToString(); } return(result); }
public async Task <Guid> CreateNewProfile(string locale) { try { CreateProfileResponse creationResponse = await serviceClient.CreateProfileAsync(locale); return(creationResponse.ProfileId); } catch (CreateProfileException ex) { Console.WriteLine("Profile Creation Error: " + ex.Message); throw; } catch (GetProfileException ex) { Console.WriteLine("Error Retrieving The Profile: " + ex.Message); throw; } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); throw; } }
private Payment CreatePayment(APIContext apiContext, string redirectUrl, CreateProfileResponse profile) { payment = null; //similar to credit card create itemlist and add item objects to it var itemList = new ItemList() { items = new List <Item>() }; foreach (CartItem cart in CommonConstants.listCart) { itemList.items.Add(new Item() { name = cart.Product.Name, currency = "USD", price = (cart.Product.Price - cart.Product.Price * cart.Product.Discount / 100).ToString(), quantity = cart.Quantity.ToString() }); } var payer = new Payer() { payment_method = "paypal", }; // Configure Redirect Urls here with RedirectUrls object var redirUrls = new RedirectUrls() { cancel_url = Url.Action("Index", "Cart", null, this.Request.Url.Scheme), return_url = redirectUrl }; // similar as we did for credit card, do here and create details object var details = new Details() { tax = "0", shipping = "0", subtotal = CommonConstants.listCart.Sum(x => x.Quantity * (x.Product.Price - x.Product.Price * x.Product.Discount / 100)).ToString(), }; // similar as we did for credit card, do here and create amount object var amount = new Amount() { currency = "USD", total = CommonConstants.listCart.Sum(x => x.Quantity * (x.Product.Price - x.Product.Price * x.Product.Discount / 100)).ToString(), // Total must be equal to sum of shipping, tax and subtotal. details = details }; var transactionList = new List <Transaction>(); transactionList.Add(new Transaction() { description = "Transaction description.", invoice_number = "your invoice number", amount = amount, item_list = itemList }); payment = new Payment() { experience_profile_id = profile.id, intent = "sale", payer = payer, transactions = transactionList, redirect_urls = redirUrls }; // Create a payment using a APIContext return(this.payment.Create(apiContext)); }
/// <summary> /// Creates Web Experience profile using portal branding and payment configuration. /// </summary> /// <param name="paymentConfig">The Payment configuration.</param> /// <param name="brandConfig">The branding configuration.</param> /// <param name="countryIso2Code">The locale code used by the web experience profile. Example-US.</param> /// <returns>The created web experience profile id.</returns> public string CreateWebExperienceProfile(PaymentConfiguration paymentConfig, BrandingConfiguration brandConfig, string countryIso2Code) { try { Dictionary <string, string> configMap = new Dictionary <string, string> { { "clientId", paymentConfig.ClientId }, { "clientSecret", paymentConfig.ClientSecret }, { "mode", paymentConfig.AccountType }, { "connectionTimeout", "120000" } }; string accessToken = new OAuthTokenCredential(configMap).GetAccessToken(); APIContext apiContext = new APIContext(accessToken) { Config = configMap }; // Pickup logo & brand name from branding configuration. // create the web experience profile. WebProfile profile = new WebProfile { name = Guid.NewGuid().ToString(), presentation = new Presentation { brand_name = brandConfig.OrganizationName, logo_image = brandConfig.HeaderImage?.ToString(), locale_code = countryIso2Code }, input_fields = new InputFields() { address_override = 1, allow_note = false, no_shipping = 1 }, flow_config = new FlowConfig() { landing_page_type = "billing" } }; CreateProfileResponse createdProfile = profile.Create(apiContext); // Now that new experience profile is created hence delete the older one. if (!string.IsNullOrWhiteSpace(paymentConfig.WebExperienceProfileId)) { try { WebProfile existingWebProfile = WebProfile.Get(apiContext, paymentConfig.WebExperienceProfileId); existingWebProfile.Delete(apiContext); } catch { } } return(createdProfile.id); } catch (PayPalException paypalException) { if (paypalException is IdentityException) { // thrown when API Context couldn't be setup. IdentityException identityFailure = paypalException as IdentityException; IdentityError failureDetails = identityFailure.Details; if (failureDetails != null && failureDetails.error.Equals("invalid_client", StringComparison.InvariantCultureIgnoreCase)) { throw new PartnerDomainException(ErrorCode.PaymentGatewayIdentityFailureDuringConfiguration).AddDetail("ErrorMessage", Resources.PaymentGatewayIdentityFailureDuringConfiguration); } } // if this is not an identity exception rather some other issue. throw new PartnerDomainException(ErrorCode.PaymentGatewayFailure).AddDetail("ErrorMessage", paypalException.Message); } }
//To make the user's profile. private async void registerBtn_Click(object sender, RoutedEventArgs e) { try { registerBtn.IsEnabled = false; var faceServiceClient = new FaceServiceClient(faceAPISubscriptionKey); registerForm = new RegisterForm(); registerForm.ShowDialog(); if (registerForm.textBox.Text == "") { speechSynthesizer.SpeakAsync("Please enter your name."); var result = MessageBox.Show("Please Enter your Name."); if (result == MessageBoxResult.OK) { registerForm = new RegisterForm(); registerForm.ShowDialog(); } registerBtn.IsEnabled = true; return; } else { userName = registerForm.textBox.Text; userDirPath = dirPath + userName + "\\"; bool exist = Directory.Exists(dirPath + userName); if (!exist) { Directory.CreateDirectory(dirPath + userName); accountBal = 10000; //Insert some amount in database along with username. conn.Open(); SqlCommand cmd = conn.CreateCommand(); cmd.CommandType = System.Data.CommandType.Text; cmd.CommandText = "Insert into AccountDetails (AccountBalance,CustomerName) values ('" + accountBal + "' , '" + userName + "')"; cmd.ExecuteNonQuery(); conn.Close(); Console.WriteLine("Record Successfully Inserted"); //Fetch the accountno from AccountDetails by using username. conn.Open(); SqlCommand cmdd = conn.CreateCommand(); cmdd.CommandType = System.Data.CommandType.Text; cmdd.CommandText = "Select AccountNo From AccountDetails where CustomerName = '" + userName + "'"; dr = cmdd.ExecuteReader(); if (dr.HasRows) { while (dr.Read()) { accountNo = int.Parse(dr[0].ToString()); } } dr.Close(); //Insert this accountno into AuthenticationDetails table. SqlCommand cmd1 = conn.CreateCommand(); cmd1.CommandType = System.Data.CommandType.Text; cmd1.CommandText = "Insert into AuthenticationDetails (AccountNo) values ('" + accountNo + "')"; cmd1.ExecuteNonQuery(); conn.Close(); Console.WriteLine("Record Successfully Inserted"); await Task.Delay(2000); speechSynthesizer.SpeakAsync("Ok, Now you need to capture your three photos."); Title = string.Format("Ready...Now click your three photos."); } else { registerBtn.IsEnabled = true; SqlCommand cmd4 = conn.CreateCommand(); cmd4.CommandType = System.Data.CommandType.Text; cmd4.CommandText = "Select * From AuthenticationDetails where FaceId = '" + faceid + "'"; dr = cmd.ExecuteReader(); if (dr.Read()) { speechSynthesizer.SpeakAsync("You already registered your data."); Title = string.Format(""); return; } else { Console.WriteLine("Sorry try with another name"); speechSynthesizer.SpeakAsync("Try with another Name."); registerBtn.IsEnabled = true; return; } } } //creating speaker profile with en-us locality. SpeakerIdentificationServiceClient _serviceClient = new SpeakerIdentificationServiceClient(speakerAPISubscriptionKey); creationResponse = await _serviceClient.CreateProfileAsync("en-US"); var tag = System.IO.Path.GetFileName(dirPath + userName); Console.WriteLine("FileName : {0}", tag); p.PersonName = tag; // Call create person REST API, the new create person id will be returned Console.WriteLine("Request: Creating person \"{0}\"", p.PersonName); p.PersonId = (await faceServiceClient.CreatePersonAsync(GroupName, p.PersonName)).PersonId.ToString(); Console.WriteLine("Person Id is : {0}", p.PersonId); faceid = p.PersonId.ToString(); Console.WriteLine("Response: Success. Person \"{0}\" (PersonID:{1}) created", p.PersonName, p.PersonId.ToString()); await Task.Delay(3000); captureBtn.IsEnabled = true; GC.Collect(); } catch (Exception ex) { registerBtn.IsEnabled = true; MessageBox.Show(ex.Message); } }