static private EWSConnection ConnectToEWS(Credentials credentials) { Logger.DebugFormat("Initializing FolderMailboxManager for email adderss {0}", credentials.EmailAddress); var exchangeService = new ExchangeService(ExchangeVersion.Exchange2010_SP1) { Credentials = new WebCredentials(credentials.UserName, credentials.Password), Timeout = 60000 }; exchangeService.AutodiscoverUrl( credentials.EmailAddress, x => { Logger.DebugFormat("Following redirection for EWS autodiscover: {0}", x); return true; } ); Logger.DebugFormat("Service URL: {0}", exchangeService.Url); return new EWSConnection() { Service = exchangeService, Router = new RecipientsMailboxManagerRouter( new EWSMailFolder(Folder.Bind(exchangeService, WellKnownFolderName.Inbox))) }; }
public void If_username_was_given_with_embedded_domain_the_domain_field_must_be_ignored() { var credentialsWithDomainEmbeddedInUsernameAndInDomainField = new Credentials(".", @"10.1.1.1\oval", string.Empty, string.Empty); AssertCredentials(credentialsWithDomainEmbeddedInUsernameAndInDomainField, "10.1.1.1", "oval", string.Empty); }
//public delegate void TournamentsUpdatedEventHandler(object sender, EventArgs e); //protected event TournamentsUpdatedEventHandler TournamentsUpdatedEvent public TabViewModelBase() { if(Credentials == null) { Credentials = new Credentials(); } }
public void GetResultDocument_NotEmptyDoc() { using (MqServiceClient mq = new MqServiceClient()) { //Задаём статус направления "Зарегистрировано в РЕГИЗ.УО" Referral referral = (new SetData()).MinRegister(); Credentials cr = new Credentials { Organization = idLpu, Token = guid }; var result = mq.Register(cr, referral); //Задаём статус "Выдано пациенту" referral = (new SetData()).SetStatus_PatientDocumentIssue(result.IdMq); var res2 = mq.UpdateFromSourcedMo(cr, referral); //Задаём статус "Выделена единица ресурса, целевой МО назначена дата приема" referral = (new SetData()).MinChangePlannedResource(result.IdMq); var res3 = mq.ChangePlannedResource(cr, referral); //Задаём статус "Начато оказание медицинской помощи в целевой МО" referral = (new SetData()).SetStatus_HealthCareStart(result.IdMq); var res4 = mq.UpdateFromTargetMo(cr, referral); //Задаём статус "Завершено оказание медицинской помощи в целевой МО" referral = (new SetData()).SetStatus_HealthCareEnd(result.IdMq); var res5 = mq.UpdateFromTargetMo(cr, referral); referral = (new SetData()).GetResultDocument(result.IdMq); var res6 = mq.GetResultDocument(cr, referral); } if (Global.errors == "") Assert.Pass(); else Assert.Fail(Global.errors); }
public void Should_be_possible_be_possible_to_get_all_credential_informations() { var credentials = new Credentials("mss", "lfernandes", "123456\\b", "RooT"); AssertCredentials(credentials, "mss", "lfernandes", "RooT"); Assert.AreEqual("123456\\b", credentials.GetPassword(), "An unexpected password value was found."); }
public void MinHealthCareEnd() { using (MqServiceClient mq = new MqServiceClient()) { Credentials cr = new Credentials { Organization = idLpu, Token = guid }; Referral referral = (new SetData()).MinRegister(); var result = mq.Register(cr, referral); //"Выдано пациенту" referral = (new SetData()).MinPatientDocumentIssue(result.IdMq); var res2 = mq.PatientDocumentIssue(cr, referral); //"Выделена единица ресурса, целевой МО назначена дата приема" referral = (new SetData()).MinChangePlannedResource(result.IdMq); var res3 = mq.ChangePlannedResource(cr, referral); //"Начато оказание медицинской помощи в целевой МО" referral = (new SetData()).MinHealthCareStart(result.IdMq); var res4 = mq.HealthCareStart(cr, referral); referral = (new SetData()).MinHealthCareEnd(result.IdMq); var res5 = mq.HealthCareEnd(cr, referral); } if (Global.errors == "") Assert.Pass(); else Assert.Fail(Global.errors); }
public void FullChangeTargetMO() { using (TestMqServiceClient mq = new TestMqServiceClient()) { Credentials cr = new Credentials { Organization = idLpu, Token = guid }; Referral referral = (new SetData()).MinRegister(); referral.ReferralSurvey = new Survey { SurveyOrgan = ReferralData.survey.SurveyOrgan, SurveyType = ReferralData.survey.SurveyType }; referral.Target = new ReferralTarget { Lpu = ReferralData.referralTarget.Lpu }; var result = mq.Register(cr, referral); //Изменяем целевую МО referral = (new SetData()).FullSetOrChangeTargetMO(result.IdMq); var res2 = mq.SetOrChangeTargetMo(cr, referral); } if (Global.errors == "") Assert.Pass(); else Assert.Fail(Global.errors); }
/** The validators to check the Credentials. */ //@NotNull //private Validator validator = Validation.buildDefaultValidatorFactory().getValidator(); /** * @throws IllegalArgumentException if the Credentials are null or if given * invalid credentials. */ public string createTicketGrantingTicket(Credentials credentials) { //Assert.notNull(credentials, "credentials cannot be null"); this.checkForErrors(credentials); return this.centralAuthenticationService.createTicketGrantingTicket(credentials); }
public void UpdateFromSourcedMo_Agreed() { using (TestMqServiceClient mq = new TestMqServiceClient()) { Referral referral = (new SetData()).MinRegister(); Credentials cr = new Credentials { Organization = idLpu, Token = guid }; var result = mq.Register(cr, referral); //обновляем данные referral = (new SetData()).MinUpdateFromSourcedMo(result.IdMq); referral.EventsInfo = new EventsInfo { Source = new EventSource { IsReferralReviewed = true, ReferralCreateDate = ReferralData.eventsInfo.Source.ReferralCreateDate, ReferralReviewDate = ReferralData.eventsInfo.Source.ReferralReviewDate } }; var updateResult = mq.UpdateFromSourcedMo(cr, referral); } if (Global.errors == "") Assert.Pass(); else Assert.Fail(Global.errors); }
protected bool PerformOAuth(string login, string mastertoken) { const string client_sig = "38918a453d07199354f8b19af05ec6562ced5788"; Dictionary<string, string> oauth; _credentials = new Credentials(); GPSOAuthClient gpsoauth = new GPSOAuthClient(login, mastertoken); gpsoauth.Proxy = Proxy; try { oauth = gpsoauth.PerformOAuth("sj", "com.google.android.music", client_sig); } catch(WebException error) { ThrowError("Authentication failed!", error); return false; } if (oauth.ContainsKey("SID") && oauth.ContainsKey("LSID") && oauth.ContainsKey("Auth")) { _credentials.SID = oauth["SID"]; _credentials.LSID = oauth["LSID"]; _credentials.Auth = oauth["Auth"]; } else { ThrowError("Login failed!"); return false; } return true; }
private Credentials GetCredentials() { var credentials = new Credentials(); try { if ( UserName.IsNullOrEmptyOrWhiteSpace() ) { ErrorMessage = "The username field should not be empty"; return null; } if (TokenData.IsNullOrEmptyOrWhiteSpace()) { ErrorMessage = AppResources.InvalidToken; return null; } var tokenParts = TokenData.Split('/'); if ( tokenParts.Length != 2 || tokenParts[0].IsNullOrEmptyOrWhiteSpace() || tokenParts[1].IsNullOrEmptyOrWhiteSpace() ) { ErrorMessage = AppResources.InvalidToken; return null; } var identity = tokenParts[0]; var token = tokenParts[1]; credentials.Username = UserName; credentials.Token = token; credentials.Identity = identity; } catch ( Exception ) { return null; } return credentials; }
public EWSConnection GetConnection(Credentials credentials) { Logger.InfoFormat("Getting EWS connection for mailbox."); EWSConnection ewsConnection; if (!_enableConnectionCaching) { Logger.InfoFormat("Creating non-cached connection for mailbox..."); ewsConnection = ConnectToEWS(credentials); } else { lock (_cachedConnections) { var key = GetKeyFromCredentials(credentials); if (_cachedConnections.ContainsKey(key)) { Logger.InfoFormat("Connection for '{0}' already exists. Retrieving from cache.", key); ewsConnection = _cachedConnections[key]; } else { Logger.InfoFormat("Creating cached connection for '{0}'...", key); _cachedConnections[key] = ConnectToEWS(credentials); ewsConnection = _cachedConnections[key]; } } } Logger.InfoFormat("Completed getting connection for mailbox."); return ewsConnection; }
private void Init() { if (ConfigurationReader == null) { ConfigurationReader = new zVirtualScenesHub.API.Configuration.WindowsStorageConfigurationReader(); } try { Credentials = new Credentials(); var profilesIndex = ConfigurationReader.ReadSetting<string>("Profiles").Result; if (!string.IsNullOrEmpty(profilesIndex)) { Credentials = NewtonSerializer<Credentials>.FromJSON<Credentials>(profilesIndex); foreach (var c in Credentials) { if (c.Default) { DefaultCredential = c; break; } } } } catch (Exception) { } }
/** * @throws IllegalArgumentException if a mapping cannot be found. * @see org.jasig.cas.authentication.AuthenticationManager#authenticate(org.jasig.cas.authentication.principal.Credentials) */ //@Override protected override Pair<AuthenticationHandler, Principal> authenticateAndObtainPrincipal(Credentials credentials) { Type credentialsClass = credentials.GetType(); DirectAuthenticationHandlerMappingHolder d = this.credentialsMapping.FirstOrDefault(x => x.Key == credentialsClass).Value; ////Assert.notNull(d, "no mapping found for: " + credentialsClass.getName()); string handlerName = d.getAuthenticationHandler().GetType().FullName; bool authenticated = false; try { authenticated = d.getAuthenticationHandler().authenticate(credentials); } catch (Exception e) { this.handleError(handlerName, credentials, e); } if (!authenticated) { //log.info("{} failed to authenticate {}", handlerName, credentials); throw BadCredentialsAuthenticationException.ERROR; } //log.info("{} successfully authenticated {}", handlerName, credentials); Principal p = d.getCredentialsToPrincipalResolver().resolvePrincipal(credentials); return new Pair<AuthenticationHandler, Principal>(d.getAuthenticationHandler(), p); }
public Authenticator(Credentials credentials, IXmlSerializer serializer) { Ensure.ArgumentNotNull(credentials, "credentials"); Credentials = credentials; _valueProvider = new SignatureValueProvider(serializer); }
public void MinUpdateMedServiceProfile() { using (MqServiceClient mq = new MqServiceClient()) { Credentials cr = new Credentials { Organization = idLpu, Token = guid }; ProfileMedService medServ = (new SetData()).MinUpdateMedServiceProfile(); mq.UpdateMedServiceProfile(cr, medServ); Options options = new Options { DateReport = OptionData.options.DateReport, Target = new ReferralTarget { Lpu = new Coding { Code = idLpu, System = Dictionary.MO, Version = "1" } }, ReferralInfo = new ReferralInfo { ProfileMedService = medServ.IdProfileMedService } }; var result = mq.GetQueueInfo(cr, options); } if (Global.errors == "") Assert.Pass(); else Assert.Fail(Global.errors); }
public bool TryAuthentifcate(Credentials credentials, out Model.UserIdentity identity) { identity = null; using (var database = DatabaseFactory.GetDatabase()) { User user = database.Query<User>().FirstOrDefault(x => x.Name == credentials.UserName); // Check if there is a User: if (user == null) { return false; } // Make sure the Hashed Passwords match: if (user.PasswordHash != cryptoService.ComputeHash(credentials.Password, user.PasswordSalt)) { return false; } // We got a User, now obtain his claims from DB: IList<Claim> claims = database.Fetch<Claim>(@" select c.* from auth.user u inner join auth.user_claim uc on u.user_id = uc.user_id inner join auth.claim c on uc.claim_id = c.claim_id where u.user_id = @0", user.Id); // And return the UserIdentity: identity = Convert(user, claims); return true; } }
public MqResult Cancellation(Credentials cr, Referral r) { try { TestReferral tr = TestReferral.BuildReferralFromDataBaseData(r.ReferralInfo.IdMq); tr.evInfo.cancellation = new TestCancellation(r.EventsInfo.Cancellation); MqResult x = client.Cancellation(cr, r); if (tr != TestReferral.BuildReferralFromDataBaseData(x.IdMq)) { Global.errors1.Add("Несовпадение"); Global.errors1.AddRange(Global.errors2); } return x; } catch (System.ServiceModel.FaultException<MqTests.WebReference.MqFault[]> e) { getErrors(e.Detail); return null; } catch (System.ServiceModel.FaultException<MqTests.WebReference.MqFault> e) { Global.errors1.Add(e.Detail.PropertyName + " - " + e.Detail.Message); return null; } }
/// <summary> /// Clears login in AppSettings (removes cookie, password, set filter to default value) /// </summary> /// <param name="creds"></param> private void ClearLogin(Credentials creds) { creds.IsLoggedIn = false; creds.Password = string.Empty; AppSettings.CookieString = string.Empty; AppSettings.Filter = 0; }
// Use this for initialization void Start() { // First create the credentials object for the account. In this example email credentials are used Credentials credentials = new Credentials(); credentials.email = email; credentials.password = password; // Create the user account with some profile data and attach it to the credentials created in the previous block GDUser user = new GDUser(); user.credentials = credentials; user.profile["email"] = email; user.profile["name"] = ""; user.profile["color"] = ""; user.profile["hobby"] = ""; user.profile["film"] = ""; user.profile["age"] = 0; user.profile["lvl"] = 1; user.profile["wonAttr"] = 0; user.profile ["friends"] = new Dictionary<string, object> (); // Make the request to Gamedonia Backend to create the account and process the result in a block. GamedoniaUsers.CreateUser(user, delegate (bool success){ if (success){ Debug.Log("Success"); } else{ Debug.Log("Fail"); } }); }
IDisposable ISupportAuthentication.WithCredentials(Credentials credentials) { var auth = _navigator as ISupportAuthentication; return auth == null ? new ActionOnDispose(() => { }) : auth.WithCredentials(credentials); }
public static void Test(string userName, string password, string sport) { ICredentials credentials = new Credentials { UserName = userName, Password = password }; var theSession = SessionFactory.CreateSession(new Uri(_url), credentials); //Get the Unified Data Service var theService = theSession.GetService("UnifiedDataAPI"); var theFeature = theService.GetFeature(sport); //Get all the Resources (Fixtures) for the given sport var theResources = theFeature.GetResources(); //Grab the first one, this is only an example after all var theResource = theResources.First(); //Get the snapshot var theSnapshot = theResource.GetSnapshot(); var fixtureSnapshot = JsonConvert.DeserializeObject<Fixture>(theSnapshot, new JsonSerializerSettings { Converters = new List<JsonConverter> { new IsoDateTimeConverter() }, NullValueHandling = NullValueHandling.Ignore }); System.Console.WriteLine(theSnapshot); theResource.StreamConnected += (sender, args) => System.Console.WriteLine("Stream Connected"); theResource.StreamEvent += (sender, args) => System.Console.WriteLine(args.Update); theResource.StreamDisconnected += (sender, args) => System.Console.WriteLine("Stream Disconnected"); //Start Streaming theResource.StartStreaming(); //Wait 60 seconds, then stop the Stream Thread.Sleep(600000); theResource.StopStreaming(); }
public void GetGeoding() { var credentials = new Credentials(token); var client = new MapboxClient(credentials); var result = client.GeocodingApi.SearchGeocoding("coventry"); Console.WriteLine(result.Result); }
public void StatusAgreedInTargedMO() { using (TestMqServiceClient mq = new TestMqServiceClient()) { //Задаём статус направления "Зарегистрировано в РЕГИЗ.УО" Referral referral = (new SetData()).MinRegister(); Credentials cr = new Credentials { Organization = idLpu, Token = guid }; var result = mq.Register(cr, referral); //Задаём статус "Выдано пациенту" referral = (new SetData()).SetStatus_PatientDocumentIssue(result.IdMq); var res2 = mq.UpdateFromSourcedMo(cr, referral); //Задаём статус "Признано обоснованным в целевой МО" referral = (new SetData()).SetStatus_AgreedInTargedMO(result.IdMq); var res3 = mq.UpdateFromTargetMo(cr, referral); if (res3.MqReferralStatus.Code != "4") Global.errors1.Add("Неверный статус:" + res3.MqReferralStatus.Code + ""); } if (Global.errors == "") Assert.Pass(); else Assert.Fail(Global.errors); }
/// <summary> /// Construct a new RestEndpointStrategy instance. /// </summary> /// <param name="endpoint">The API endpoint to connect to.</param> /// <param name="insecureSSL">Ignore SSL certificate errors.</param> /// <param name="authFile">The location of the authentication file. Default: working directory.</param> /// <param name="formatter">The formatter to use to format the payloads.</param> public RestEndpointStrategy( string endpoint, bool insecureSSL, string authFile, JsonFormatter formatter ) { Log.Info( "Using REST endpoint strategy." ); PreferredFormatter = formatter; InsecureSSL = insecureSSL; try { AuthInfo = ReadFromAuthFile( authFile ); } catch( Exception ex ) { Log.ErrorFormat( "Problem with authentication file: {0}", ex.Message ); throw; } RecievedPayloads = new ConcurrentQueue<string>(); RetryTimer = new System.Timers.Timer(); RetryTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent); RetryTimer.Interval = TimeSpan.FromSeconds( 10.0 ).TotalMilliseconds; Endpoint = endpoint; EndpointUri = new Uri( Endpoint ); CheckConfiguration(); }
private void CredentialStoreTest(string url, string username, string password) { try { Uri uri = new Uri(url, UriKind.Absolute); Credentials writeCreds = new Credentials(username, password); Credentials readCreds = null; ICredentialStore priamryStore = new CredentialStore("prime-test"); priamryStore.WriteCredentials(uri, writeCreds); if (priamryStore.ReadCredentials(uri, out readCreds)) { Assert.AreEqual(writeCreds.Password, readCreds.Password, "Passwords did not match between written and read credentials"); Assert.AreEqual(writeCreds.Username, readCreds.Username, "Usernames did not match between written and read credentials"); } else { Assert.Fail("Failed to read credentials"); } priamryStore.DeleteCredentials(uri); Assert.IsFalse(priamryStore.ReadCredentials(uri, out readCreds), "Deleted credentials were read back"); } catch (Exception exception) { Assert.Fail(exception.Message); } }
public CredentialStore(Configuration.IConfigurationReader configurationReader = null) { ConfigurationReader = configurationReader; if (ConfigurationReader == null) { #if WINDOWS_PHONE ConfigurationReader = new Configuration.IsolatedStorageConfigurationReader(); #else ConfigurationReader = new Configuration.AppConfigConfigurationReader(); #endif } Credentials = new Credentials(); var profilesIndex = ConfigurationReader.ReadSetting<string>("Profiles"); if (!string.IsNullOrEmpty(profilesIndex)) { Credentials = Newtonsoft.Json.JsonConvert.DeserializeObject<Credentials>(profilesIndex); foreach (var c in Credentials) { if (c.Default) { DefaultCredential = c; break; } } } SetupDefault(); }
public void Equality() { Credentials oneA = new Credentials("a", "a", ServiceAccount.LocalService); Credentials oneB = new Credentials("a", "a", ServiceAccount.LocalService); Credentials two = new Credentials("2", "a", ServiceAccount.LocalService); Credentials three = new Credentials("a", "2", ServiceAccount.LocalService); Credentials four = new Credentials("a", "a", ServiceAccount.User); oneA.Equals(oneA) .ShouldBeTrue("instance equality"); oneA.Equals(oneB) .ShouldBeTrue("value equality"); oneA.Equals(two) .ShouldBeFalse("username"); oneA.Equals(three) .ShouldBeFalse("password"); oneA.Equals(four) .ShouldBeFalse("service account"); oneA.Equals(null) .ShouldBeFalse("null"); }
/// <summary> /// Opens a storage session with the storage server. /// </summary> /// <param name="depotId">The depot id.</param> /// <param name="depotVersion">The depot version.</param> /// <param name="cellId">The cell id.</param> /// <param name="credentials">The credentials.</param> /// <param name="doHandshake">Whether or not to send the handshake and reopen cell</param> /// <returns>A new StorageSession object for the session.</returns> public StorageSession OpenStorage( uint depotId, uint depotVersion, uint cellId, Credentials credentials, bool doHandshake = true ) { if (doHandshake) { bool bRet = this.HandshakeServer((ESteam2ServerType)7); if (!bRet) throw new Steam2Exception("Storage handshake with content server failed"); bRet = this.SendCommand( 0, // open storage cellId ); byte success = this.Socket.Reader.ReadByte(); if (success == 0) throw new Steam2Exception(string.Format("Unable to open storage depot for cellid {0}", cellId)); ushort bannerLen = NetHelpers.EndianSwap(this.Socket.Reader.ReadUInt16()); byte[] bannerData = this.Socket.Reader.ReadBytes(bannerLen); } return new StorageSession( this, depotId, depotVersion, credentials ); }
public bool Authenticate(Credentials credentials) { if (credentials.Expiry < DateTime.Now) return false; Credentials = credentials; return true; }
private SearchImages(Credentials credentials, string baseUrl, DelegatingHandler customHandler) : base(customHandler) { _customHandler = customHandler; Credentials = credentials; BaseUrl = baseUrl; }
private void LoadRequestDetails(Credentials creds, string requestid) { using (var webClient = new System.Net.WebClient()) { string rootUrl = System.Configuration.ConfigurationManager.AppSettings["webServiceRootUrl"].ToString(); string url = String.Format("{0}GetCoordinationRequestDetails?callsign={1}&password={2}&requestid={3}", rootUrl, creds.Username, creds.Password, requestid); string strJson = webClient.DownloadString(url); dynamic json = JsonConvert.DeserializeObject <dynamic>(strJson); lblAltitude.Text = json.Request.Altitude; lblAntennaHeight.Text = json.Request.AntennaHeight; lblID.Text = String.Format("Coordination Request #{0}{1}", json.Request.State, json.Request.ID); lblLatitude.Text = json.Request.Latitude; lblLongitude.Text = json.Request.Longitude; lblOutputFrequency.Text = json.Request.OutputFrequency; lblPower.Text = json.Request.OutputPower; lblRequestor.Text = String.Format("{0}, {1}", json.Request.Requestor.Name, json.Request.Requestor.Callsign); lblStatus.Text = json.Request.Status.Description; if (json.Request.Notes != null) { foreach (dynamic note in json.Request.Notes) { using (TableRow row = new TableRow()) { using (TableCell cell = new TableCell()) { cell.Text = String.Format("{0}, {1}", note.Note.User.Name, note.Note.User.Callsign); cell.HorizontalAlign = HorizontalAlign.Left; row.Cells.Add(cell); } using (TableCell cell = new TableCell()) { cell.Text = String.Format("{0}", note.Note.Timestamp); cell.HorizontalAlign = HorizontalAlign.Right; row.Cells.Add(cell); } tblNotes.Rows.Add(row); } using (TableRow row = new TableRow()) { TableCell cell = new TableCell(); cell.Text = note.Note.Text; cell.ColumnSpan = 2; row.Cells.Add(cell); tblNotes.Rows.Add(row); } } } if (json.Request.Workflow != null) { foreach (dynamic step in json.Request.Workflow) { using (TableRow row = new TableRow()) { using (TableCell cell = new TableCell()) { cell.Text = step.Step.State; row.Cells.Add(cell); } using (TableCell cell = new TableCell()) { cell.Text = step.Step.Status.Description; row.Cells.Add(cell); } using (TableCell cell = new TableCell()) { cell.Text = String.Format("{0}<div class='noteDate'>{1}</div>", step.Step.Note, step.Step.TimeStamp); row.Cells.Add(cell); } tblWorkflow.Rows.Add(row); } } } } }
public async Task <HttpOperationResponse <AnalyzeResult> > AnalyzeWithCustomModelWithHttpMessagesAsync2(System.Guid id, Stream formStream, IList <string> keys = default(IList <string>), Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken), string contentType = "application/pdf") { if (Endpoint == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Endpoint"); } if (formStream == null) { throw new ValidationException(ValidationRules.CannotBeNull, "formStream"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("id", id); tracingParameters.Add("keys", keys); tracingParameters.Add("formStream", formStream); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "AnalyzeWithCustomModel", tracingParameters); } // Construct URL var _baseUrl = BaseUri; var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "custom/models/{id}/analyze"; _url = _url.Replace("{Endpoint}", Endpoint); _url = _url.Replace("{id}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(id, SerializationSettings).Trim('"'))); List <string> _queryParameters = new List <string>(); if (keys != null) { _queryParameters.Add(string.Format("keys={0}", System.Uri.EscapeDataString(string.Join(",", keys)))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; MultipartFormDataContent _multiPartContent = new MultipartFormDataContent(); if (formStream != null) { StreamContent _formStream = new StreamContent(formStream); FileStream _formStreamAsFileStream = formStream as FileStream; if (_formStreamAsFileStream != null) { _formStream.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = "form_stream", FileName = _formStreamAsFileStream.Name }; _formStream.Headers.Add("Content-Type", contentType); } _multiPartContent.Add(_formStream, "form_stream"); } _httpRequest.Content = _multiPartContent; // Set Credentials if (Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = SafeJsonConvert.DeserializeObject <ErrorResponse>(_responseContent, DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse <AnalyzeResult>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject <AnalyzeResult>(_responseContent, DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
public void Remove([NotNull] string key, Credentials credentials = null, Action <Response> callback = null) { Wrap(RemoveAsync(key, credentials), callback); }
public async Task SetUpCredentials(int userId, [FromBody] Credentials credentials) { await _synchronizationService.SetUpUserCredentials(userId, credentials); }
private static void executeIAM(string[] args, Credentials credentials) { var nArgs = CLIHelper.GetNamedArguments(args); var helper = new IAMHelper(credentials); switch (args[1]) { case "create-policy": { if (!nArgs.ContainsKey("permissions")) { throw new NotSupportedException("permissions parameter was not specified"); } if (!nArgs.ContainsKey("paths")) { throw new NotSupportedException("paths parameter was not specified"); } var paths = nArgs["paths"].Split(',').Where(x => !x.IsNullOrWhitespace()).ToArray(); if (paths.IsNullOrEmpty()) { throw new Exception("At least one path must be specified in the paths parameter."); } var permissions = nArgs["permissions"].Split(',').Where(x => !x.IsNullOrWhitespace()) .ToArray().ToEnum <AWSWrapper.S3.S3Helper.Permissions>(); if (permissions.IsNullOrEmpty()) { throw new Exception("No permissions were found!"); } var result = helper.CreatePolicyS3Async( name: nArgs["name"], paths: paths, permissions: permissions, description: nArgs.FirstOrDefault(x => x.Key == "description").Value ?? $"Admin S3 Access Policy to '{nArgs["paths"].JsonSerialize()}' auto generated by AWSHelper").Result; Console.WriteLine($"SUCCESS, {nArgs["name"]} policy was created for path {nArgs["paths"].JsonSerialize()}, Arn: {result.Arn}."); } ; break; case "delete-policy": { var result = helper.DeletePolicyByNameAsync( name: nArgs["name"]).Result; Console.WriteLine($"SUCCESS, {nArgs["name"]} policy was removed."); } ; break; case "create-role": { if (!nArgs.ContainsKey("policies")) { throw new NotSupportedException("policies parameter was not specified"); } var policies = nArgs["policies"].Split(',').Where(x => !x.IsNullOrWhitespace()).ToArray(); if (policies.IsNullOrEmpty()) { throw new Exception($"No policies were found although flag was present, {nArgs["policies"]}, verify that names are separated by ','"); } var result = helper.CreateRoleWithPoliciesAsync( roleName: nArgs["name"], policies: policies, createInstanceProfile: nArgs.GetValueOrDefault("create-instance-profile").ToBoolOrDefault(false), roleDescription: nArgs.FirstOrDefault(x => x.Key == "description").Value ?? $"Role '{nArgs["name"]}' auto generated by AWSHelper").Result; Console.WriteLine($"SUCCESS, {nArgs["name"]} role was created, Result:\n{result.JsonSerialize(Newtonsoft.Json.Formatting.Indented)}."); } ; break; case "delete-role": { var result = helper.DeleteRoleAsync( roleName: nArgs["name"], detachPolicies: true, deleteInstanceProfiles: nArgs.GetValueOrDefault("delete-instance-profiles").ToBoolOrDefault(false) ).Result; Console.WriteLine($"SUCCESS, {nArgs["name"]} role was removed and all policies detatched."); } ; break; case "help": case "--help": case "-help": case "-h": case "h": HelpPrinter($"{args[0]}", "Amazon Identity and Access Management", ("create-policy", "Accepts params: permissions (',' separated, allowed: Read,Write,Delete,All,<s3-specyfic without 's3:', case sensitive>), name, paths (',' separated), description (optional)"), ("create-role", "Accepts params: name, policies (',' separated), description (optional)"), ("delete-policy", "Accepts params: name"), ("delete-role", "Accepts params: name")); break; default: { Console.WriteLine($"Try '{args[0]} help' to find out list of available commands."); throw new Exception($"Unknown IAM command: '{args[0]} {args[1]}'"); } } }
public static string Authenticate(Credentials credentials) { JObject o = new JObject(); string res_ = "Failed creating session: "; try { o["username"] = credentials.username; o["clientVersion"] = MainWindow.m_sCurrentVersion; var httpContent = new StringContent(o.ToString(), Encoding.UTF8, "application/json"); string res = sendPost(BackendURL + m_Const_startSession, httpContent).Result; dynamic response = null; if (res != null) { response = JsonConvert.DeserializeObject(res); } ; if (response != null && (bool)response.success) { // call credentials.sessionKey = (string)response.data.SessionKey; ClientConfigDTO config = new ClientConfigDTO(response.data.ClientConfig); bool versionValid = validateVersion(config.NewestClientVersion); StateManager.Init(credentials, config); var g_config = Utils.getLocalConfig(); if (g_config != null) { string webhookUrl = g_config["WebHookURL"]; string email = g_config["Email"]; //register local webhhok if (!String.IsNullOrWhiteSpace(webhookUrl)) { JObject u = new JObject(); u["WebHookURL"] = webhookUrl; u["SessionName"] = credentials.username; u["SessionKey"] = credentials.sessionKey; var webHookContent = new StringContent(u.ToString(), Encoding.UTF8, "application/json"); sendPost(BackendURL + m_Const_addWebHook, webHookContent); } // register local email if (!String.IsNullOrWhiteSpace(email)) { JObject u = new JObject(); u["Email"] = email; u["SessionName"] = credentials.username; u["SessionKey"] = credentials.sessionKey; var emailContent = new StringContent(u.ToString(), Encoding.UTF8, "application/json"); sendPost(BackendURL + m_Const_registerEmail, emailContent); } } res_ = ""; } else if (response != null) { res_ += response.message; } else { res_ += "Failed connecting to server"; } } catch (Exception exc) { res_ += "Exception occured."; Log.Write("Error occured when trying to authenticate \n " + exc.Message); Log.Write(exc.StackTrace); } return(res_); }
public ConversionClient(Credentials creds = null) { Credentials = creds; }
public static void ConfigureCredentials(Credentials credentials) { _observer.XmlConfig = credentials; }
public YggdrasilAuthenticator(Credentials credentials) { this.Credentials = credentials; }
/// <summary> /// Post operation to serialize or deserialize GraphRunbookContent /// </summary> /// <param name='resourceGroupName'> /// Name of an Azure Resource group. /// </param> /// <param name='automationAccountName'> /// The name of the automation account. /// </param> /// <param name='parameters'> /// Input data describing the graphical runbook. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <AzureOperationResponse <GraphicalRunbookContent> > ConvertGraphRunbookContentWithHttpMessagesAsync(string resourceGroupName, string automationAccountName, GraphicalRunbookContent parameters, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._]+$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._]+$"); } } if (automationAccountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "automationAccountName"); } if (SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.SubscriptionId"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } string apiVersion = "2021-06-22"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("automationAccountName", automationAccountName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ConvertGraphRunbookContent", tracingParameters); } // Construct URL var _baseUrl = BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Automation/automationAccounts/{automationAccountName}/convertGraphRunbookContent").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{automationAccountName}", System.Uri.EscapeDataString(automationAccountName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(SubscriptionId)); List <string> _queryParameters = new List <string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (GenerateClientRequestId != null && GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", AcceptLanguage); } if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if (parameters != null) { _requestContent = SafeJsonConvert.SerializeObject(parameters, SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = SafeJsonConvert.DeserializeObject <ErrorResponse>(_responseContent, DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse <GraphicalRunbookContent>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject <GraphicalRunbookContent>(_responseContent, DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
public async Task <bool> CheckIfUserExist([FromBody] Credentials credentials) { return(await _synchronizationService.CheckIfUserExist(credentials)); }
public HTTPProxy(Uri address, Credentials credentials, bool isTransparent) { this.Address = address; this.Credentials = credentials; this.IsTransparent = isTransparent; }
public TasksApi(Endpoints endPoints, IApiClient apiClient, IJsonSerializer serializer, Credentials credentials) : base(apiClient, serializer, credentials, endPoints.LoggedIn) { this.endPoints = endPoints.Tasks; }
public override IEnumerator RunTest() { LogSystem.InstallDefaultReactors(); try { VcapCredentials vcapCredentials = new VcapCredentials(); fsData data = null; // Get credentials from a credential file defined in environmental variables in the VCAP_SERVICES format. // See https://www.ibm.com/watson/developercloud/doc/common/getting-started-variables.html. var environmentalVariable = Environment.GetEnvironmentVariable("VCAP_SERVICES"); var fileContent = File.ReadAllText(environmentalVariable); // Add in a parent object because Unity does not like to deserialize root level collection types. fileContent = Utility.AddTopLevelObjectToJson(fileContent, "VCAP_SERVICES"); // Convert json to fsResult fsResult r = fsJsonParser.Parse(fileContent, out data); if (!r.Succeeded) { throw new WatsonException(r.FormattedMessages); } // Convert fsResult to VcapCredentials object obj = vcapCredentials; r = _serializer.TryDeserialize(data, obj.GetType(), ref obj); if (!r.Succeeded) { throw new WatsonException(r.FormattedMessages); } // Set credentials from imported credntials Credential credential = vcapCredentials.VCAP_SERVICES["speech_to_text"][TestCredentialIndex].Credentials; _username = credential.Username.ToString(); _password = credential.Password.ToString(); _url = credential.Url.ToString(); } catch { Log.Debug("TestSpeechToText", "Failed to get credentials from VCAP_SERVICES file. Please configure credentials to run this test. For more information, see: https://github.com/watson-developer-cloud/unity-sdk/#authentication"); } // Create credential and instantiate service Credentials credentials = new Credentials(_username, _password, _url); // Or authenticate using token //Credentials credentials = new Credentials(_url) //{ // AuthenticationToken = _token //}; _speechToText = new SpeechToText(credentials); _customCorpusFilePath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/test-stt-corpus.txt"; _customWordsFilePath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/test-stt-words.json"; _wavFilePath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/test-audio.wav"; _audioClip = WaveFile.ParseWAV("testClip", File.ReadAllBytes(_wavFilePath)); Log.Debug("ExampleSpeechToText", "Attempting to recognize"); _speechToText.Recognize(_audioClip, HandleOnRecognize); while (!_recognizeTested) { yield return(null); } // Get models Log.Debug("ExampleSpeechToText", "Attempting to get models"); _speechToText.GetModels(HandleGetModels); while (!_getModelsTested) { yield return(null); } // Get model Log.Debug("ExampleSpeechToText", "Attempting to get model {0}", _modelNameToGet); _speechToText.GetModel(HandleGetModel, _modelNameToGet); while (!_getModelTested) { yield return(null); } // Get customizations Log.Debug("ExampleSpeechToText", "Attempting to get customizations"); _speechToText.GetCustomizations(HandleGetCustomizations); while (!_getCustomizationsTested) { yield return(null); } // Create customization Log.Debug("ExampleSpeechToText", "Attempting create customization"); _speechToText.CreateCustomization(HandleCreateCustomization, "unity-test-customization", "en-US_BroadbandModel", "Testing customization unity"); while (!_createCustomizationsTested) { yield return(null); } // Get customization Log.Debug("ExampleSpeechToText", "Attempting to get customization {0}", _createdCustomizationID); _speechToText.GetCustomization(HandleGetCustomization, _createdCustomizationID); while (!_getCustomizationTested) { yield return(null); } // Get custom corpora Log.Debug("ExampleSpeechToText", "Attempting to get custom corpora for {0}", _createdCustomizationID); _speechToText.GetCustomCorpora(HandleGetCustomCorpora, _createdCustomizationID); while (!_getCustomCorporaTested) { yield return(null); } // Add custom corpus Log.Debug("ExampleSpeechToText", "Attempting to add custom corpus {1} in customization {0}", _createdCustomizationID, _createdCorpusName); _speechToText.AddCustomCorpus(HandleAddCustomCorpus, _createdCustomizationID, _createdCorpusName, true, _customCorpusFilePath); while (!_addCustomCorpusTested) { yield return(null); } // Get custom corpus Log.Debug("ExampleSpeechToText", "Attempting to get custom corpus {1} in customization {0}", _createdCustomizationID, _createdCorpusName); _speechToText.GetCustomCorpus(HandleGetCustomCorpus, _createdCustomizationID, _createdCorpusName); while (!_getCustomCorpusTested) { yield return(null); } // Wait for customization Runnable.Run(CheckCustomizationStatus(_createdCustomizationID)); while (!_isCustomizationReady) { yield return(null); } // Get custom words Log.Debug("ExampleSpeechToText", "Attempting to get custom words."); _speechToText.GetCustomWords(HandleGetCustomWords, _createdCustomizationID); while (!_getCustomWordsTested) { yield return(null); } // Add custom words from path Log.Debug("ExampleSpeechToText", "Attempting to add custom words in customization {0} using Words json path {1}", _createdCustomizationID, _customWordsFilePath); string customWords = File.ReadAllText(_customWordsFilePath); _speechToText.AddCustomWords(HandleAddCustomWordsFromPath, _createdCustomizationID, customWords); while (!_addCustomWordsFromPathTested) { yield return(null); } // Wait for customization _isCustomizationReady = false; Runnable.Run(CheckCustomizationStatus(_createdCustomizationID)); while (!_isCustomizationReady) { yield return(null); } // Add custom words from object Words words = new Words(); Word w0 = new Word(); List <Word> wordList = new List <Word>(); w0.word = "mikey"; w0.sounds_like = new string[1]; w0.sounds_like[0] = "my key"; w0.display_as = "Mikey"; wordList.Add(w0); Word w1 = new Word(); w1.word = "charlie"; w1.sounds_like = new string[1]; w1.sounds_like[0] = "char lee"; w1.display_as = "Charlie"; wordList.Add(w1); Word w2 = new Word(); w2.word = "bijou"; w2.sounds_like = new string[1]; w2.sounds_like[0] = "be joo"; w2.display_as = "Bijou"; wordList.Add(w2); words.words = wordList.ToArray(); Log.Debug("ExampleSpeechToText", "Attempting to add custom words in customization {0} using Words object", _createdCustomizationID); _speechToText.AddCustomWords(HandleAddCustomWordsFromObject, _createdCustomizationID, words); while (!_addCustomWordsFromObjectTested) { yield return(null); } // Wait for customization _isCustomizationReady = false; Runnable.Run(CheckCustomizationStatus(_createdCustomizationID)); while (!_isCustomizationReady) { yield return(null); } // Get custom word Log.Debug("ExampleSpeechToText", "Attempting to get custom word {1} in customization {0}", _createdCustomizationID, words.words[0].word); _speechToText.GetCustomWord(HandleGetCustomWord, _createdCustomizationID, words.words[0].word); while (!_getCustomWordTested) { yield return(null); } // Train customization Log.Debug("ExampleSpeechToText", "Attempting to train customization {0}", _createdCustomizationID); _speechToText.TrainCustomization(HandleTrainCustomization, _createdCustomizationID); while (!_trainCustomizationTested) { yield return(null); } // Wait for customization _isCustomizationReady = false; Runnable.Run(CheckCustomizationStatus(_createdCustomizationID)); while (!_isCustomizationReady) { yield return(null); } // Upgrade customization - not currently implemented in service //Log.Debug("ExampleSpeechToText", "Attempting to upgrade customization {0}", _createdCustomizationID); //_speechToText.UpgradeCustomization(HandleUpgradeCustomization, _createdCustomizationID); //while (!_upgradeCustomizationTested) // yield return null; // Delete custom word Log.Debug("ExampleSpeechToText", "Attempting to delete custom word {1} in customization {0}", _createdCustomizationID, words.words[2].word); _speechToText.DeleteCustomWord(HandleDeleteCustomWord, _createdCustomizationID, words.words[2].word); while (!_deleteCustomWordTested) { yield return(null); } // Delay Log.Debug("ExampleDiscovery", string.Format("Delaying delete environment for {0} sec", _delayTimeInSeconds)); Runnable.Run(Delay(_delayTimeInSeconds)); while (!_readyToContinue) { yield return(null); } _readyToContinue = false; // Delete custom corpus Log.Debug("ExampleSpeechToText", "Attempting to delete custom corpus {1} in customization {0}", _createdCustomizationID, _createdCorpusName); _speechToText.DeleteCustomCorpus(HandleDeleteCustomCorpus, _createdCustomizationID, _createdCorpusName); while (!_deleteCustomCorpusTested) { yield return(null); } // Delay Log.Debug("ExampleDiscovery", string.Format("Delaying delete environment for {0} sec", _delayTimeInSeconds)); Runnable.Run(Delay(_delayTimeInSeconds)); while (!_readyToContinue) { yield return(null); } _readyToContinue = false; // Reset customization Log.Debug("ExampleSpeechToText", "Attempting to reset customization {0}", _createdCustomizationID); _speechToText.ResetCustomization(HandleResetCustomization, _createdCustomizationID); while (!_resetCustomizationTested) { yield return(null); } // Delay Log.Debug("ExampleDiscovery", string.Format("Delaying delete environment for {0} sec", _delayTimeInSeconds)); Runnable.Run(Delay(_delayTimeInSeconds)); while (!_readyToContinue) { yield return(null); } _readyToContinue = false; // Delete customization Log.Debug("ExampleSpeechToText", "Attempting to delete customization {0}", _createdCustomizationID); _speechToText.DeleteCustomization(HandleDeleteCustomization, _createdCustomizationID); while (!_deleteCustomizationsTested) { yield return(null); } Log.Debug("ExampleSpeechToText", "Speech to Text examples complete."); yield break; }
public HTTPProxy(Uri address, Credentials credentials) : this(address, credentials, false) { SendWholeUri = true; }
/// <summary> /// Create an instance of the InMemoryCredentialStore /// </summary> /// <param name="credentials"></param> public InMemoryCredentialStore(Credentials credentials) { Ensure.ArgumentNotNull(credentials, nameof(credentials)); _credentials = credentials; }
/// <summary> /// Parses the server's challenge token and returns the next challenge response. /// </summary> /// <remarks> /// Parses the server's challenge token and returns the next challenge response. /// </remarks> /// <returns>The next challenge response.</returns> /// <param name="token">The server's challenge token.</param> /// <param name="startIndex">The index into the token specifying where the server's challenge begins.</param> /// <param name="length">The length of the server's challenge.</param> /// <exception cref="System.InvalidOperationException"> /// The SASL mechanism is already authenticated. /// </exception> /// <exception cref="System.NotSupportedException"> /// THe SASL mechanism does not support SASL-IR. /// </exception> /// <exception cref="SaslException"> /// An error has occurred while parsing the server's challenge token. /// </exception> protected override byte[] Challenge(byte[] token, int startIndex, int length) { if (IsAuthenticated) { throw new InvalidOperationException(); } if (token == null) { throw new NotSupportedException("CRAM-MD5 does not support SASL-IR."); } var cred = Credentials.GetCredential(Uri, MechanismName); var userName = Encoding.UTF8.GetBytes(cred.UserName); var password = Encoding.UTF8.GetBytes(cred.Password); var ipad = new byte[64]; var opad = new byte[64]; byte[] digest; if (password.Length > 64) { byte[] checksum; using (var md5 = new MD5()) checksum = md5.ComputeHash(password); Array.Copy(checksum, ipad, checksum.Length); Array.Copy(checksum, opad, checksum.Length); } else { Array.Copy(password, ipad, password.Length); Array.Copy(password, opad, password.Length); } for (int i = 0; i < 64; i++) { ipad[i] ^= 0x36; opad[i] ^= 0x5c; } using (var md5 = new MD5()) { md5.TransformBlock(ipad, 0, ipad.Length, null, 0); md5.TransformFinalBlock(token, startIndex, length); digest = md5.Hash; } using (var md5 = new MD5()) { md5.TransformBlock(opad, 0, opad.Length, null, 0); md5.TransformFinalBlock(digest, 0, digest.Length); digest = md5.Hash; } var buffer = new byte[userName.Length + 1 + (digest.Length * 2)]; int offset = 0; for (int i = 0; i < userName.Length; i++) { buffer[offset++] = userName[i]; } buffer[offset++] = 0x20; for (int i = 0; i < digest.Length; i++) { byte c = digest[i]; buffer[offset++] = HexAlphabet[(c >> 4) & 0x0f]; buffer[offset++] = HexAlphabet[c & 0x0f]; } IsAuthenticated = true; return(buffer); }
/// <summary> /// Retrieve the list of virtual numbers available for a specific country. /// </summary> /// <param name="request">Search filter</param> /// <param name="creds">(Optional) Overridden credentials for only this request</param> /// <returns></returns> public static SearchResults Search(SearchRequest request, Credentials creds = null) { var json = ApiRequest.DoRequest(ApiRequest.GetBaseUriFor(typeof(Number), "/number/search/"), request, creds); return(JsonConvert.DeserializeObject <SearchResults>(json)); }
/// <summary> /// Change the webhook endpoints associated with a rented virtual number or associate a virtual number with an Application. /// </summary> /// <param name="cmd">Update request</param> /// <param name="creds">(Optional) Overridden credentials for only this request</param> /// <returns></returns> public static ResponseBase Update(NumberUpdateCommand cmd, Credentials creds = null) { var response = ApiRequest.DoPostRequest(ApiRequest.GetBaseUriFor(typeof(Number), "/number/update"), cmd, creds); return(JsonConvert.DeserializeObject <ResponseBase>(response.JsonResponse)); }
public PrisonUser(string prefix) : this(prefix, Credentials.GenerateCredential(7), string.Format("Pr!5{0}", Credentials.GenerateCredential(10)), false) { }
public static SearchResults ListOwnNumbers(SearchRequest request, Credentials creds = null) { var json = ApiRequest.DoRequest(ApiRequest.GetBaseUriFor(typeof(Account), "/account/numbers/"), request, creds); return(JsonConvert.DeserializeObject <SearchResults>(json)); }
public MYOBCompanyFiles(Credentials inCredentials) { CompanyName = inCredentials.Organisation; }
public Connection(Uri mainUrl, Uri apiUrl, Credentials credentials) { MainUrl = mainUrl; ApiUrl = apiUrl; Credentials = credentials; }
public UninstallHost(ServiceDescription description, ServiceStartMode startMode, IEnumerable <string> dependencies, Credentials credentials, IEnumerable <Action> preActions, IEnumerable <Action> postActions, bool sudo) : base(description, startMode, dependencies, credentials, preActions, postActions, sudo) { }
public void Update([NotNull] string key, [NotNull] string data, DatastoreOperation operation, Credentials credentials = null, Action <Response <string> > callback = null) { Wrap(UpdateAsync(key, data, operation, credentials), callback); }
/// <summary> /// Create a new application /// </summary> /// <param name="request">Application request</param> /// <param name="creds">(Optional) Overridden credentials for only this request</param> /// <returns></returns> public static ApplicationResponse Create(ApplicationRequest request, Credentials creds = null) { var response = ApiRequest.DoPostRequest(ApiRequest.GetBaseUriFor(typeof(Application), "/v1/applications"), request, creds); return(JsonConvert.DeserializeObject <ApplicationResponse>(response.JsonResponse)); }
/// <summary> /// List all of the applications associated with this account /// </summary> /// <param name="PageSize">Set the number of items returned on each call to this endpoint. The default is 10 records.</param> /// <param name="PageIndex">Set the offset from the first page. The default value is 0, calls to this endpoint return a page of <page_size>. For example, set page_index to 3 to retrieve items 31 - 40 when page_size is the default value.</param> /// <param name="AppId">Optional id of specific application to retrieve</param> /// <param name="creds">(Optional) Overridden credentials for only this request</param> /// <returns></returns> public static List <ApplicationResponse> List(int PageSize = 10, int PageIndex = 0, string AppId = "", Credentials creds = null) { if (!string.IsNullOrEmpty(AppId)) { return(new List <ApplicationResponse> { JsonConvert.DeserializeObject <ApplicationResponse>( ApiRequest.DoRequest(ApiRequest.GetBaseUriFor(typeof(Application), $"/v1/applications/{AppId}"), // TODO: using this method sig allows us to have the api auth injected at the expense of opaque code here new Dictionary <string, string>(), creds)) }); } var json = ApiRequest.DoRequest(ApiRequest.GetBaseUriFor(typeof(Application), "/v1/applications"), new Dictionary <string, string> { { "page_size", PageSize.ToString() }, { "page_index", PageIndex.ToString() } }, creds); var response = JsonConvert.DeserializeObject <ApplicationListResponse>(json); return(response._embedded.applications); }
public bool HasPassword() { return(Credentials.Any(c => c.Type.StartsWith(CredentialTypes.Password.Prefix, StringComparison.OrdinalIgnoreCase))); }
public void Set([NotNull] string key, [NotNull] string data, Credentials credentials = null, Action <Response> callback = null) { Wrap(SetAsync(key, data, credentials), callback); }