/// <summary> /// retruns list of matching records /// </summary> /// <param name="entitySetName">example: contacts, opportunities, accounts</param> /// <param name="query">select and filter query and optional orderby</param> /// <param name="isFetchXml">define is the query is fetch xml or not</param> /// <see cref="https://msdn.microsoft.com/en-us/library/mt607843.aspx"/> /// <seealso cref="https://msdn.microsoft.com/en-us/library/gg334767.aspx#bkmk_filter"/> /// <seealso cref="https://msdn.microsoft.com/en-us/library/gg334767.aspx#bkmk_filter"/> /// <seealso cref="https://msdn.microsoft.com/en-us/library/gg309638.aspx#bkmk_passParametersToFunctions"/> /// <see cref="https://msdn.microsoft.com/en-us/library/gg328117.aspx"/> /// <example>?$select=firstname,lastname&$filter=contains(fullname,'(sample)')&$orderby=jobtitle asc, annualincome desc</example> /// <returns>entity Collection</returns> async Task <string> ICrmApiService.RetrieveRecords(string entitySetName, string query, bool isFetchXml = false, int?maxpagesize = null) { ThrowIf.ArgumentNull("entityLogicalName can't be null", entitySetName); ThrowIf.ArgumentNull("query can't be blank", query); if (maxpagesize != null) { HttpCrmClient.DefaultRequestHeaders.Remove("Prefer"); HttpCrmClient.DefaultRequestHeaders.Add("Prefer", $"odata.maxpagesize={maxpagesize}"); } if (isFetchXml) { return(await this.GetRecordsUsingFetchXml(entitySetName, query)); } else { string requestUri = $"{ entitySetName}{query}"; HttpResponseMessage response = await HttpCrmClient.GetAsync(requestUri, HttpCompletionOption.ResponseHeadersRead); if (response.IsSuccessStatusCode) //200 { string entityCollection = await response.Content.ReadAsStringAsync(); return(entityCollection); } else { throw new Exception(string.Format("Failed to retrieve {0}. Reason: {1}.\n Exception: {2}. \n Query {3}", entitySetName, response.ReasonPhrase, await response.Content.ReadAsStringAsync(), query)); } } }
private static void ExecuteTests(IExecutorPlugin executorPlugin, List <IPlatform> platforms) { ThrowIf.ArgumentNull(executorPlugin, nameof(executorPlugin)); ThrowIf.ArgumentNull(platforms, nameof(platforms)); // Hack: For now just use a single Platform. TODO: Use all Platforms later. var firstPlatform = platforms[0]; var plugins = new List <IExecutorPlugin> { executorPlugin }; executorPlugin.Computer = firstPlatform.Computers[0]; // We already have one plugin, so add 1 less than Computers.Count. for (int i = 1; i < firstPlatform.Computers.Count; ++i) { var newPlugin = executorPlugin.ClonePlugin(); newPlugin.Computer = firstPlatform.Computers[i]; plugins.Add(newPlugin); } // Run all plugins in parallel. Parallel.ForEach(plugins, plugin => { plugin.Execute(); }); }
/// <summary> /// Gets the plugin specified in the XmlNode. /// </summary> /// <param name="node">The XmlNode containing the path to the plugin DLL.</param> /// <param name="xmlConfig">The NTestController.xml config file.</param> /// <returns>The plugin.</returns> /// <exception cref="ArgumentNullException">A null or whitespace only argument was passed in.</exception> /// <exception cref="ArgumentException">The XML node contains an unknown plugin type.</exception> /// <exception cref="TypeLoadException">The plugin DLL doesn't contain the plugin type specified in the XML node.</exception> /// <exception cref="XmlException">There was an error parsing the XmlNode.</exception> public static IPlugin GetPlugin(XmlNode node, string xmlConfig) { ThrowIf.ArgumentNull(node, nameof(node)); string dllFile = XmlUtils.GetXmlAttribute(node, "path"); string pluginTypeString = XmlUtils.GetXmlAttribute(node, "type"); PluginType pluginType; const bool ignoreCase = true; if (!Enum.TryParse(pluginTypeString, ignoreCase, out pluginType)) { throw new ArgumentException(StringUtils.FormatInvariant("Invalid Plugin Type '{0}' was found.", pluginTypeString)); } // Load the plugin. IPlugin plugin = LoadPlugin(dllFile, xmlConfig); if (plugin.PluginType != pluginType) { throw new TypeLoadException(StringUtils.FormatInvariant("Wrong plugin type found! Expecting '{0}', but got '{1}' in '{2}'.", pluginTypeString, plugin.PluginType.ToString(), dllFile)); } return(plugin); }
/// <summary> /// Update the entity (Record Id) in Dynamics CRM /// </summary> /// <param name="entitySetName">example: contacts, opportunities, accounts</param> /// <example>contacts, opportunities </example> /// <param name="id">Record Id</param> /// <param name="jsonUpdateRequest"> Request Object</param> /// <returns> success </returns> async Task <bool> ICrmApiService.UpdateRecord(string entitySetName, Guid id, string jsonUpdateRequest) { ThrowIf.ArgumentNull("entityLogicalName can't be null", entitySetName); ThrowIf.ArgumentNull("Record Id can't be blank", id); ThrowIf.ArgumentNull("jsonUpdateRequest can't be blank", jsonUpdateRequest); string requestUri = string.Format("{0}{1}({2})", HttpCrmClient.BaseAddress, entitySetName, id); HttpMethod httpMethod = new HttpMethod("Patch"); HttpRequestMessage updateRequest = new HttpRequestMessage(httpMethod, requestUri) { Content = new StringContent(jsonUpdateRequest, Encoding.UTF8, "application/json") }; HttpResponseMessage updateResponse = await HttpCrmClient.SendAsync(updateRequest, HttpCompletionOption.ResponseContentRead); if (updateResponse.IsSuccessStatusCode) { return(true); } else { throw new Exception(string.Format("Failed to update contact for reason: {0}. Exception:{1}", updateResponse.ReasonPhrase, updateResponse.Content?.ReadAsStringAsync())); } }
public static IComputer CreateComputer(XmlNode computerNode, XmlNode defaultsNode) { ThrowIf.ArgumentNull(computerNode, nameof(computerNode)); ThrowIf.ArgumentNull(defaultsNode, nameof(defaultsNode)); IComputer computer = new Computer(); computer.Hostname = XmlUtils.GetXmlAttribute(computerNode, "hostname"); var defaultComputerNode = defaultsNode.SelectSingleNode("computer"); computer.Timeout = int.Parse(XmlUtils.GetXmlAttributeOrDefault(computerNode, defaultComputerNode, "timeout")); // Get values from all the sub-nodes. var envVarNode = XmlUtils.GetChildNodeOrDefault(computerNode, defaultsNode, "env_var"); // TODO: The <env_var> node should be moved inside a <env_vars> node. var nunitNode = XmlUtils.GetChildNodeOrDefault(computerNode, defaultsNode, "nunit"); var testResultsNode = XmlUtils.GetChildNodeOrDefault(computerNode, defaultsNode, "test_results"); var workingDirNode = XmlUtils.GetChildNodeOrDefault(computerNode, defaultsNode, "working_dir"); var credentialsNode = XmlUtils.GetChildNodeOrDefault(computerNode, defaultsNode, "credentials"); string envVarName = XmlUtils.GetXmlAttribute(envVarNode, "name"); string envVarValue = XmlUtils.GetXmlAttribute(envVarNode, "value"); computer.EnvironmentVariables.Add(envVarName, envVarValue); computer.NunitPath = XmlUtils.GetXmlAttribute(nunitNode, "path"); computer.OutputPath = XmlUtils.GetXmlAttribute(testResultsNode, "path"); computer.WorkingDirectory = XmlUtils.GetXmlAttribute(workingDirNode, "path"); computer.Credentials.Username = XmlUtils.GetXmlAttribute(credentialsNode, "username"); computer.Credentials.Password = XmlUtils.GetXmlAttribute(credentialsNode, "password"); return(computer); }
public static void ArgumentNull_NullArg_ArgumentNullException(string arg, string nameOfArg) { Assert.Throws <ArgumentNullException>(() => { ThrowIf.ArgumentNull(arg, nameOfArg); }, "{0}.{1}() should throw a {2} if passed a null argument!", nameof(ThrowIf), nameof(ThrowIf.ArgumentNull), nameof(ArgumentNullException)); }
public static void ArgumentNull_ValidArgs_NoException(object arg) { Assert.DoesNotThrow(() => { ThrowIf.ArgumentNull(arg, nameof(arg)); }, "{0}.{1}() should not throw an exception if passed a non-null argument!", nameof(ThrowIf), nameof(ThrowIf.ArgumentNull)); }
/// <summary> /// Adds a test that finished and has no retries left. /// </summary> /// <param name="test">The test to add to the list.</param> public void AddCompletedTest(Test test) { ThrowIf.ArgumentNull(test, nameof(test)); lock (_lock) { _completedTests.Add(test); } }
/// <summary> /// Enqueues a test to run. /// </summary> /// <param name="test">The test to add to the queue.</param> public void EnqueueTestToRun(Test test) { ThrowIf.ArgumentNull(test, nameof(test)); Log.WriteDebug("Queueing test: {0}", test.TestName); lock (_lock) { _testsToRun.Enqueue(test); } }
/// <summary> /// Provides secure connection to access Dynamics CrmApi /// </summary> /// <param name="configuration"> WebApi Configuration</param> /// <see cref="WebApiConfiguration"/> public static void CreateCrmApiServiceInstance(WebApiConfiguration configuration) { ThrowIf.ArgumentNull("WebApiConfiguration can't be null", configuration); if (_instance != null && _instance.IsReady && configuration.CRMApiEndpointUri.Equals(_configuration?.CRMApiEndpointUri)) { throw new Exception("Instance is already created"); } else { _instance = new CrmApiService(configuration); } }
public void Initialize(IFilesRepository fr, Guid fileId) { ThrowIf.ArgumentNull(fr, nameof(fr)); _filesRepository = fr; _file = _filesRepository.GetFileInfo(fileId); if (_file == null) { throw new InvalidOperationException( I18NHelper.FormatInvariant("Fatal. File '{0}' not found in FileStore", fileId)); } }
public void Initialize(IFileStreamRepository fsr, IConfigRepository config, Guid fileId) { ThrowIf.ArgumentNull(fsr, nameof(fsr)); ThrowIf.ArgumentNull(config, nameof(config)); _filesRepository = fsr; _configRepository = config; _file = _filesRepository.GetFileHead(fileId); if (_file == null) { throw new InvalidOperationException( I18NHelper.FormatInvariant("Fatal. File '{0}' not found in legacy database", fileId)); } }
public IPrincipal ProcessResponse(string samlResponse, IFederatedAuthenticationSettings settings) { ThrowIf.ArgumentNull(samlResponse, nameof(samlResponse)); ThrowIf.ArgumentNull(settings, nameof(settings)); var token = ReadSecurityToken(samlResponse, settings); if (token == null) { // TODO add logging // Log.DebugFormat("[SAMLHandler] Cannot read non SAML2 token.\n {0}", tokenString); throw new FederatedAuthenticationException("Cannot read token", FederatedAuthenticationErrorCode.WrongFormat); } var samlSecurityTokenRequirement = new SamlSecurityTokenRequirement { NameClaimType = settings.NameClaimType, // "Username", MapToWindows = false }; var handler = new BpSaml2SecurityTokenHandler(samlResponse, samlSecurityTokenRequirement) { Configuration = new SecurityTokenHandlerConfiguration() }; ConfigureHandler(handler.Configuration, settings); ReadOnlyCollection <ClaimsIdentity> validateToken; try { validateToken = handler.ValidateToken(token); } catch (FederatedAuthenticationException faEx) { if (faEx.ErrorCode != FederatedAuthenticationErrorCode.WrongFormat) { throw; } token = (Saml2SecurityToken)handler.ReadToken(samlResponse); validateToken = handler.ValidateToken(token); } return(new ClaimsPrincipal(validateToken)); }
/// <summary> /// Retieve Record by Id /// </summary> /// <param name="entitySetName">example: contacts, opportunities, accounts</param> /// <example>contacts, opportunities </example> /// <param name="id"></param> /// <param name="queryOptions"></param> /// <returns>Record</returns> async Task <string> ICrmApiService.RetrieveRecord(string entitySetName, Guid id, string queryOptions) { ThrowIf.ArgumentNull("entityLogicalName can't be null", entitySetName); ThrowIf.ArgumentNull("Record Id can't be blank", id); string requestUri = string.Format("{0}{1}({2}){3}", HttpCrmClient.BaseAddress, entitySetName, id, queryOptions); HttpResponseMessage retrieveResponse = await HttpCrmClient.GetAsync(requestUri, HttpCompletionOption.ResponseHeadersRead); if (retrieveResponse.IsSuccessStatusCode) //200 { return(await retrieveResponse.Content?.ReadAsStringAsync()); } else { throw new Exception(string.Format("Failed to retrieve contact for reason: {0}\n Exception:{1}", retrieveResponse.Content, await retrieveResponse.Content.ReadAsStringAsync())); } }
/// <summary> /// Establises the connection to Dynamics 365 Api /// </summary> /// <param name="crmApiUrl"> CRM Api url</param> /// <param name="redirectUrl"> redirect uri registered in Azure AAD App</param> /// <param name="clientId"> clientId(AppId) of registered Azure AAD App</param> /// <param name="clientSecret">clientSecret of registered Azure AAD App</param> /// <param name="tenentId">Tenent Id of Azure AAD endpoint</param> private CrmApiService(WebApiConfiguration configuration) { ThrowIf.ArgumentNull("WebApiConfiguration can't be null", configuration, configuration.CRMApiEndpointUri); _configuration = configuration; try { HttpMessageHandler messageHandler = new OAuthMessageHandler(configuration, new HttpClientHandler()); HttpCrmClient = new HttpClient(messageHandler) { Timeout = new TimeSpan(0, 2, 0) //2 minutes }; HttpCrmClient.BaseAddress = new Uri($"{configuration.CRMApiEndpointUri.TrimEnd('/')}/"); _whoAmI = GetWhoAmIRequest(); } catch (Exception) { throw; } }
/// <summary> /// Create a new entity record in Dynamics CRM and returns record GUID /// </summary> /// <param name="entitySetName">example: contacts, opportunities, accounts</param> /// <example>contacts, opportunities </example> /// <param name="jsonRequest"> Request Object</param> /// <returns> Record Id</returns> async Task <Guid> ICrmApiService.CreateRecord(string entitySetName, string jsonRequest) { ThrowIf.ArgumentNull("entityLogicalName can't be null", entitySetName); ThrowIf.ArgumentNull("jsonRequest can't be null", jsonRequest); string requestUri = string.Format("{0}{1}", HttpCrmClient.BaseAddress, entitySetName); HttpRequestMessage createRequest = new HttpRequestMessage(HttpMethod.Post, requestUri) { Content = new StringContent(jsonRequest) }; createRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); HttpResponseMessage createResponse = await HttpCrmClient.SendAsync(createRequest, HttpCompletionOption.ResponseHeadersRead); if (createResponse.IsSuccessStatusCode) { string recordUri = createResponse.Headers.GetValues("OData-EntityId").FirstOrDefault(); Match match = Regex.Match(recordUri, @"[{(]?[0-9A-F]{8}[-]?([0-9A-F]{4}[-]?){3}[0-9A-F]{12}[)}]?"); if (match.Success) { return(Guid.Parse(match.Value.Replace("(", "").Replace(")", "").Trim())); } else { match = Regex.Match(recordUri, @"[{(]?[0-9A-F]{8}[-]?([0-9A-F]{4}[-]?){3}[0-9A-F]{12}[)}]?".ToLower()); if (match.Success) { return(Guid.Parse(match.Value.Replace("(", "").Replace(")", "").Trim())); } } return(Guid.Empty); } else { throw new Exception(string.Format("Failed to Post Records Reason{0}. Exception{1}", createResponse.ReasonPhrase, await createResponse.Content?.ReadAsStringAsync())); } }
/// <summary> /// Prints the specified message to the output stream if the current log level is >= level. /// This method is thread-safe. All output is prepended with the date & time, and log level. /// </summary> /// <example>2016-05-21 19:10:01Z INFO: This is the message.</example> /// <param name="level">The logging level of this message.</param> /// <param name="writer">The stream to where the output is sent.</param> /// <param name="format">The format string to be printed.</param> /// <param name="args">(optional) The arguments for the format string.</param> protected void Write(VerboseLevel level, TextWriter writer, string format, params Object[] args) { ThrowIf.ArgumentNull(writer, nameof(writer)); if (ShouldWrite(level)) { string datetime = DateTime.Now.ToString("u", CultureInfo.InvariantCulture); format = StringUtils.FormatInvariant("{0} {1}: {2}", datetime, level.ToString(), format); lock (_lock) { if (args == null) { writer.WriteLine(format); } else { writer.WriteLine(format, args); } } } }
/// <summary> /// delete entity record /// </summary> /// <param name="entitySetName">example: contacts, opportunities, accounts</param> /// <example>contacts, opportunities </example> /// <param name="id">record id</param> /// <returns>sucesss</returns> async Task <bool> ICrmApiService.DeleteRecord(string entitySetName, Guid id) { ThrowIf.ArgumentNull("entityLogicalName can't be null", entitySetName); ThrowIf.ArgumentNull("Record Id can't be blank", id); string requestUri = string.Format("{0}{1}({2})", HttpCrmClient.BaseAddress, entitySetName, id); HttpResponseMessage deleteResponse = await HttpCrmClient.DeleteAsync(requestUri); string responseBody = await deleteResponse.Content.ReadAsStringAsync(); if (deleteResponse.IsSuccessStatusCode) //200-299 { Console.WriteLine("Entity deleted: \n{0}.", id); return(true); } else if (deleteResponse.StatusCode == HttpStatusCode.NotFound) //404 { throw new HttpRequestException($"Entity not found: {id} with execption: {responseBody}.\nReasonPhase:{deleteResponse.ReasonPhrase}"); } else { throw new HttpRequestException($"Failed to delete record: {id} with execption: {responseBody}.\nReasonPhase:{deleteResponse.ReasonPhrase}"); } }
public override void Validate(X509Certificate2 certificate) { // Check that there is a certificate. ThrowIf.ArgumentNull(certificate, nameof(certificate)); if (_allowedCertificate.IssuerName.Name != certificate.IssuerName.Name) { throw new FederatedAuthenticationException( "Certificate was not issued by a trusted issuer", FederatedAuthenticationErrorCode.NotTrustedIssuer); } if (_allowedCertificate.Thumbprint != certificate.Thumbprint) { throw new FederatedAuthenticationException( "Invalid thumbprint! Certificate was not issued by a trusted issuer", FederatedAuthenticationErrorCode.NotTrustedIssuer); } if (!IsValidCertificateTime(certificate.NotBefore, certificate.NotAfter)) { throw new FederatedAuthenticationException( "Invalid usage time! Certificate was not issued by a trusted issuer", FederatedAuthenticationErrorCode.NotTrustedIssuer); } if (_verifyCertificateChain) { if (!certificate.Verify()) { CollectAndLogValidationInfo(certificate); throw new FederatedAuthenticationException("Certificate Validation Failed", FederatedAuthenticationErrorCode.CertificateValidation); } } }
/// <summary> /// Read Azure KeyVault /// </summary> public void ReadKeyVault() { try { string keyVaultUrl = string.Empty; string crmInstanceConnection = string.Empty; string appId = string.Empty; string appKey = string.Empty; string authorityURL = string.Empty; ////Read the values from KeyVault Synchronously if (ConfigurationManager.AppSettings.AllKeys.Contains(Constants.KeyVaultUrl)) { keyVaultUrl = ConfigurationManager.AppSettings[Constants.KeyVaultUrl]; } if (ConfigurationManager.AppSettings.AllKeys.Contains(Constants.CrmInstanceConnection)) { crmInstanceConnection = ConfigurationManager.AppSettings[Constants.CrmInstanceConnection]; } if (ConfigurationManager.AppSettings.AllKeys.Contains(Constants.KeyVaultClientId)) { this.clientId = ConfigurationManager.AppSettings[Constants.KeyVaultClientId]; } if (ConfigurationManager.AppSettings.AllKeys.Contains(Constants.KeyVaultClientKey)) { this.clientSecret = ConfigurationManager.AppSettings[Constants.KeyVaultClientKey]; } if (ConfigurationManager.AppSettings.AllKeys.Contains(Constants.ResourceURL)) { this.resourceURL = ConfigurationManager.AppSettings[Constants.ResourceURL]; } if (ConfigurationManager.AppSettings.AllKeys.Contains(Constants.AppClientId)) { appId = ConfigurationManager.AppSettings[Constants.AppClientId]; } if (ConfigurationManager.AppSettings.AllKeys.Contains(Constants.AppClientKey)) { appKey = ConfigurationManager.AppSettings[Constants.AppClientKey]; } if (ConfigurationManager.AppSettings.AllKeys.Contains(Constants.AppClientKey)) { appKey = ConfigurationManager.AppSettings[Constants.AppClientKey]; } if (ConfigurationManager.AppSettings.AllKeys.Contains(Constants.AuthorityURL)) { authorityURL = ConfigurationManager.AppSettings[Constants.AuthorityURL]; } ThrowIf.ArgumentNull(keyVaultUrl, "Key Vault can not be null"); ThrowIf.ArgumentNull(crmInstanceConnection, "crmInstanceConnection can not be null"); ThrowIf.ArgumentNull(this.clientSecret, "clientSecret can not be null"); ThrowIf.ArgumentNull(this.clientId, "clientId can not be null"); KeyVaultClient kv = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(this.GetToken)); this.CRMConnection = kv.GetSecretAsync(keyVaultUrl, crmInstanceConnection, new CancellationToken()).GetAwaiter().GetResult().Value; this.appClientID = kv.GetSecretAsync(keyVaultUrl, appId, new CancellationToken()).GetAwaiter().GetResult().Value; this.appClientSecret = kv.GetSecretAsync(keyVaultUrl, appKey, new CancellationToken()).GetAwaiter().GetResult().Value; this.authority = kv.GetSecretAsync(keyVaultUrl, authorityURL, new CancellationToken()).GetAwaiter().GetResult().Value; } catch (Exception ex) { this.logger.Error("Exception in keyVault Read", ex); throw; } }