public async Task <GoogleResponse> GetTimezoneNameAsync(float lat, float lon, int dt) { var key = _configuration.GetSection("Google").GetSection("GoogleApiKey").Value; var latStr = lat.ToString(System.Globalization.CultureInfo.InvariantCulture); var lonStr = lon.ToString(System.Globalization.CultureInfo.InvariantCulture); using (var client = new HttpClient()) { try { client.BaseAddress = new Uri(_configuration.GetSection("Google").GetSection("GoogleApiURL").Value); var response = await client.GetAsync($"/maps/api/timezone/json?location={latStr},{lonStr}×tamp={dt}&language=es&key={key}"); response.EnsureSuccessStatusCode(); var stringResult = await response.Content.ReadAsStringAsync(); GoogleResponse googleResult = JsonConvert.DeserializeObject <GoogleResponse>(stringResult); return(googleResult); } catch (HttpRequestException httpRequestException) { throw new Exception("Error on google call", httpRequestException); } } }
public async Task <long> GetTotalResultsAsync(string query) { if (string.IsNullOrEmpty(query)) { throw new ArgumentException("The term cannot be null or empty", nameof(query)); } string customSearchRequestUri = GoogleConfig.BaseUrl .Replace("{ApiKey}", GoogleConfig.ApiKey) .Replace("{Context}", GoogleConfig.Cx) .Replace("{Query}", query); var response = await _client.GetAsync(customSearchRequestUri); using (response) { if (!response.IsSuccessStatusCode) { throw new Exception("Request not processed."); } GoogleResponse results = JsonHelper .Deserialize <GoogleResponse> (await response.Content.ReadAsStringAsync()); return(long.Parse(results.searchInformation.totalResults)); } }
public async Task <ActionResult <LoginResponseDto> > Authenticate(LoginDto loginDto) { GoogleResponse googleResponse = await GetGoogleDetails(loginDto.GoogleIdToken); if (string.IsNullOrWhiteSpace(googleResponse?.GoogleUserId)) { return(Unauthorized()); } var user = context.Users.SingleOrDefault(row => row.GoogleUserId == googleResponse.GoogleUserId); if (user == null) { user = new User { GoogleUserId = googleResponse.GoogleUserId, Name = loginDto.User.Name, CreatedUtc = DateTime.UtcNow, ProfileImageUrl = loginDto.User.Picture.ToString(), RefreshToken = GenerateRefreshToken(), }; context.Users.Add(user); context.SaveChanges(); } string accessToken = CreateAccessToken(user.UserId, user.IsAdmin); return(new LoginResponseDto { RefreshToken = user.RefreshToken, AccessToken = accessToken, User = GetUser(user.UserId), }); }
public async Task <FirebaseAuthResponseModel> SigninWithGoogle() { try { FirebaseAuthResponseModel response = new FirebaseAuthResponseModel() { Status = true, Response = "Successfully signed in to Google." }; CrossGoogleClient.Current.Logout(); GoogleResponse <Plugin.GoogleClient.Shared.GoogleUser> data = await CrossGoogleClient.Current.LoginAsync(); if (data.Status == GoogleActionStatus.Completed) { response = await LoginWithEmailPassword(data.Data.Email, data.Data.GivenName + data.Data.FamilyName); return(response); } else { response.Status = false; response.Response = data.Message; } return(response); } catch (Exception ex) { FirebaseAuthResponseModel response = new FirebaseAuthResponseModel() { Status = false, Response = ex.Message }; return(response); } }
private void BuildResults(List <string> queries) { List <GoogleResponse> responses = new List <GoogleResponse>(); foreach (string query in queries) { var response = new GoogleResponse() { Queries = new QueriesResponse() { Request = new List <TotalResultsResponse>() { new TotalResultsResponse() { TotalResults = _faker.Random.ULong(), SearchTerms = query } } } }; responses.Add(response); } ExpectedResults = responses; }
/// <summary> /// Is recaptcha passed. /// </summary> /// <param name="googleRecaptchaResponse">Recaptcha response from Google.</param> /// <param name="secret">Secret key string.</param> /// <returns>Result: true or false.</returns> public async Task <bool> IsReCaptchaPassedAsync(string googleRecaptchaResponse, string secret) { HttpClient httpClient = new HttpClient(); FormUrlEncodedContent content = new FormUrlEncodedContent(new[] { new KeyValuePair <string, string>("secret", secret), new KeyValuePair <string, string>("response", googleRecaptchaResponse) }); HttpResponseMessage postResult = await httpClient.PostAsync($"https://www.google.com/recaptcha/api/siteverify", content); if (postResult.StatusCode != HttpStatusCode.OK) { return(false); } string jsonResult = postResult.Content.ReadAsStringAsync().Result; GoogleResponse jsonData = JsonSerializer.Deserialize <GoogleResponse>(jsonResult, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); return(jsonData.Success); }
public static VoiceTextData RecordText(int seconds) { string file = Path.GetTempFileName();// +".flac"; Recorder rec = new Recorder(file); System.Threading.Thread.Sleep(seconds * 1000); rec.Stop(); while (!rec.AllDone) { } GC.SuppressFinalize(rec); GoogleRecognizer recogn = new GoogleRecognizer(); GoogleResponse respdata = null; try { respdata = recogn.RecognizeFlac(file); } catch (Exception e) { respdata = null; } if (respdata == null) { return(null); } File.Delete(file); //Json return(new VoiceTextData() { Rating = respdata.result[0].alternative[0].confidence, Recognised = respdata.result[0].alternative[0].transcript }); }
public void SpellingSuggestionIsParsed() { var response = new GoogleResponse(SampleResponses.SpellingSuggestion); var results = response.SpellingSuggestions(); Assert.AreEqual("education", results[0]); }
public void TotalResultsIsParsed() { var response = new GoogleResponse(SampleResponses.ExampleResponseSelectedFields); var totalResults = response.TotalResults; Assert.AreEqual(194, totalResults); }
async Task <IActionResult> QUERY(GoogleRequest request) { //https://developers.google.com/actions/smarthome/create#actiondevicesquery var payload = request.inputs.First().payload as PayLoads.DevicesQueryInputPayload; var response = new GoogleResponse <PayLoads.DeviceQueryPayload>(request); return(Ok(response)); }
public void FirstResultIsParsed() { var response = new GoogleResponse(SampleResponses.ExampleResponseSelectedFields); var results = response.Results(); Assert.AreEqual("Videos of council meetings – East Sussex County Council", results[0].Title); Assert.AreEqual("https://www.eastsussex.gov.uk/yourcouncil/webcasts/", results[0].Url.ToString()); Assert.AreEqual("<b>Videos</b> of council meetings. Webcasts of meetings are available online for six months after the date of the meeting. They include index points that allow you to ...", results[0].Excerpt); }
public string findNearestStore(string zipcode, string storeName) { GoogleResponse response = new GoogleResponse(); //Instantiating google response object NearestStoreResponse storeResponse = new NearestStoreResponse(); //Instantiating places response object string formattedString = ""; string encodedZipCode = HttpUtility.UrlEncode(zipcode); var googleUrl = "https://maps.googleapis.com/maps/api/geocode/json?address=" + encodedZipCode + "&key=AIzaSyC3dCRXiBTV_f0i7Ap2ZgXWTaS933cfn8w"; //Googles geocode url with users zipcode input using (var webClient = new System.Net.WebClient()) { var json = webClient.DownloadString(googleUrl); //downloaded content from google url page response = JsonConvert.DeserializeObject <GoogleResponse>(json); //Deserializing content to response object } var lat = ""; var lng = ""; try //error handling { //setting lat , lng to results from google call lat = response.results[0].geometry.location.lat; lng = response.results[0].geometry.location.lng; } catch (Exception) { formattedString = "Your search result has returned zero places"; return(formattedString); } // Encode the string. string encodedStoreName = HttpUtility.UrlEncode(storeName); string nearestPlaceUrl = "https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input=" + encodedStoreName + "&inputtype=textquery&fields=formatted_address,name&locationbias=circle:32186@" + lat + "," + lng + "&key=AIzaSyC3dCRXiBTV_f0i7Ap2ZgXWTaS933cfn8w"; using (var webClient = new System.Net.WebClient()) { var json = webClient.DownloadString(nearestPlaceUrl); //downloaded content from google url page storeResponse = JsonConvert.DeserializeObject <NearestStoreResponse>(json); //Deserializing content to response object } if (storeResponse.status.Equals("OK")) { formattedString = storeResponse.candidates[0].name + " was found at " + storeResponse.candidates[0].formatted_address; } else { formattedString = "Your search result has returned zero places"; } return(formattedString); }
public async Task <object> Register([FromBody] UserRegister userRegister) { if (!ModelState.IsValid) { return(BadRequest(ModelState.Values.SelectMany(start => start.Errors).Select(error => error.ErrorMessage).Take(1).ElementAt(0))); } // Google Recaptcha Validation if (WebConfigurationManager.AppSettings["GoogleRecaptcha"] == "true") { GoogleResponse googleResponse = await _google.ValidateRecaptcha <GoogleResponse>(userRegister.Token); if (!googleResponse.Success) { return(BadRequest("error.validation.invalid-recaptcha")); } } // HCaptcha Validation if (WebConfigurationManager.AppSettings["HCaptcha"] == "true") { HCaptchaResponse hCaptchaResponse = await _hCaptcha.Validate <HCaptchaResponse>(userRegister.Token); if (!hCaptchaResponse.Success) { return(BadRequest("error.validation.invalid-hcaptcha")); } } UserRegisterResponse user = await _userService.Register(userRegister); if (user.ErrorEmail) { return(BadRequest("error.user.email-exists")); } if (user.ErrorCpf) { return(BadRequest("error.user.cpf-exists")); } // Register Mail if (WebConfigurationManager.AppSettings["Mail"] == "true") { string message = RenderRazor.RenderView("~/Views/MailTemplates/Register.cshtml", userRegister, null); MailService.SendMailAsync(userRegister.Email, new string[] { }, "Register", message); } return(Ok(user)); }
async Task <IActionResult> SYNC(GoogleRequest request) { //https://developers.google.com/actions/smarthome/create#actiondevicessync var response = new GoogleResponse <PayLoads.DevicesSyncPayLoad>(request); var UserId = GetUserId(); var GoogleUser = DataContext.GoogleUsers.FirstOrDefault(o => o.UserId == UserId); if (GoogleUser == null) { GoogleUser = new SmartDevices.Devices.GoogleUser { GoogleUserId = Guid.NewGuid(), UserId = UserId, ActivationDate = DateTime.UtcNow, Active = true }; await DataContext.GoogleUsers.AddAsync(GoogleUser); } else { if (GoogleUser.Active == false) { GoogleUser.Active = true; GoogleUser.ActivationDate = DateTime.UtcNow; } } await DataContext.SaveChangesAsync(); response.payload = new PayLoads.DevicesSyncPayLoad { agentUserId = UserId }; var UserDevices = await DataContext.Devices.Where(o => o.UserId == UserId).ToListAsync(); var googleDevices = from e in UserDevices select new ST.SmartDevices.Google.DeviceSYNC { id = e.DeviceId.ToString(), name = new DeviceName { name = e.Name, nicknames = e.NickNames.Select(o => o.NickName)?.ToArray() }, roomHint = e.Piece.Name, traits = e.Traits.Select(o => o.DeviceTraitId)?.ToArray(), type = e.DeviceType?.DeviceTypeId, willReportState = willReportState(e) }; response.payload.devices = googleDevices?.ToArray(); response.payload.agentUserId = UserId; return(Ok(response)); }
async Task <IActionResult> EXECUTE(GoogleRequest request) { //https://developers.google.com/actions/smarthome/create#actiondevicesexecute var userId = GetUserId(); var userChannel = SmartHubContext.Clients.User(userId); if (userChannel != null) { await userChannel.NewGoogleAction(Guid.Empty, ""); } var response = new GoogleResponse <PayLoads.DeviceExecuteResponsePayload>(request); return(Ok(response)); }
public async Task <IEnumerable <BookModel> > GetGoogleBooks(string query, int maxResults = 20) { var response = await _client.GetAsync($"volumes?q={query}&maxResults={maxResults}"); if (response.IsSuccessStatusCode) { var jsonString = await response.Content.ReadAsStringAsync(); GoogleResponse googleResponse = JsonConvert.DeserializeObject <GoogleResponse>(jsonString); return(googleResponse.Items); } throw new HttpRequestException(); }
public bool isCaptchaValid(string response, string key) { var requestString = string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", key, response); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestString); using (WebResponse captchaResponse = request.GetResponse()) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(GoogleResponse)); GoogleResponse gResponse = serializer.ReadObject(captchaResponse.GetResponseStream()) as GoogleResponse; return(gResponse.Success); } }
private Address BuildAddress(GoogleResponse googleResponse) { var address = new Address(); AddressComponent[] addressComponents = googleResponse .Results? .FirstOrDefault()? .AddressComponents; if (addressComponents == null || !addressComponents.Any()) { return(address); } foreach (AddressComponent component in addressComponents) { string type = component.Types?.FirstOrDefault(); switch (type?.ToLowerInvariant()) { case "street_number": address.StreetNumber = component.LongName; break; case "subpremise": address.Subremise = component.LongName; break; case "route": address.Route = component.LongName; break; case "locality": address.Locality = component.LongName; break; case "administrative_area_level_1": address.AdministrativeAreaLevel1 = component.LongName; break; case "administrative_area_level_2": address.AdministrativeAreaLevel2 = component.LongName; break; } } return(address); }
public static List <Book> MapGoogleResponse(GoogleResponse response) { return(response.Items.OrderBy(ww => ww.VolumeInfo.Title) .Take(10) .Select(ww => { return new Book() { Title = ww?.VolumeInfo?.Title, Photo_Url = ww?.VolumeInfo?.ImageLinks == null ? "NotFound" : ww.VolumeInfo.ImageLinks.Thumbnail, Author_Name = ww?.VolumeInfo?.Authors != null ? ww.VolumeInfo.Authors[0] : "NotFound", Description = ww?.VolumeInfo?.Description != null ? ww?.VolumeInfo?.Description : "NotFound", Categories = ww?.VolumeInfo?.Categories != null ? ww?.VolumeInfo?.Categories : new List <string>() }; } ).ToList()); }
public async Task RunTask() { if (string.IsNullOrWhiteSpace(_fileLocations.InputFilePath) || !File.Exists(_fileLocations.InputFilePath)) { throw new ArgumentNullException( nameof(_fileLocations.InputFilePath), "Your InputFile does not exists. Please, specify valid file names in the appSettings.json file"); } if (string.IsNullOrWhiteSpace(_fileLocations.OutputFilePath) || !File.Exists(_fileLocations.OutputFilePath)) { throw new ArgumentNullException( nameof(_fileLocations.OutputFilePath), "Your OutputFile does not exists. Please, specify valid file names in the appSettings.json file"); } if (!_validExtensions.Contains(Path.GetExtension(_fileLocations.InputFilePath))) { throw new ArgumentException( "Your InputFile is not correct. Only .txt and .csv files are allowed"); } if (!_validExtensions.Contains(Path.GetExtension(_fileLocations.OutputFilePath))) { throw new ArgumentException( "Your OutputFile is not correct. Only .txt and .csv files are allowed"); } string[] lines = File.ReadLines(_fileLocations.InputFilePath).ToArray(); foreach (string inputAddress in lines) { var inputAddressValid = inputAddress.Trim('"', ',', ';'); GoogleResponse googleResponse = await _googleService.ValidateAsync(inputAddressValid); string validatedAddress = _addressBuilder.BuildAddressString(googleResponse); Console.WriteLine($"{inputAddressValid};{validatedAddress}"); using (StreamWriter streamWriter = new StreamWriter(_fileLocations.OutputFilePath, true)) { streamWriter.WriteLine($"{inputAddressValid};{validatedAddress}"); } } }
public async Task <FirebaseAuthResponseModel> SignUpWithGoogle() { try { FirebaseAuthResponseModel response = new FirebaseAuthResponseModel() { Status = true, Response = "Sign up successful. Verification email sent." }; CrossGoogleClient.Current.Logout(); GoogleResponse <Plugin.GoogleClient.Shared.GoogleUser> data = await CrossGoogleClient.Current.LoginAsync(); if (data.Status == GoogleActionStatus.Completed) { await FirebaseAuth.Instance.CreateUserWithEmailAndPasswordAsync(data.Data.Email, data.Data.GivenName + data.Data.FamilyName); FirebaseAuth.Instance.CurrentUser.SendEmailVerification(); int ndx = data.Data.Email.IndexOf("@"); int cnt = data.Data.Email.Length - ndx; string defaultName = string.IsNullOrEmpty(data.Data.GivenName + " " + data.Data.FamilyName) ? data.Data.Email.Remove(ndx, cnt) : data.Data.GivenName + " " + data.Data.FamilyName; dataClass.LoggedInUser = new Account() { Uid = FirebaseAuth.Instance.CurrentUser.Uid, Email = data.Data.Email, UserName = defaultName, UserType = 1, CreatedAt = DateTime.UtcNow }; } else { response.Status = false; response.Response = data.Message; } return(response); } catch (Exception ex) { FirebaseAuthResponseModel response = new FirebaseAuthResponseModel() { Status = false, Response = ex.Message }; return(response); } }
/// <summary> /// Search /// </summary> /// <param name="keyword">keyword</param> /// <returns></returns> public async Task <GoogleResponse> Search(string keyword) { string apiKey = _configurationGoogleOptions.ApiKey; string cx = _configurationGoogleOptions.Cx; string uri = _configurationGoogleOptions.Uri; var request = WebRequest.Create(uri + apiKey + "&cx=" + cx + "&q=" + keyword.ToUpper()); var response = (HttpWebResponse)request.GetResponse(); var dataStream = response.GetResponseStream(); var reader = new StreamReader(dataStream); var responseString = await reader.ReadToEndAsync(); //get json and convert to object GoogleResponse googleReponse = JsonConvert.DeserializeObject <GoogleResponse>(responseString); return(googleReponse); }
// This function returns user's Google profile. public async Task <GoogleResponse> GetGoogleUser(AuthenticatorCompletedEventArgs googleAccount) { GoogleResponse googleDate = null; try { var request = new OAuth2Request("GET", new Uri(Constant.GoogleUserInfoUrl), null, googleAccount.Account); var GoogleResponse = await request.GetResponseAsync(); var googelUserData = GoogleResponse.GetResponseText(); googleDate = JsonConvert.DeserializeObject <GoogleResponse>(googelUserData); } catch { } return(googleDate); }
public async Task <GoogleResponse> ValidateAsync(string address) { var url = $"{_httpClient.BaseAddress}?address={address}&language=uk&key={_googleSettings.Key}"; HttpResponseMessage result = await _httpClient.GetAsync(url); if (result.IsSuccessStatusCode) { string json = await result.Content.ReadAsStringAsync(); GoogleResponse googleResponse = JsonConvert.DeserializeObject <GoogleResponse>(json); return(googleResponse); } else { Console.WriteLine($"Response Status Code is not successful ({result.StatusCode}) for address: {address}"); return(null); } }
public ContentResult Post([FromBody] GoogleRequest value) { var query = value.queryResult.queryText; var sessionId = value.session; var intent = value.queryResult.intent; _client.SendBotMessage(query, sessionId).Wait(); var replies = _client.ReadBotMessages(sessionId).Result; //TODO: This pulls the last message sent by the bot. Could break for multiple messages sent var reply = replies.LastOrDefault(); var response = new GoogleResponse(reply); var json = Newtonsoft.Json.JsonConvert.SerializeObject(response); var res = json.ToString(); return(Content(json.ToString(), "application/json")); }
public async Task <ActionResult <LoginResponseDto> > Authenticate(LoginDto loginDto) { GoogleResponse googleResponse = await GetGoogleDetails(loginDto.GoogleAccessToken); if (string.IsNullOrWhiteSpace(googleResponse?.GoogleUserId)) { return(Unauthorized()); } var user = context.User.SingleOrDefault(row => row.GoogleUserId == googleResponse.GoogleUserId); if (user == null) { user = new User { GoogleUserId = googleResponse.GoogleUserId, Name = googleResponse.Name }; context.User.Add(user); context.SaveChanges(); } var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(appSettings.Value.SecurityKey)); var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var claims = new List <Claim> { new Claim(ClaimsIdentity.DefaultNameClaimType, user.UserId.ToString()), }; var token = new JwtSecurityToken( issuer: "samorme.com", audience: "samorme.com", claims: claims, signingCredentials: credentials); return(new LoginResponseDto { Name = googleResponse.Name, AccessToken = new JwtSecurityTokenHandler().WriteToken(token), }); }
public async void GoogleUserProfileAsync(string accessToken, string refreshToken, AuthenticatorCompletedEventArgs e) { var client = new HttpClient(); var socialLogInPost = new SocialLogInPost(); var request = new OAuth2Request("GET", new Uri(Constant.GoogleUserInfoUrl), null, e.Account); var GoogleResponse = await request.GetResponseAsync(); var userData = GoogleResponse.GetResponseText(); GoogleResponse googleData = JsonConvert.DeserializeObject <GoogleResponse>(userData); socialLogInPost.email = googleData.email; socialLogInPost.password = ""; socialLogInPost.token = refreshToken; socialLogInPost.signup_platform = "GOOGLE"; var socialLogInPostSerialized = JsonConvert.SerializeObject(socialLogInPost); var postContent = new StringContent(socialLogInPostSerialized, Encoding.UTF8, "application/json"); var RDSResponse = await client.PostAsync(Constant.LogInUrl, postContent); var responseContent = await RDSResponse.Content.ReadAsStringAsync(); if (RDSResponse.IsSuccessStatusCode) { if (responseContent != null) { if (responseContent.Contains(Constant.EmailNotFound)) { Application.Current.MainPage = new SocialLogInSignUp(googleData.given_name, googleData.family_name, googleData.email, accessToken, refreshToken, "GOOGLE"); } if (responseContent.Contains(Constant.AutheticatedSuccesful)) { Application.Current.MainPage = new HomePage(); } } } }
public async Task <long> GetTotalResultsAsync(string query) { if (string.IsNullOrEmpty(query)) { throw new ArgumentException("The specified parameter is invalid.", nameof(query)); } string searchRequest = GoogleConfig.BaseUrl.Replace("{Key}", GoogleConfig.ApiKey) .Replace("{Context}", GoogleConfig.ContextId) .Replace("{Query}", query); using (var response = await _client.GetAsync(searchRequest)) { if (!response.IsSuccessStatusCode) { throw new Exception("We weren't able to process your request. Please try again later."); } GoogleResponse results = JsonHelper.Deserialize <GoogleResponse>(await response.Content.ReadAsStringAsync()); return(long.Parse(results.SearchInformation.TotalResults)); } }
public async Task <object> Login([FromBody] UserLogin userLogin) { if (!ModelState.IsValid) { return(BadRequest(ModelState.Values.SelectMany(start => start.Errors).Select(error => error.ErrorMessage).Take(1).ElementAt(0))); } // Google Recaptcha Validation if (WebConfigurationManager.AppSettings["GoogleRecaptcha"] == "true") { GoogleResponse googleResponse = await _google.ValidateRecaptcha <GoogleResponse>(userLogin.Token); if (!googleResponse.Success) { return(BadRequest("error.validation.invalid-recaptcha")); } } // HCaptcha Validation if (WebConfigurationManager.AppSettings["HCaptcha"] == "true") { HCaptchaResponse hCaptchaResponse = await _hCaptcha.Validate <HCaptchaResponse>(userLogin.Token); if (!hCaptchaResponse.Success) { return(BadRequest("error.validation.invalid-hcaptcha")); } } object user = await _userService.Auth(userLogin); if (user == null) { return(BadRequest("error.validation.incorrect-login")); } return(Ok(user)); }
public string BuildAddressString(GoogleResponse googleResponse) { if (googleResponse == null) { return(string.Empty); } Address address = BuildAddress(googleResponse); var sb = new StringBuilder(); List <string> componentsList = new List <string>(); componentsList.Add(address.AdministrativeAreaLevel1); if (!string.IsNullOrWhiteSpace(address.AdministrativeAreaLevel2) && !address.AdministrativeAreaLevel2.Contains(Exception)) { componentsList.Add(address.AdministrativeAreaLevel2); } componentsList.Add(address.Locality); componentsList.Add(address.Route); componentsList.Add(address.StreetNumber); componentsList.Add(address.Subremise); var componentsArray = componentsList .Where(x => !string.IsNullOrWhiteSpace(x)) .ToArray(); if (!componentsArray.Any()) { return(string.Empty); } sb.AppendJoin(", ", componentsArray); return(sb.ToString()); }