/// <summary> /// Adds the domain user credential. /// </summary> /// <param name="target">The target.</param> /// <param name="userName">Name of the user.</param> /// <param name="password">The password.</param> public static void AddDomainUserCredential(string target, string userName, string password) { Credential userCredential = new Credential(); try { userCredential.TargetName = target; userCredential.Type = (uint)CRED_TYPE.CRED_TYPE_DOMAIN_PASSWORD; userCredential.UserName = userName; userCredential.AttributeCount = 0; userCredential.Persist = (uint)CRED_PERSIST.CRED_PERSIST_LOCAL_MACHINE; byte[] bpassword = Encoding.Unicode.GetBytes(password); userCredential.CredentialBlobSize = (uint)bpassword.Length; userCredential.CredentialBlob = Marshal.StringToCoTaskMemUni(password); if (!CredWrite(ref userCredential, (uint)0)) { throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error()); } } finally { if (userCredential.CredentialBlob != null) { Marshal.FreeCoTaskMem(userCredential.CredentialBlob); } } }
public void AddRange(Credential.Info[] cInfo) { foreach (Credential.Info cI in cInfo) { List.Add(cI); } }
public String CheckPayooAccount(String username) { String result = ""; try { Credential credential = new Credential(); credential.APIUsername = ConfigurationManager.AppSettings["APIUsername"]; credential.APIPassword = ConfigurationManager.AppSettings["APIPassword"]; credential.APISignature = ConfigurationManager.AppSettings["APISignature"]; Caller caller = new Caller(); caller.InitCall(ConfigurationManager.AppSettings["PayooBusinessAPI"], credential, Server.MapPath(@"..\App_Data\Certificates\biz_pkcs12.p12"), "alpe", Server.MapPath(@"..\App_Data\Certificates\payoo_public_cert.pem")); CheckPayooAccountRequestType req = new CheckPayooAccountRequestType(); req.AccountID = username; // agentb2 ; vimp71 | [email protected] CheckPayooAccountResponseType res = (CheckPayooAccountResponseType)caller.Call("CheckPayooAccount", req); if (res.Ack == AckCodeType.Success) { result = "Valid"; } else { result = "InValid Account"; } } catch (Exception ex) { result = "False"; throw ex; } return result; }
/// <summary> /// Encrypt credential based on the public key of server /// </summary> /// <param name="credential"></param> /// <param name="certificate"></param> /// <returns></returns> public byte[] EncryptCredentialBasedOnCertificateOfServer(Credential credential,X509Certificate2 certificate) { RSACryptoServiceProvider publicKey = (RSACryptoServiceProvider)certificate.PublicKey.Key; string info = JsonConvert.SerializeObject(credential); byte[] credentialInfoByte = publicKey.Encrypt(System.Text.Encoding.Default.GetBytes(info), false); return credentialInfoByte; }
public async Task<IEnumerable<IndustryJob>> GetIndustryJobsAsync(Credential credentials) { if (!(await AccessAllowed(credentials.AccessMask, CallEndPoint.IndustryJobs))) throw new UnauthorizedAccessException(); return await _repo.GetIndustryJobsAsync(1, credentials); }
public async Task<IEnumerable<Asset>> GetAssetsAsync(Credential credentials) { if (!(await AccessAllowed(credentials.AccessMask, CallEndPoint.AssetList))) throw new UnauthorizedAccessException(); return await _repo.GetAssetsAsync(1, credentials); }
public async Task<IEnumerable<Transaction>> GetTransactionsAsync(Credential credentials) { if (!(await AccessAllowed(credentials.AccessMask, CallEndPoint.WalletTransactions))) throw new UnauthorizedAccessException(); throw new NotImplementedException(); }
public IHttpActionResult PutCredential(int id, Credential credential) { if (!ModelState.IsValid) { return BadRequest(ModelState); } if (id != credential.ID) { return BadRequest(); } db.Entry(credential).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!CredentialExists(id)) { return NotFound(); } else { throw; } } return StatusCode(HttpStatusCode.NoContent); }
public ActionResult Create(CredentialCreateModel model) { if (ModelState.IsValid) { try { using (var db = new MySelfieEntities()) { var entity = new Credential(); entity.MergeWithOtherType(model); db.Credentials.Add(entity); db.SaveChanges(); } } catch (Exception ex) { ModelState.AddModelError("ex", ex); return View(model); } return RedirectToRoute("credential_index_g"); } return View(model); }
public bool ValidateCredentials(ICollection<Credential> credentials, string password, out Credential matched) { var ldapCred = credentials.FirstOrDefault(c => c.Type == CredentialType_LdapUser); matched = ldapCred; if (ldapCred != null) { try { LdapConnection connection = new LdapConnection(this.Configuration.Server); connection.SessionOptions.SecureSocketLayer = true; connection.SessionOptions.VerifyServerCertificate = (ldapConnection, certificate) => { return true; }; connection.AuthType = AuthType.Negotiate; NetworkCredential credential = new NetworkCredential(ldapCred.Value, password); connection.Credential = credential; connection.Bind(); return true; } catch (Exception) { return false; } } return false; }
private void UserAuthenticated(Credential credential) { if (credential != null) { DialogResult = true; } }
public async Task<ICredential> AuthenticateAsync(Uri requestUri, Uri callbackUri = null) { var requestUriStrb = new StringBuilder(); requestUriStrb.Append(requestUri.AbsoluteUri); if (callbackUri != null) { requestUriStrb.AppendFormat("&oauth_callback={0}", callbackUri.AbsoluteUri); } var listener = new HttpListener(); listener.Prefixes.Add(callbackUri.AbsoluteUri); listener.Start(); System.Diagnostics.Process.Start(requestUriStrb.ToString()); var ctx = await listener.GetContextAsync(); var token = new Credential(ctx.Request.QueryString.Get("oauth_token"), ctx.Request.QueryString.Get("oauth_verifier")); // empty response // ctx.Response.ContentLength64 = 0; // await ctx.Response.OutputStream.WriteAsync(new byte[0], 0, 0); ctx.Response.OutputStream.Close(); listener.Stop(); return token; }
/// <summary> /// Adds a credential to the credential locker. /// </summary> /// <param name="credential">The credential to be added.</param> public static void AddCredential(Credential credential) { if (credential == null || string.IsNullOrEmpty(credential.ServiceUri)) return; var serverInfo = IdentityManager.Current.FindServerInfo(credential.ServiceUri); var host = serverInfo == null ? credential.ServiceUri : serverInfo.ServerUri; string passwordValue = null; // value stored as password in the password locker string userName = null; var oAuthTokenCredential = credential as OAuthTokenCredential; var arcGISTokenCredential = credential as ArcGISTokenCredential; var arcGISNetworkCredential = credential as ArcGISNetworkCredential; if (oAuthTokenCredential != null) { userName = oAuthTokenCredential.UserName; if (!string.IsNullOrEmpty(oAuthTokenCredential.OAuthRefreshToken)) // refreshable OAuth token --> we store it so we'll be able to generate a new token from it passwordValue = OAuthRefreshTokenPrefix + oAuthTokenCredential.OAuthRefreshToken; else if (!string.IsNullOrEmpty(oAuthTokenCredential.Token)) passwordValue = OAuthAccessTokenPrefix + oAuthTokenCredential.Token; } else if (arcGISTokenCredential != null) { userName = arcGISTokenCredential.UserName; if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(arcGISTokenCredential.Password)) // Token generated from an username/password --> store the password passwordValue = PasswordPrefix + arcGISTokenCredential.Password; } else if (arcGISNetworkCredential != null) { // networkcredential: store the password if (arcGISNetworkCredential.Credentials != null) { NetworkCredential networkCredential = arcGISNetworkCredential.Credentials.GetCredential(new Uri(host), ""); if (networkCredential != null && !string.IsNullOrEmpty(networkCredential.Password)) { userName = networkCredential.UserName; if (!string.IsNullOrEmpty(networkCredential.Domain)) userName = networkCredential.Domain + "\\" + userName; passwordValue = NetworkCredentialPasswordPrefix + networkCredential.Password; } } } // Store the value in the password locker if (passwordValue != null) { var passwordVault = new PasswordVault(); var resource = ResourcePrefix + host; // remove previous resource stored for the same host try // FindAllByResource throws an exception when no pc are stored { foreach (PasswordCredential pc in passwordVault.FindAllByResource(resource)) passwordVault.Remove(pc); } catch {} passwordVault.Add(new PasswordCredential(resource, userName, passwordValue)); } }
public UpdateDialog(string fileName, Credential cred) { InitializeComponent(); FileName = fileName; InitializeUI(cred); }
public void AddCredentialToCustomer(Credential credential, int customerID) { var customer = Customers.Where(c => c.ID == customerID).First(); credential.CustomerID = customer.ID; credential.MyCustomer = customer; customer.Credentials.Add(credential); }
public void AddCredentialToCustomer(Credential credential, int customerID) { var customer = CustDB.Customers.Find(customerID); if (customer == null) throw new ArgumentException("Key not found"); customer.Credentials.Add(credential); }
public void AddCredentialToNode(Credential credential, int nodeID) { var node = CustDB.Nodes.Find(nodeID); if (node == null) throw new ArgumentException("Key not found"); node.Credentials.Add(credential); }
/// <summary> /// Adds a credential to the isolated storage. /// </summary> /// <param name="credential">The credential to be added.</param> public static void AddCredential(Credential credential) { if (credential == null || string.IsNullOrEmpty(credential.ServiceUri)) return; var serverInfo = IdentityManager.Current.FindServerInfo(credential.ServiceUri); var host = serverInfo == null ? credential.ServiceUri : serverInfo.ServerUri; string passwordValue = null; // value stored as password in the isolated storage string userName = null; var oAuthTokenCredential = credential as OAuthTokenCredential; var arcGISTokenCredential = credential as ArcGISTokenCredential; var arcGISNetworkCredential = credential as ArcGISNetworkCredential; var certificateCredential = credential as CertificateCredential; if (oAuthTokenCredential != null) { userName = oAuthTokenCredential.UserName; if (!string.IsNullOrEmpty(oAuthTokenCredential.OAuthRefreshToken)) // refreshable OAuth token --> we store it so we'll be able to generate a new token from it passwordValue = OAuthRefreshTokenPrefix + oAuthTokenCredential.OAuthRefreshToken; else if (!string.IsNullOrEmpty(oAuthTokenCredential.Token)) passwordValue = OAuthAccessTokenPrefix + oAuthTokenCredential.Token; } else if (arcGISTokenCredential != null) { userName = arcGISTokenCredential.UserName; if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(arcGISTokenCredential.Password)) // Token generated from an username/password --> store the password passwordValue = PasswordPrefix + arcGISTokenCredential.Password; } else if (arcGISNetworkCredential != null) { // networkcredential: store the password if (arcGISNetworkCredential.Credentials != null) { NetworkCredential networkCredential = arcGISNetworkCredential.Credentials.GetCredential(new Uri(host), ""); if (networkCredential != null && !string.IsNullOrEmpty(networkCredential.Password)) { userName = networkCredential.UserName; if (!string.IsNullOrEmpty(networkCredential.Domain)) userName = networkCredential.Domain + "\\" + userName; passwordValue = NetworkCredentialPasswordPrefix + networkCredential.Password; } } } else if (certificateCredential != null) { // certificateCredential: store the serial number if (certificateCredential.ClientCertificate != null) { passwordValue = CertificateCredentialPrefix + certificateCredential.ClientCertificate.GetSerialNumberString(); } } // Store the value in the isolated storage if (passwordValue != null) { AddCachedCredential(host, userName, passwordValue); } }
public List<Schema.User> Execute(Credential.CredentialBase credential) { Parameters.Clear(); Parameters.Add(_Query.ToString()); var result = Common.HttpPost(URL, Parameters, credential, HttpRequestMethod); return new JavaScriptSerializer().Deserialize<Schema.UsersObj>(result).Users; }
public void AddCredential(string type, string link) { var cred = new Credential(); cred.Type = type; cred.Link = link; cred.TenantId = TenantId; this.Credentials.Add(cred); }
public string Execute(Credential.CredentialBase credential) { Parameters.Clear(); Parameters.Add(_VenueId.ToString()); var result = Common.HttpPost(URL, Parameters, credential, HttpRequestMethod); return result; }
public Schema.User Execute(Credential credential) { Parameters.Clear(); Parameters.Add(_UserId); Parameters.Add(_ShowBadges); Parameters.Add(_ShowMayorships); string result = Common.HTTPPost(URL, Parameters, credential, HTTP_REQUEST_METHOD); return new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<FoursquareNET.Schema.UserObj>(result).User; }
public Schema.User Execute(Credential.CredentialBase credential) { Parameters.Clear(); Parameters.Add(_UserId.ToString()); Parameters.Add(_ShowBadges.ToString()); Parameters.Add(_ShowMayorships.ToString()); var result = Common.HttpPost(URL, Parameters, credential, HttpRequestMethod); return new JavaScriptSerializer().Deserialize<Schema.UserObj>(result).User; }
public void AddCredentialToNode(Credential credential, int nodeID) { var node = Customers.SelectMany(c => c.Nodes) .Where(n => n.ID == nodeID) .First(); credential.MyNode = node; credential.NodeID = node.ID; node.Credentials.Add(credential); }
internal string AutenticateUser(Credential credential) { /* Token de teste */ RandomNumberGenerator rng = new RNGCryptoServiceProvider(); var tokenData = new byte[64]; rng.GetBytes(tokenData); string s = Convert.ToBase64String(tokenData); var token = new AutenticationToken(credential); tokenDictionary.TryAdd(s, token); return s; }
public bool ValidatePasswordCredential(Credential credential, string providedPassword) { Func<string, Credential, bool> validator; if (!Validators.TryGetValue(credential.Type, out validator)) { return false; } return validator(providedPassword, credential); }
public CredentialAuditRecord(Credential credential, bool removed) { Type = credential.Type; Identity = credential.Identity; // Track the value for credentials that are definitely revokable (API Key, etc.) and have been removed if (removed && !CredentialTypes.IsPassword(credential.Type)) { Value = credential.Value; } }
public IHttpActionResult PostCredential(Credential credential) { if (!ModelState.IsValid) { return BadRequest(ModelState); } db.Credentials.Add(credential); db.SaveChanges(); return CreatedAtRoute("DefaultApi", new { id = credential.ID }, credential); }
public IList<Group> Authorize(Credential credential) { var id = credential.ID; var functionalGroups = from ctf in Context.tblcredentialtofunctionalgroup join fg in Context.tlkpfunctionalgroup on ctf.idfunctionalgroup equals fg.idfunctionalgroup where ctf.idcredential == id select fg; credential.Groups = functionalGroups.Cast<Group>().ToList(); return credential.Groups; }
public async Task<bool> ValidateCredentials(Uri targetUri, Credential credentials) { return await Task.Run(() => { try { Credential.Validate(credentials); return true; } catch { } return false; }); }
private KeyClient GetKeyClient() => new KeyClient(new Uri($"https://{Configuration.VaultName}.vault.azure.net/"), Credential.CreateTokenCredential());
public T GetAcsResponse <T>(AcsRequest <T> request, string regionId, Credential credential) where T : AcsResponse { HttpResponse httpResponse = this.DoAction(request, regionId, credential); return(ParseAcsResponse(request, httpResponse)); }
private static extern bool CredWrite(ref Credential userCredential, uint flags);
public static async Task PublishUserGameCredentialRemovedIntegrationEventAsync(this IServiceBusPublisher publisher, Credential credential) { var integrationEvent = new UserGameCredentialRemovedIntegrationEvent { Credential = new GameCredentialDto { UserId = credential.UserId, PlayerId = credential.PlayerId, Game = credential.Game.ToEnum <EnumGame>() } }; await publisher.PublishAsync(integrationEvent); }
internal virtual void PrepareSession() { // make sure we have a valid WebRequestSession object to work with if (null == WebSession) { WebSession = new WebRequestSession(); } if (null != SessionVariable) { // save the session back to the PS environment if requested PSVariableIntrinsics vi = SessionState.PSVariable; vi.Set(SessionVariable, WebSession); } // // handle credentials // if (null != Credential && Authentication == WebAuthenticationType.None) { // get the relevant NetworkCredential NetworkCredential netCred = Credential.GetNetworkCredential(); WebSession.Credentials = netCred; // supplying a credential overrides the UseDefaultCredentials setting WebSession.UseDefaultCredentials = false; } else if ((null != Credential || null != Token) && Authentication != WebAuthenticationType.None) { ProcessAuthentication(); } else if (UseDefaultCredentials) { WebSession.UseDefaultCredentials = true; } if (null != CertificateThumbprint) { X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly); X509Certificate2Collection collection = (X509Certificate2Collection)store.Certificates; X509Certificate2Collection tbCollection = (X509Certificate2Collection)collection.Find(X509FindType.FindByThumbprint, CertificateThumbprint, false); if (tbCollection.Count == 0) { CryptographicException ex = new CryptographicException(WebCmdletStrings.ThumbprintNotFound); throw ex; } foreach (X509Certificate2 tbCert in tbCollection) { X509Certificate certificate = (X509Certificate)tbCert; WebSession.AddCertificate(certificate); } } if (null != Certificate) { WebSession.AddCertificate(Certificate); } // // handle the user agent // if (null != UserAgent) { // store the UserAgent string WebSession.UserAgent = UserAgent; } if (null != Proxy) { WebProxy webProxy = new WebProxy(Proxy); webProxy.BypassProxyOnLocal = false; if (null != ProxyCredential) { webProxy.Credentials = ProxyCredential.GetNetworkCredential(); } else if (ProxyUseDefaultCredentials) { // If both ProxyCredential and ProxyUseDefaultCredentials are passed, // UseDefaultCredentials will overwrite the supplied credentials. webProxy.UseDefaultCredentials = true; } WebSession.Proxy = webProxy; } if (-1 < MaximumRedirection) { WebSession.MaximumRedirection = MaximumRedirection; } // store the other supplied headers if (null != Headers) { foreach (string key in Headers.Keys) { // add the header value (or overwrite it if already present) WebSession.Headers[key] = Headers[key].ToString(); } } }
static void Main(string[] args) { try { // 必要步骤: // 实例化一个认证对象,入参需要传入腾讯云账户密钥对secretId,secretKey。 // 这里采用的是从环境变量读取的方式,需要在环境变量中先设置这两个值。 // 你也可以直接在代码中写死密钥对,但是小心不要将代码复制、上传或者分享给他人, // 以免泄露密钥对危及你的财产安全。 Credential cred = new Credential { SecretId = Environment.GetEnvironmentVariable("TENCENTCLOUD_SECRET_ID"), SecretKey = Environment.GetEnvironmentVariable("TENCENTCLOUD_SECRET_KEY") }; // 实例化一个client选项,可选的,没有特殊需求可以跳过 ClientProfile clientProfile = new ClientProfile(); // 指定签名算法(默认为HmacSHA256) clientProfile.SignMethod = ClientProfile.SIGN_TC3SHA256; // 非必要步骤 // 实例化一个客户端配置对象,可以指定超时时间等配置 HttpProfile httpProfile = new HttpProfile(); // SDK默认使用POST方法。 // 如果你一定要使用GET方法,可以在这里设置。GET方法无法处理一些较大的请求。 httpProfile.ReqMethod = "GET"; // SDK有默认的超时时间,非必要请不要进行调整。 // 如有需要请在代码中查阅以获取最新的默认值。 httpProfile.Timeout = 10; // 请求连接超时时间,单位为秒(默认60秒) // SDK会自动指定域名。通常是不需要特地指定域名的,但是如果你访问的是金融区的服务, // 则必须手动指定域名,例如云服务器的上海金融区域名: cvm.ap-shanghai-fsi.tencentcloudapi.com httpProfile.Endpoint = "cvm.tencentcloudapi.com"; // 代理服务器,当你的环境下有代理服务器时设定 httpProfile.WebProxy = Environment.GetEnvironmentVariable("HTTPS_PROXY"); clientProfile.HttpProfile = httpProfile; // 实例化要请求产品(以cvm为例)的client对象 // 第二个参数是地域信息,可以直接填写字符串ap-guangzhou,或者引用预设的常量,clientProfile是可选的 CvmClient client = new CvmClient(cred, "ap-guangzhou", clientProfile); // 实例化一个请求对象,根据调用的接口和实际情况,可以进一步设置请求参数 // 你可以直接查询SDK源码确定DescribeInstancesRequest有哪些属性可以设置, // 属性可能是基本类型,也可能引用了另一个数据结构。 // 推荐使用IDE进行开发,可以方便的跳转查阅各个接口和数据结构的文档说明。 DescribeInstancesRequest req = new DescribeInstancesRequest(); // 基本类型的设置。 // 此接口允许设置返回的实例数量。此处指定为只返回一个。 // SDK采用的是指针风格指定参数,即使对于基本类型你也需要用指针来对参数赋值。 // SDK提供对基本类型的指针引用封装函数 req.Limit = 1; // 数组类型的设置。 // 此接口允许指定实例 ID 进行过滤,但是由于和接下来要演示的 Filter 参数冲突,先注释掉。 // req.InstanceIds = new string[] { "ins-r8hr2upy" }; // 复杂对象的设置。 // 在这个接口中,Filters是数组,数组的元素是复杂对象Filter,Filter的成员Values是string数组。 // 填充请求参数,这里request对象的成员变量即对应接口的入参 // 你可以通过官网接口文档或跳转到request对象的定义处查看请求参数的定义 Filter zoneFilter = new Filter(); // 创建Filter对象, 以zone的维度来查询cvm实例 zoneFilter.Name = "zone"; zoneFilter.Values = new string[] { "ap-guangzhou-1", "ap-guangzhou-2" }; Filter nameFilter = new Filter(); nameFilter.Name = "instance-name"; nameFilter.Values = new string[] { "中文测试" }; req.Filters = new Filter[] { zoneFilter, nameFilter }; // Filters 是成员为Filter对象的列表 //// 这里还支持以标准json格式的string来赋值请求参数的方式。下面的代码跟上面的参数赋值是等效的 //string strParams = "{\"Filters\":[{\"Name\":\"zone\",\"Values\":[\"ap-guangzhou-1\",\"ap-guangzhou-2\"]}]}"; //req = DescribeInstancesRequest.FromJsonString<DescribeInstancesRequest>(strParams); // 通过client对象调用DescribeInstances方法发起请求。注意请求方法名与请求对象是对应的 // 返回的resp是一个DescribeInstancesResponse类的实例,与请求对象对应 DescribeInstancesResponse resp = client.DescribeInstances(req).ConfigureAwait(false).GetAwaiter().GetResult(); // 输出json格式的字符串回包 Console.WriteLine(AbstractModel.ToJsonString(resp)); // 也可以取出单个值。 // 你可以通过官网接口文档或跳转到response对象的定义处查看返回字段的定义 Console.WriteLine(resp.TotalCount); } catch (Exception e) { Console.WriteLine(e.ToString()); } Console.Read(); }
public static Dictionary <string, object> genCredential(Dictionary <string, object> values) { checkArguments(values, new string[] { "secretId", "secretKey", "region" }); Credential cred = new Credential { SecretId = (string)values["secretId"], SecretKey = (string)values["secretKey"] }; string region = (string)values["region"]; ClientProfile clientProfile = new ClientProfile(); HttpProfile httpProfile = new HttpProfile(); httpProfile.Endpoint = ("sts.tencentcloudapi.com"); clientProfile.HttpProfile = httpProfile; // get policy string policy = null; if (values.ContainsKey("policy")) { policy = (string)values["policy"]; } if (policy == null) { checkArguments(values, new string[] { "bucket", "allowActions" }); string bucket = (string)values["bucket"]; string[] allowActions = (string[])values["allowActions"]; string[] allowPrefixes; if (values.ContainsKey("allowPrefix")) { allowPrefixes = new string[] { (string)values["allowPrefix"] }; } else if (values.ContainsKey("allowPrefixes")) { allowPrefixes = (string[])values["allowPrefixes"]; } else { throw new System.ArgumentException("allowPrefix and allowPrefixes are both null."); } policy = getPolicy(region, bucket, allowPrefixes, allowActions); } // duration Int32 durationSeconds = 1800; if (values.ContainsKey("durationSeconds")) { durationSeconds = (Int32)values["durationSeconds"]; } Dictionary <string, object> body = new Dictionary <string, object>(); body.Add("DurationSeconds", durationSeconds); body.Add("Name", "cos-sts-sdk-dotnet"); body.Add("Policy", policy); StsClient client = new StsClient(cred, region, clientProfile); GetFederationTokenRequest req = new GetFederationTokenRequest(); string strParams = JsonConvert.SerializeObject(body); req = GetFederationTokenRequest.FromJsonString <GetFederationTokenRequest>(strParams); GetFederationTokenResponse resp = client.GetFederationToken(req). ConfigureAwait(false).GetAwaiter().GetResult(); string jsonString = JsonConvert.SerializeObject(resp); Dictionary <string, object> dic = JsonConvert.DeserializeObject <Dictionary <string, object> >(jsonString); if (dic.ContainsKey("ExpiredTime")) { dic.Add("StartTime", Int32.Parse(dic["ExpiredTime"].ToString()) - durationSeconds); } return(dic); }
public void CreateCredential(Credential credential) { _context.Add(credential); }
/// <summary> /// Validates that a set of credentials grants access to the target resource. /// <para/> /// Returns `<see langword="true"/>` if successful; otherwise `<see langword="false"/>`. /// </summary> /// <param name="targetUri">The target resource to validate against.</param> /// <param name="credentials">The credentials to validate.</param> public async Task <bool> ValidateCredentials(TargetUri targetUri, Credential credentials) { return(await Authority.ValidateCredentials(targetUri, credentials)); }
/// <summary> /// Client Constructor. /// </summary> /// <param name="credential">Credentials.</param> /// <param name="region">Region name, such as "ap-guangzhou".</param> /// <param name="profile">Client profiles.</param> public FmuClient(Credential credential, string region, ClientProfile profile) : base(endpoint, version, credential, region, profile) { }
/// <summary> /// Client constructor. /// </summary> /// <param name="credential">Credentials.</param> /// <param name="region">Region name, such as "ap-guangzhou".</param> public FmuClient(Credential credential, string region) : this(credential, region, new ClientProfile()) { }
// Module defining this command // Optional custom code for this activity /// <summary> /// Returns a configured instance of System.Management.Automation.PowerShell, pre-populated with the command to run. /// </summary> /// <param name="context">The NativeActivityContext for the currently running activity.</param> /// <returns>A populated instance of Sytem.Management.Automation.PowerShell</returns> /// <remarks>The infrastructure takes responsibility for closing and disposing the PowerShell instance returned.</remarks> protected override ActivityImplementationContext GetPowerShell(NativeActivityContext context) { System.Management.Automation.PowerShell invoker = global::System.Management.Automation.PowerShell.Create(); System.Management.Automation.PowerShell targetCommand = invoker.AddCommand(PSCommandName); // Initialize the arguments if (LocalCredential.Expression != null) { targetCommand.AddParameter("LocalCredential", LocalCredential.Get(context)); } if (UnjoinDomainCredential.Expression != null) { targetCommand.AddParameter("UnjoinDomainCredential", UnjoinDomainCredential.Get(context)); } if (Credential.Expression != null) { targetCommand.AddParameter("Credential", Credential.Get(context)); } if (DomainName.Expression != null) { targetCommand.AddParameter("DomainName", DomainName.Get(context)); } if (OUPath.Expression != null) { targetCommand.AddParameter("OUPath", OUPath.Get(context)); } if (Server.Expression != null) { targetCommand.AddParameter("Server", Server.Get(context)); } if (Unsecure.Expression != null) { targetCommand.AddParameter("Unsecure", Unsecure.Get(context)); } if (Options.Expression != null) { targetCommand.AddParameter("Options", Options.Get(context)); } if (WorkgroupName.Expression != null) { targetCommand.AddParameter("WorkgroupName", WorkgroupName.Get(context)); } if (Restart.Expression != null) { targetCommand.AddParameter("Restart", Restart.Get(context)); } if (PassThru.Expression != null) { targetCommand.AddParameter("PassThru", PassThru.Get(context)); } if (NewName.Expression != null) { targetCommand.AddParameter("NewName", NewName.Get(context)); } if (Force.Expression != null) { targetCommand.AddParameter("Force", Force.Get(context)); } if (GetIsComputerNameSpecified(context) && (PSRemotingBehavior.Get(context) == RemotingBehavior.Custom)) { targetCommand.AddParameter("ComputerName", PSComputerName.Get(context)); } return(new ActivityImplementationContext() { PowerShellInstance = invoker }); }
/// <summary> /// Saves the given credential. /// </summary> /// <param name="target">Name of the application/URL the credential is used for.</param> /// <param name="credential">Credential to store.</param> /// <returns>True if successfully stored, false otherwise.</returns> public bool Save(Uri target, Credential credential) { return(store.WriteCredentials(target, credential)); }
public SSORegDTO SSORegistration(SSORegDTO dto) { var checkCredential = (from u in db.Credentials where u.UserName == dto.username select u).FirstOrDefault(); var getLocation = (from u in db.Locations where u.Address == "NULL" && u.City == "NULL" && u.State == "NULL" && u.Zipcode == "NULL" select u).FirstOrDefault(); SSORegDTO response = new SSORegDTO(); response.Messages = new List <string>(); using (var dbTransaction = db.Database.BeginTransaction()) { try { if (getLocation == null) { Location location = new Location() { Address = "NULL", City = "NULL", State = "NULL", Zipcode = "NULL", Latitude = 0.0, Longitude = 0.0 }; db.Locations.Add(location); db.SaveChanges(); } if (checkCredential == null) { var locationID = (from u in db.Locations where u.Address == "NULL" && u.City == "NULL" && u.State == "NULL" && u.Zipcode == "NULL" select u).FirstOrDefault(); Credential cred = new Credential() { UserName = dto.username, Password = dto.password }; db.Credentials.Add(cred); db.SaveChanges(); Salt salt = new Salt() { UserID = cred.UserID, SaltValue = dto.salt, Credential = cred }; db.Salts.Add(salt); db.SaveChanges(); UserProfile type = new UserProfile() { UserID = cred.UserID, LocationID = locationID.LocationID, Type = "SSO" }; db.UserProfiles.Add(type); db.SaveChanges(); dbTransaction.Commit(); response.Messages.Add("Success!"); response.isSuccessful = true; return(response); } dbTransaction.Rollback(); response.Messages.Add("User Already Exist"); response.isSuccessful = false; return(response); }catch (MulticastNotSupportedException) { dbTransaction.Rollback(); response.Messages.Add("Failed to Exist"); response.isSuccessful = false; return(response); } } }
public void DeleteCredential(Credential credential) { _context.Remove(credential); }
public override IEnumerator RunTest() { LogSystem.InstallDefaultReactors(); VcapCredentials vcapCredentials = new VcapCredentials(); fsData data = null; string result = null; var vcapUrl = Environment.GetEnvironmentVariable("VCAP_URL"); var vcapUsername = Environment.GetEnvironmentVariable("VCAP_USERNAME"); var vcapPassword = Environment.GetEnvironmentVariable("VCAP_PASSWORD"); using (SimpleGet simpleGet = new SimpleGet(vcapUrl, vcapUsername, vcapPassword)) { while (!simpleGet.IsComplete) { yield return(null); } result = simpleGet.Result; } // Add in a parent object because Unity does not like to deserialize root level collection types. result = Utility.AddTopLevelObjectToJson(result, "VCAP_SERVICES"); // Convert json to fsResult fsResult r = fsJsonParser.Parse(result, 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["document_conversion"]; _username = credential.Username.ToString(); _password = credential.Password.ToString(); _url = credential.Url.ToString(); // Create credential and instantiate service Credentials credentials = new Credentials(_username, _password, _url); // Or authenticate using token //Credentials credentials = new Credentials(_url) //{ // AuthenticationToken = _token //}; _documentConversion = new DocumentConversion(credentials); _examplePath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/watson_beats_jeopardy.html"; if (!_documentConversion.ConvertDocument(OnConvertDocument, OnFail, _examplePath, _conversionTarget)) { Log.Debug("TestDocumentConversion.RunTest()", "Document conversion failed!"); } while (!_convertDocumentTested) { yield return(null); } Log.Debug("TestDoucmentConversion.RunTest()", "Document conversion examples complete."); yield break; }
private void AddCommonProperties(Credential cred) { cred.Type = CredentialType.Generic; cred.Target = "WindowsPushClientSFTPCredential"; cred.PersistanceType = PersistanceType.LocalComputer; }
public virtual async Task <AuthenticatedUser> Register(string username, string emailAddress, Credential credential) { if (_config.FeedOnlyMode) { throw new FeedOnlyModeException(FeedOnlyModeException.FeedOnlyModeError); } var existingUser = Entities.Users .FirstOrDefault(u => u.Username == username || u.EmailAddress == emailAddress); if (existingUser != null) { if (string.Equals(existingUser.Username, username, StringComparison.OrdinalIgnoreCase)) { throw new EntityException(Strings.UsernameNotAvailable, username); } else { throw new EntityException(Strings.EmailAddressBeingUsed, emailAddress); } } var newUser = new User(username) { EmailAllowed = true, UnconfirmedEmailAddress = emailAddress, EmailConfirmationToken = CryptographyService.GenerateToken(), NotifyPackagePushed = true, CreatedUtc = _dateTimeProvider.UtcNow }; // Add a credential for the password newUser.Credentials.Add(credential); if (!_config.ConfirmEmailAddresses) { newUser.ConfirmEmailAddress(); } // Write an audit record await Auditing.SaveAuditRecordAsync(new UserAuditRecord(newUser, AuditedUserAction.Register, credential)); Entities.Users.Add(newUser); await Entities.SaveChangesAsync(); _telemetryService.TrackNewUserRegistrationEvent(newUser, credential); return(new AuthenticatedUser(newUser, credential)); }
private async Task <AuthenticatedUser> AuthenticateInternal(Func <Credential, Credential> matchCredential, Credential credential) { if (credential.Type.StartsWith(CredentialTypes.Password.Prefix, StringComparison.OrdinalIgnoreCase)) { // Password credentials cannot be used this way. throw new ArgumentException(Strings.PasswordCredentialsCannotBeUsedHere, nameof(credential)); } using (_trace.Activity("Authenticate Credential: " + credential.Type)) { var matched = matchCredential(credential); if (matched == null) { _trace.Information("No user matches credential of type: " + credential.Type); await Auditing.SaveAuditRecordAsync( new FailedAuthenticatedOperationAuditRecord(null, AuditedAuthenticatedOperationAction.FailedLoginNoSuchUser, attemptedCredential : credential)); return(null); } if (matched.User is Organization) { _trace.Information($"Cannot authenticate organization account '{matched.User.Username}'."); await Auditing.SaveAuditRecordAsync( new FailedAuthenticatedOperationAuditRecord(null, AuditedAuthenticatedOperationAction.FailedLoginUserIsOrganization, attemptedCredential : credential)); return(null); } if (matched.HasExpired) { _trace.Verbose("Credential of type '" + matched.Type + "' for user '" + matched.User.Username + "' has expired on " + matched.Expires.Value.ToString("O", CultureInfo.InvariantCulture)); return(null); } if (CredentialTypes.IsApiKey(matched.Type) && !matched.IsScopedApiKey() && !matched.HasBeenUsedInLastDays(_config.ExpirationInDaysForApiKeyV1)) { // API key credential was last used a long, long time ago - expire it await Auditing.SaveAuditRecordAsync( new UserAuditRecord(matched.User, AuditedUserAction.ExpireCredential, matched)); matched.Expires = _dateTimeProvider.UtcNow; await Entities.SaveChangesAsync(); _trace.Verbose( "Credential of type '" + matched.Type + "' for user '" + matched.User.Username + "' was last used on " + matched.LastUsed.Value.ToString("O", CultureInfo.InvariantCulture) + " and has now expired."); return(null); } // store tenant (organization) id, if available matched.TenantId = credential.TenantId; // update last used timestamp matched.LastUsed = _dateTimeProvider.UtcNow; await Entities.SaveChangesAsync(); _trace.Verbose("Successfully authenticated '" + matched.User.Username + "' with '" + matched.Type + "' credential"); return(new AuthenticatedUser(matched.User, matched)); } }
public virtual async Task <AuthenticatedUser> Authenticate(Credential credential) { return(await AuthenticateInternal(FindMatchingCredential, credential)); }
public HttpAuthorizationService(Credential credential, IHttpWrapper httpWrapper, string url) : base(credential, url) { Url = url; Credentials = credential; this.httpWrapper = httpWrapper; }
/// <summary> /// Performs record-by-record processing functionality for the cmdlet. /// </summary> protected override void ProcessRecord() { if (PrtgSessionState.Client == null || Force.IsPresent) { PrtgSessionState.Client = PassHash.IsPresent ? new PrtgClient(Server, Credential.GetNetworkCredential().UserName, Credential.GetNetworkCredential().Password, AuthMode.PassHash, IgnoreSSL) : new PrtgClient(Server, Credential.GetNetworkCredential().UserName, Credential.GetNetworkCredential().Password, ignoreSSL: IgnoreSSL); if (RetryCount != null) { PrtgSessionState.Client.RetryCount = RetryCount.Value; } if (RetryDelay != null) { PrtgSessionState.Client.RetryDelay = RetryDelay.Value; } if (LogLevel != null) { LogLevel level = PrtgAPI.LogLevel.None; foreach (var l in LogLevel) { level |= l; } PrtgSessionState.Client.LogLevel = level; } if (!ProgressTrue && (ProgressFalse || IsScript || IsISE)) { PrtgSessionState.EnableProgress = false; } else { PrtgSessionState.EnableProgress = true; } WritePassThru(); } else { throw new InvalidOperationException($"Already connected to server {PrtgSessionState.Client.Server}. To override please specify -Force"); } }
private void connectButton_Click(object sender, EventArgs e) { // DEV REMOVE password = passwordField.Text; environment = "https://dcmisdev.api.crm4.dynamics.com/api/data/v8.2/"; // environmentField.Text; using (var cred = new Credential()) { if (!usernameField.Text.Equals(null) && !passwordField.Text.Equals(null)) { // Store username and password in credential manager cred.Username = username; cred.Password = password; cred.Target = "Fabric Time Recording App"; cred.Type = CredentialType.Generic; cred.PersistanceType = PersistanceType.LocalComputer; cred.Save(); // Create message box System.Windows.Forms.DialogResult logonOutput; // Buttons for message box MessageBoxButtons OKButtons = MessageBoxButtons.OK; MessageBoxButtons retryButtons = MessageBoxButtons.RetryCancel; // Get the CRM connection string and connect to the CRM Organization CrmServiceClient crmConn = new CrmServiceClient("AuthType = Office365; Url =" + environment + "; Username="******"; Password="******""); IOrganizationService crmService = crmConn.OrganizationServiceProxy; if (crmConn.IsReady) { // Create a column set to define which attributes should be retrieved. ColumnSet caseAttributes = new ColumnSet(new string[] { "title", "ticketnumber" }); ColumnSet timeRecordAttributes = new ColumnSet(new string[] { "subject", "new_caseid", "regardingobjectid" }); // Retrieve the caseID and its name and ownerid attributes. Entity caseID = crmService.Retrieve("incident", new Guid("CFA8B94E-C81D-E711-80FF-5065F38BD4E1"), caseAttributes); Console.Write("Retrieved Case: " + caseAttributes.ToString() + "."); // Update the postal code attribute. caseID["description"] = "Connected Successfully"; // Update the Case. crmService.Update(caseID); Console.WriteLine("\n Updated Case: " + caseAttributes.ToString() + "."); // Successful login box logonOutput = MessageBox.Show("Successfully connected to Dynamics 365", "Connected", OKButtons); //Hide/lock login related fields passwordLabel.Visible = false; passwordField.Visible = false; connectButton.Visible = false; environmentField.Text = environment; usernameField.Text = username; environmentField.Enabled = false; usernameField.Enabled = false; // Set Logged in/out messages loggedOutMessage.Visible = false; loggedInLabel.Visible = true; userLoggedInLabel.Visible = true; userLoggedInLabel.Text = username; } else { // Failed login box logonOutput = MessageBox.Show("Please check your credentials and try again", "Failed To Connect", retryButtons); // Set Logged in/out messages loggedOutMessage.Visible = true; loggedInLabel.Visible = false; userLoggedInLabel.Visible = false; } } else { MessageBox.Show("Please fill in Username and Password"); } } }
public Task <int> DeleteCredentialAsync(Credential credential) { return(_database.DeleteAsync(credential)); }
public virtual async Task <AuthenticatedUser> Register(string username, string emailAddress, Credential credential) { var existingUser = Entities.Users .FirstOrDefault(u => u.Username == username || u.EmailAddress == emailAddress); if (existingUser != null) { if (String.Equals(existingUser.Username, username, StringComparison.OrdinalIgnoreCase)) { throw new EntityException(Strings.UsernameNotAvailable, username); } else { throw new EntityException(Strings.EmailAddressBeingUsed, emailAddress); } } var apiKey = Guid.NewGuid(); var newUser = new User(username) { EmailAllowed = true, UnconfirmedEmailAddress = emailAddress, EmailConfirmationToken = CryptographyService.GenerateToken(), CreatedUtc = DateTime.UtcNow }; // Add a credential for the password and the API Key newUser.Credentials.Add(CredentialBuilder.CreateV1ApiKey(apiKey)); newUser.Credentials.Add(credential); if (!Config.ConfirmEmailAddresses) { newUser.ConfirmEmailAddress(); } // Write an audit record await Auditing.SaveAuditRecord(new UserAuditRecord(newUser, UserAuditAction.Registered)); Entities.Users.Add(newUser); Entities.SaveChanges(); return(new AuthenticatedUser(newUser, credential)); }
/// <summary> /// 点击 “导入” 触发方法 /// </summary> /// <param name="parameter"></param> private void ImportVoucherInfo(object parameter) { string[] arryVoucherInfo = File.ReadAllLines(FilePath); arryVoucherInfo = arryVoucherInfo.Distinct().ToArray(); //去掉已经存在于数据库的 #region List <string> listVoucherInfo = arryVoucherInfo.ToList(); string selectVocher = string.Format("select * from sc_credential where status=1 and personno='{0}' ", PersonNo); using (MySqlDataReader reader = MySqlHelper.ExecuteReader(EnvironmentInfo.ConnectionString, selectVocher)) { while (reader.Read()) { var credentialNoTemp = reader["CredentialNo"].ToString(); listVoucherInfo.Remove(credentialNoTemp); } } arryVoucherInfo = listVoucherInfo.ToArray(); #endregion if (arryVoucherInfo.Length == 0) { ShowMessage("没有可导入的车牌"); return; } var personNoP = PersonNo; if (credential == null || string.IsNullOrEmpty(credential.Id)) { ShowMessage("请先校验!"); return; } Task.Factory.StartNew(() => { //List<string> pcsSqls = new List<string>(); //List<string> insertVouchers = new List<string>(); //List<string> insertVehicles = new List<string>(); //List<string> insertCredentialChannelRels = new List<string>(); foreach (var item in arryVoucherInfo) { List <string> insertSqls = new List <string>(); //新增 凭证 (根据从数据库中获取的一个例子为主,主要替换掉ID ,凭证号,创建时间,更新时间,备注,车牌) Credential insertCredential = new Credential() { Id = Guid.NewGuid().ToString("N"), CredentialNo = item, CreateTime = DateTime.Now, UpdatedTime = DateTime.Now, Remark = "工具导入", Plate = item }; insertSqls.Add(string.Format(@" insert into sc_credential (Id,PersonId,PersonNo,PersonName,CredentialNo,CredentialType, StartTime,EndTime, Status,IsDeleted,CreatedTime,CreatedOperatorId,CreatedOperatorNo,CreatedOperatorName, UpdatedTime,UpdatedOperatorId,UpdatedOperatorNo,UpdatedOperatorName, CardNum, PhysicsNum,CardKey,Password,PhotoPath,DataPath,TxtData,BlobData,FileMd5, IsVisitor,FingerNo, Remark, IsAntiFlag, Plate,PlateColor,VehicleType) select '{0}',PersonId,PersonNo,PersonName,'{1}',CredentialType, StartTime,EndTime, Status,IsDeleted,'{2}',CreatedOperatorId,CreatedOperatorNo,CreatedOperatorName, '{3}',UpdatedOperatorId,UpdatedOperatorNo,UpdatedOperatorName, CardNum, PhysicsNum,CardKey,Password,PhotoPath,DataPath,TxtData,BlobData,FileMd5, IsVisitor,FingerNo, '{4}', IsAntiFlag, '{5}',PlateColor,VehicleType from sc_credential where PersonNo='{6}' limit 1 ", insertCredential.Id, insertCredential.CredentialNo, insertCredential.CreateTime, insertCredential.UpdatedTime, insertCredential.Remark, insertCredential.Plate, personNoP)); //新增车辆信息 insertSqls.Add(string.Format(@"insert into pms_Vehicle ( Id,CredentialId,Plate, PlateColor,VehicleBrand,VehicleColor,VehicleType, VehicleSituation,PersonId,Status,OpenId, Remark,CreatedTime, FaceImageUrl ) select replace(uuid(),'-','') ,'{0}','{1}', PlateColor,VehicleBrand,VehicleColor,VehicleType, VehicleSituation,PersonId,Status,OpenId, '{2}','{3}', FaceImageUrl from pms_Vehicle where CredentialId='{4}' limit 1 ", insertCredential.Id, item, "工具导入", DateTime.Now, credential.Id )); //新增 凭证- 通道 关系 信息 insertSqls.Add(string.Format(@" insert into pms_credential_channel_rel (Id,CredentialId,CredentialNo, CredentialType,ChannelId,LeaseStallId,CredentialStatus ) select replace(uuid(),'-',''),'{0}','{1}', CredentialType,ChannelId,LeaseStallId,CredentialStatus from pms_credential_channel_rel where CredentialId='{2}' ", insertCredential.Id, item, credential.Id )); insertSqls.Add(string.Format(@" insert into {3}.pms_credential_channel_rel (Id,CredentialId,CredentialNo, CredentialType,ChannelId,LeaseStallId,CredentialStatus ) select replace(uuid(),'-',''),'{0}','{1}', CredentialType,ChannelId,LeaseStallId,CredentialStatus from pms_credential_channel_rel where CredentialId='{2}' ", insertCredential.Id, item, credential.Id, EnvironmentInfo.DbConnEntity.DbName + "_pcs" )); insertSqls.Add(string.Format(@" update {1}.pms_credential_channel_rel set ChannelId=(select LeaseStallId from pms_credential_channel_rel where CredentialId='{0}' and ChannelId ='11111111111111111111111111111111' ) where CredentialId='{0}' and ChannelId ='11111111111111111111111111111111' ", insertCredential.Id, EnvironmentInfo.DbConnEntity.DbName + "_pcs")); //insertSqls.Add(string.Format(@" update jielink_pcs.pms_credential_channel_rel // set channel=(select LeaseStallId from jielink_pcs.pms_credential_channel_rel where CredentialId='{0}' and ChannelId ='11111111111111111111111111111111' ) // where CredentialId='{0}' and ChannelId ='11111111111111111111111111111111' ", insertCredential.Id)); //执行sql 语句 try { using (MySqlConnection conn = new MySqlConnection(EnvironmentInfo.ConnectionString)) { conn.Open(); MySqlTransaction transaction = conn.BeginTransaction(); MySqlCommand cmd = conn.CreateCommand(); cmd.CommandTimeout = int.MaxValue;//超时时间设置60分钟 cmd.Transaction = transaction; try { foreach (var insertSql in insertSqls) { LogHelper.CommLogger.Info(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "导入凭证信息执行sql:" + insertSql); cmd.CommandText = insertSql; int x = cmd.ExecuteNonQuery(); if (x <= 0) { throw new Exception("新增失败!sql语句为: " + insertSql); } } transaction.Commit(); ShowMessage($"导入凭证 {item} 成功!"); } catch (Exception ex) { transaction.Rollback(); LogHelper.CommLogger.Error("数据新增遇到些问题,事务回滚:" + ex.ToString()); ShowMessage("数据新增遇到些问题,事务回滚:" + ex.ToString()); } } } catch (Exception ex) { LogHelper.CommLogger.Error("数据新增遇到些问题" + ex.ToString()); ShowMessage("数据新增遇到些问题" + ex.ToString()); } } }); }
public virtual async Task ReplaceCredential(User user, Credential credential) { await ReplaceCredentialInternal(user, credential); Entities.SaveChanges(); }
public static bool ValidatePasswordCredential(IEnumerable <Credential> creds, string password, out Credential matched) { matched = creds.FirstOrDefault(c => ValidatePasswordCredential(c, password)); return(matched != null); }
public void GetCommonResponse() { var status = 200; var code = "ThisIsCode"; var message = "ThisIsMessage"; var requestId = "ThisIsRequestId"; // Mock RegionIds ISet<string> regionIds = new HashSet<string>(); regionIds.Add("cn-hangzhou"); // Mock productDomains var productDomains = new List<ProductDomain>(); var productDomain = new ProductDomain("Ess", "ess.aliyuncs.com"); productDomains.Add(productDomain); // Mock endpoint var endpoint = new Endpoint("cn-hangzhou", regionIds, productDomains); // Mock endpoints var endpoints = new List<Endpoint>(); endpoints.Add(endpoint); // Mock response var response = new HttpResponse(); var content = Encoding.GetEncoding("UTF-8") .GetBytes("{\"Code\":\"" + code + "\",\"Message\":\"" + message + "\",\"RequestId\":\"" + requestId + "\"}"); response.ContentType = FormatType.JSON; response.Content = content; response.Status = status; // Mock credential var credential = new Credential(AKID, AKSE); // Mock Profile var mockProfile = new Mock<IClientProfile>(); mockProfile.Setup(foo => foo.GetCredential()).Returns(credential); var profile = mockProfile.Object; // Mock DefaultAcsClient var mockDefaultAcsClient = new Mock<DefaultAcsClient>(profile); mockDefaultAcsClient.Setup(foo => foo.DoAction( It.IsAny<AcsRequest<CommonResponse>>(), It.IsAny<bool>(), It.IsAny<int>(), It.IsAny<string>(), It.IsAny<AlibabaCloudCredentials>(), It.IsAny<Signer>(), It.IsAny<FormatType>(), It.IsAny<List<Endpoint>>() )).Returns(response); var instance = mockDefaultAcsClient.Object; // DefaultAcsClient instance = this.MockDefaultAcsClient(); // Mock AcsResquest var request = new CommonRequest(); request.RegionId = "cn-hangzhou"; request.Product = "Ess"; request.LocationProduct = "ess"; request.LocationEndpointType = "openAPI"; var commonResponse = instance.GetCommonResponse(request); Assert.NotNull(commonResponse); Assert.Equal(200, commonResponse.HttpStatus); }
//private bool _recognizeTextGetTested = false; //private bool _recognizeTextPostTested = false; 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["visual_recognition"][TestCredentialIndex].Credentials; _apikey = credential.Apikey.ToString(); _url = credential.Url.ToString(); } catch { Log.Debug("TestVisualRecognition", "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(_apikey, _url); _visualRecognition = new VisualRecognition(credentials); _visualRecognition.VersionDate = _visualRecognitionVersionDate; // Get all classifiers Log.Debug("ExampleVisualRecognition", "Attempting to get all classifiers"); if (!_visualRecognition.GetClassifiers(OnGetClassifiers)) { Log.Debug("ExampleVisualRecognition", "Failed to get all classifiers!"); } while (!_getClassifiersTested) { yield return(null); } #if TRAIN_CLASSIFIER // Train classifier Log.Debug("ExampleVisualRecognition", "Attempting to train classifier"); string positiveExamplesPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/visual-recognition-classifiers/giraffe_positive_examples.zip"; string negativeExamplesPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/visual-recognition-classifiers/negative_examples.zip"; Dictionary <string, string> positiveExamples = new Dictionary <string, string>(); positiveExamples.Add("giraffe", positiveExamplesPath); if (!_visualRecognition.TrainClassifier(OnTrainClassifier, "unity-test-classifier-example", positiveExamples, negativeExamplesPath)) { Log.Debug("ExampleVisualRecognition", "Failed to train classifier!"); } while (!_trainClassifierTested) { yield return(null); } // Find classifier by ID Log.Debug("ExampleVisualRecognition", "Attempting to find classifier by ID"); if (!_visualRecognition.GetClassifier(OnGetClassifier, _classifierID)) { Log.Debug("ExampleVisualRecognition", "Failed to get classifier!"); } while (!_getClassifierTested) { yield return(null); } #endif #if DELETE_TRAINED_CLASSIFIER // Delete classifier by ID Log.Debug("ExampleVisualRecognition", "Attempting to delete classifier"); if (!_visualRecognition.DeleteClassifier(OnDeleteClassifier, _classifierToDelete)) { Log.Debug("ExampleVisualRecognition", "Failed to delete classifier!"); } #endif while (!_deleteClassifierTested) { yield return(null); } // Classify get Log.Debug("ExampleVisualRecognition", "Attempting to get classify via URL"); if (!_visualRecognition.Classify(OnClassifyGet, _imageURL)) { Log.Debug("ExampleVisualRecognition", "Classify image failed!"); } while (!_classifyGetTested) { yield return(null); } // Classify post image Log.Debug("ExampleVisualRecognition", "Attempting to classify via image on file system"); string imagesPath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/visual-recognition-classifiers/giraffe_to_classify.jpg"; string[] owners = { "IBM", "me" }; string[] classifierIDs = { "default", _classifierID }; if (!_visualRecognition.Classify(imagesPath, OnClassifyPost, owners, classifierIDs, 0.5f)) { Log.Debug("ExampleVisualRecognition", "Classify image failed!"); } while (!_classifyPostTested) { yield return(null); } // Detect faces get Log.Debug("ExampleVisualRecognition", "Attempting to detect faces via URL"); if (!_visualRecognition.DetectFaces(OnDetectFacesGet, _imageURL)) { Log.Debug("ExampleVisualRecogntiion", "Detect faces failed!"); } while (!_detectFacesGetTested) { yield return(null); } // Detect faces post image Log.Debug("ExampleVisualRecognition", "Attempting to detect faces via image"); string faceExamplePath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/visual-recognition-classifiers/obama.jpg"; if (!_visualRecognition.DetectFaces(faceExamplePath, OnDetectFacesPost)) { Log.Debug("ExampleVisualRecognition", "Detect faces failed!"); } while (!_detectFacesPostTested) { yield return(null); } //// Recognize text get //Log.Debug("ExampleVisualRecognition", "Attempting to recognizeText via URL"); //if (!_visualRecognition.RecognizeText(OnRecognizeTextGet, _imageTextURL)) // Log.Debug("ExampleVisualRecognition", "Recognize text failed!"); //while (!_recognizeTextGetTested) // yield return null; //// Recognize text post image //Log.Debug("ExampleVisualRecognition", "Attempting to recognizeText via image"); //string textExamplePath = Application.dataPath + "/Watson/Examples/ServiceExamples/TestData/visual-recognition-classifiers/from_platos_apology.png"; //if (!_visualRecognition.RecognizeText(textExamplePath, OnRecognizeTextPost)) // Log.Debug("ExampleVisualRecognition", "Recognize text failed!"); //while (!_recognizeTextPostTested) // yield return null; Log.Debug("ExampleVisualRecognition", "Visual Recogition tests complete"); yield break; }