Here are the examples of the csharp api System.IO.StreamReader.ReadToEndAsync() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
961 Examples
19
Source : HttpResponseParserTest.cs
with Apache License 2.0
from Asesjix
with Apache License 2.0
from Asesjix
[Fact]
public async Task ParseStreamContentAsync_Success_TestAsync()
{
var httpResponse = CreateTestResponse();
using (var ticketStream = await new HttpResponseParser()
.UseHttpResponse(httpResponse)
.ParseStreamContentAsync())
using (var reader = new StreamReader(ticketStream))
{
var ticketString = await reader.ReadToEndAsync();
replacedert.Equal(TestConstants.TicketSerialized, ticketString);
}
}
19
Source : DaumCafeSession.cs
with GNU Affero General Public License v3.0
from asmejkal
with GNU Affero General Public License v3.0
from asmejkal
public async Task Authenticate(CancellationToken ct)
{
async Task<string> GetFuid()
{
var request = WebRequest.CreateHttp("https://logins.daum.net/accounts/signinform.do");
request.Method = "GET";
request.Headers["Connection"] = "keep-alive";
request.Headers["Cache-Control"] = "max-age=0";
request.Headers["Upgrade-Insecure-Requests"] = "1";
request.Headers["User-Agent"] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36";
request.Headers["Accept"] = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8";
request.Headers["Accept-Encoding"] = "gzip, deflate, br";
request.Headers["Accept-Language"] = "en,cs-CZ;q=0.9,cs;q=0.8";
using (var response = await request.GetResponseAsync(ct))
using (var stream = response.GetResponseStream())
using (var gzipStream = new GZipStream(stream, CompressionMode.Decompress))
using (var reader = new StreamReader(gzipStream))
{
var content = await reader.ReadToEndAsync();
var doc = new HtmlDoreplacedent();
doc.LoadHtml(content);
return doc.DoreplacedentNode.Descendants("input").FirstOrDefault(x => x.GetAttributeValue("name", "") == "fuid")?.GetAttributeValue("value", "");
}
}
var fuid = await GetFuid();
if (string.IsNullOrWhiteSpace(fuid))
throw new NodeNotFoundException("Cannot find FUID.");
var request = WebRequest.CreateHttp($"https://logins.daum.net/accounts/login.do");
request.Method = "POST";
request.Headers["Connection"] = "keep-alive";
request.Headers["Cache-Control"] = "max-age=0";
request.Headers["Origin"] = "https://logins.daum.net";
request.Headers["Upgrade-Insecure-Requests"] = "1";
request.ContentType = "application/x-www-form-urlencoded";
request.Headers["User-Agent"] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36"; // required
request.Headers["Accept"] = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8";
request.Headers["Referer"] = "https://logins.daum.net/accounts/signinform.do"; // required
request.Headers["Accept-Encoding"] = "gzip, deflate, br";
request.Headers["Accept-Language"] = "en,cs-CZ;q=0.9,cs;q=0.8";
request.CookieContainer = new CookieContainer();
using (var stream = await request.GetRequestStreamAsync())
using (var writer = new StreamWriter(stream, System.Text.Encoding.ASCII, 1, false))
{
await writer.WriteAsync($"url=https%3A%2F%2Fwww.daum.net%2F&relative=&weblogin=1&service=&fuid={fuid}&slevel=1&finaldest=&reloginSeq=0&id={_credential.Item1}&pw=");
await _credential.Item2.ForEach(async x => { await writer.WriteAsync((char)x); });
}
using (var response = await request.GetResponseAsync(ct))
{
// Expire old cookies
foreach (Cookie cookie in _handler.CookieContainer.GetCookies(new Uri("https://daum.net")))
cookie.Expired = true;
if (response.ResponseUri.ToString().Contains("releasecountryrestrict"))
throw new CountryBlockException(); // Failed because of logging in from a different country
if (response.Cookies.Count <= 0)
throw new LoginFailedException();
// Add new cookies
foreach (Cookie cookie in response.Cookies)
_handler.CookieContainer.Add(new Uri($"https://{cookie.Domain}{cookie.Path}"), cookie);
}
}
19
Source : BitlyUrlShortener.cs
with GNU Affero General Public License v3.0
from asmejkal
with GNU Affero General Public License v3.0
from asmejkal
public async Task<string> ShortenAsync(string url)
{
var request = WebRequest.CreateHttp("https://api-ssl.bitly.com/v4/bitlinks");
request.Method = "POST";
request.ContentType = "application/json";
request.Headers["Authorization"] = "Bearer " + _apiKey;
using (var writer = new StreamWriter(await request.GetRequestStreamAsync(), Encoding.ASCII))
await writer.WriteAsync("{\"long_url\": \"" + url + "\"}");
using (var response = (HttpWebResponse)await request.GetResponseAsync())
using (var stream = response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
var content = await reader.ReadToEndAsync();
var o = JObject.Parse(content);
return (string)o["link"];
}
}
19
Source : GoogleHelpers.cs
with GNU Affero General Public License v3.0
from asmejkal
with GNU Affero General Public License v3.0
from asmejkal
public static async Task<GoogleAccountCredentials> ParseServiceAccountKeyFile(string path)
{
using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read))
using (var reader = new StreamReader(stream))
{
var data = await reader.ReadToEndAsync();
var o = JObject.Parse(data);
return new GoogleAccountCredentials()
{
Email = (string)o["client_email"],
Id = (string)o["client_id"],
Key = (string)o["private_key"],
};
}
}
19
Source : PolrUrlShortener.cs
with GNU Affero General Public License v3.0
from asmejkal
with GNU Affero General Public License v3.0
from asmejkal
public async Task<string> ShortenAsync(string url)
{
var request = WebRequest.CreateHttp($"{_domain}/api/v2/action/shorten?key={_apiKey}&url={Uri.EscapeDataString(url)}&is_secret=false");
using (var response = (HttpWebResponse)await request.GetResponseAsync())
using (var stream = response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
return await reader.ReadToEndAsync();
}
}
19
Source : SpotifyClient.cs
with GNU Affero General Public License v3.0
from asmejkal
with GNU Affero General Public License v3.0
from asmejkal
public async Task<string> SearchTrackId(string query)
{
var request = WebRequest.CreateHttp($"https://api.spotify.com/v1/search?q={Uri.EscapeDataString(query)}&type=track&limit=1");
request.Headers.Add("Authorization", $"Bearer {await GetToken()}");
using (var response = (HttpWebResponse)await request.GetResponseAsync())
using (var reader = new StreamReader(response.GetResponseStream()))
{
var text = await reader.ReadToEndAsync();
dynamic root = JObject.Parse(text);
dynamic item = (root.tracks?.items as JArray)?.FirstOrDefault();
return (string)item?.id;
}
}
19
Source : SpotifyClient.cs
with GNU Affero General Public License v3.0
from asmejkal
with GNU Affero General Public License v3.0
from asmejkal
public async Task<string> SearchTrackUrl(string query)
{
var request = WebRequest.CreateHttp($"https://api.spotify.com/v1/search?q={Uri.EscapeDataString(query)}&type=track&limit=1");
request.Headers.Add("Authorization", $"Bearer {await GetToken()}");
using (var response = (HttpWebResponse)await request.GetResponseAsync())
using (var reader = new StreamReader(response.GetResponseStream()))
{
var text = await reader.ReadToEndAsync();
dynamic root = JObject.Parse(text);
dynamic item = (root.tracks?.items as JArray)?.FirstOrDefault();
return (string)item?.external_urls?.spotify;
}
}
19
Source : ViewsModule.cs
with GNU Affero General Public License v3.0
from asmejkal
with GNU Affero General Public License v3.0
from asmejkal
private async Task<YoutubeInfo> GetYoutubeInfo(IEnumerable<string> ids, string youtubeKey)
{
string url = $"https://www.googleapis.com/youtube/v3/videos?part=statistics,snippet&id={string.Join(",", ids)}&key={youtubeKey}";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
using (HttpWebResponse response = (HttpWebResponse)(await request.GetResponseAsync()))
using (Stream stream = response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
var html = await reader.ReadToEndAsync();
var json = JObject.Parse(html);
ulong totalViews = 0;
ulong totalLikes = 0;
DateTime firstPublishedAt = DateTime.Now;
var items = json["items"];
foreach (var item in items)
{
var statistics = item["statistics"];
totalViews += (ulong)statistics["viewCount"];
totalLikes += (ulong?)statistics["likeCount"] ?? 0;
var publishedAt = (DateTime)item["snippet"]["publishedAt"];
if (publishedAt < firstPublishedAt)
firstPublishedAt = publishedAt;
}
YoutubeInfo info = new YoutubeInfo();
info.Views = totalViews;
info.Likes = totalLikes;
info.PublishedAt = firstPublishedAt;
return info;
}
}
19
Source : SpotifyHelpers.cs
with GNU Affero General Public License v3.0
from asmejkal
with GNU Affero General Public License v3.0
from asmejkal
public static async Task<(string Token, int ExpiresIn)> RefreshToken(string refreshToken, string clientId, string clientSecret)
{
var request = WebRequest.CreateHttp("https://accounts.spotify.com/api/token");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Headers.Add("Authorization", BuildAuthorizationHeader(clientId, clientSecret));
using (var writer = new StreamWriter(await request.GetRequestStreamAsync(), Encoding.ASCII))
{
await writer.WriteAsync($"grant_type=refresh_token&refresh_token={refreshToken}");
}
using (var response = (HttpWebResponse)await request.GetResponseAsync())
using (var reader = new StreamReader(response.GetResponseStream()))
{
var text = await reader.ReadToEndAsync();
var root = JObject.Parse(text);
return ((string)root["access_token"], (int)root["expires_in"]);
}
}
19
Source : SpotifyHelpers.cs
with GNU Affero General Public License v3.0
from asmejkal
with GNU Affero General Public License v3.0
from asmejkal
public static async Task<(string Token, int ExpiresIn)> GetClientToken(string clientId, string clientSecret)
{
var request = WebRequest.CreateHttp("https://accounts.spotify.com/api/token");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Headers.Add("Authorization", BuildAuthorizationHeader(clientId, clientSecret));
using (var writer = new StreamWriter(await request.GetRequestStreamAsync(), Encoding.ASCII))
await writer.WriteAsync("grant_type=client_credentials");
using (var response = (HttpWebResponse)await request.GetResponseAsync())
using (var reader = new StreamReader(response.GetResponseStream()))
{
var text = await reader.ReadToEndAsync();
dynamic root = JObject.Parse(text);
return ((string)root["access_token"], (int)root["expires_in"]);
}
}
19
Source : ReactionsModule.cs
with GNU Affero General Public License v3.0
from asmejkal
with GNU Affero General Public License v3.0
from asmejkal
[Command("reactions", "import", "Adds all reactions from a file.")]
[Alias("reaction", "import", true)]
[Comment("Attach a file with reactions obtained with `reactions export`. Expected format: \n`[{\"trigger1\":\"value1\"},{\"trigger2\":\"value2\"}]` \n\nAlternative format (doesn't allow duplicates): \n`{\"trigger1\":\"value1\",\"trigger2\":\"value2\"}`")]
public async Task ImportReactions(ICommand command)
{
await replacedertPrivileges(command.Author, command.GuildId);
if (!command.Message.Attachments.Any())
throw new IncorrectParametersCommandException("You need to attach a file with reactions obtained with `reactions export`.", true);
var attachment = command.Message.Attachments.First();
var request = WebRequest.CreateHttp(attachment.Url);
using (var response = await request.GetResponseAsync())
using (var stream = response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
var content = await reader.ReadToEndAsync();
ICollection<Dictionary<string, string>> reactions;
try
{
reactions = JsonConvert.DeserializeObject<ICollection<Dictionary<string, string>>>(content);
}
catch (JsonException)
{
try
{
// Try the second format
reactions = new[] { JsonConvert.DeserializeObject<Dictionary<string, string>>(content) };
}
catch (JsonException)
{
throw new IncorrectParametersCommandException("The provided file is invalid.", true);
}
}
await _settings.Modify(command.GuildId, (ReactionsSettings s) =>
{
foreach (var reaction in reactions.SelectMany(x => x))
{
var newId = s.NextReactionId++;
s.Reactions.Add(new Reaction() { Id = newId, Trigger = reaction.Key, Value = reaction.Value });
}
});
await command.ReplySuccess($"Added {reactions.Count} reactions!");
}
}
19
Source : TranslatorModule.cs
with GNU Affero General Public License v3.0
from asmejkal
with GNU Affero General Public License v3.0
from asmejkal
[Command("translate", "Translates a piece of text.")]
[Alias("tr"), Alias("번역")]
[Parameter("From", LanguageRegex, ParameterType.String, "the language of the message")]
[Parameter("To", LanguageRegex, ParameterType.String, "the language to translate into")]
[Parameter("Message", ParameterType.String, ParameterFlags.Remainder, "the word or sentence you want to translate")]
[Comment("Korean = `ko` \nreplacedan = `ja` \nEnglish = `en` \nChinese(Simplified) = `zh-CH` \nChinese(Traditional) = `zh-TW` \nSpanish = `es` \nFrench = `fr` \nGerman = `de` \nRussian = `ru` \nPortuguese = `pt` \nItalian = `it` \nVietnamese = `vi` \nThai = `th` \nIndonesian = `id`")]
[Example("ko en 사랑해")]
public async Task Translate(ICommand command, ILogger logger)
{
await command.Message.Channel.TriggerTypingAsync();
var stringMessage = command["Message"].ToString();
var firstLang = command["From"].ToString();
var lastLang = command["To"].ToString();
var byteDataParams = Encoding.UTF8.GetBytes($"source={Uri.EscapeDataString(firstLang)}&target={Uri.EscapeDataString(lastLang)}&text={Uri.EscapeDataString(stringMessage)}");
try
{
var request = WebRequest.CreateHttp("https://openapi.naver.com/v1/papago/n2mt");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Headers.Add("X-Naver-Client-Id", _integrationOptions.Value.PapagoClientId);
request.Headers.Add("X-Naver-Client-Secret", _integrationOptions.Value.PapagoClientSecret);
request.ContentLength = byteDataParams.Length;
using (var st = request.GetRequestStream())
{
st.Write(byteDataParams, 0, byteDataParams.Length);
}
using (var responseClient = await request.GetResponseAsync())
using (var reader = new StreamReader(responseClient.GetResponseStream()))
{
var parserObject = JObject.Parse(await reader.ReadToEndAsync());
var trMessage = parserObject["message"]["result"]["translatedText"].ToString();
var translateSentence = trMessage.Truncate(EmbedBuilder.MaxDescriptionLength);
EmbedBuilder embedBuilder = new EmbedBuilder()
.Withreplacedle($"Translation from **{firstLang.ToUpper()}** to **{lastLang.ToUpper()}**")
.WithDescription(translateSentence)
.WithColor(new Color(0, 206, 56))
.WithFooter("Powered by Papago");
await command.Reply(embedBuilder.Build());
}
}
catch (WebException ex) when (ex.Response is HttpWebResponse r && r.StatusCode == HttpStatusCode.BadRequest)
{
throw new IncorrectParametersCommandException("Unsupported language combination.");
}
catch (WebException ex)
{
logger.LogError(ex, "Failed to reach Papago");
await command.Reply($"Couldn't reach Papago (error {(ex.Response as HttpWebResponse)?.StatusCode.ToString() ?? ex.Status.ToString()}). Please try again in a few seconds.");
}
}
19
Source : LastFmClient.cs
with GNU Affero General Public License v3.0
from asmejkal
with GNU Affero General Public License v3.0
from asmejkal
public async Task<LastFmArtistDetail> GetArtistDetail(string artist, LastFmDataPeriod period)
{
try
{
var infoTask = GetArtistInfo(artist);
var request = WebRequest.CreateHttp($"https://www.last.fm/user/{User}/library/music/{Uri.EscapeDataString(artist)}?date_preset={StatsPeriodWebMapping[period]}");
request.Timeout = (int)RequestTimeout.TotalMilliseconds;
using (var response = (HttpWebResponse)await request.GetResponseAsync())
using (var reader = new StreamReader(response.GetResponseStream()))
{
var content = await reader.ReadToEndAsync();
var doc = new HtmlDoreplacedent();
doc.LoadHtml(content);
// Get artist info
var info = await infoTask;
if (info == null)
return null;
// Get avatar (we can't get it via the API because it never actually has the artist's image...)
var image = doc.DoreplacedentNode.Descendants("span")
.FirstOrDefault(x => x.HasClreplaced("library-header-image"))?
.Descendants("img")
.FirstOrDefault()?
.GetAttributeValue("src", null)?
.Replace("avatar70s", "avatar170s");
// Get playcount and count of listened albums and tracks (in that order)
var metadata = doc.DoreplacedentNode
.Descendants("p")
.Where(x => x.HasClreplaced("metadata-display") && x.ParentNode.HasClreplaced("metadata-item"))
.Select(x => int.Parse(x.InnerText, System.Globalization.NumberStyles.Any, new System.Globalization.CultureInfo("en-US")))
.ToList();
var playcount = metadata.ElementAtOrDefault(0);
var albumsListened = metadata.ElementAtOrDefault(1);
var tracksListened = metadata.ElementAtOrDefault(2);
// Get top albums and tracks
IEnumerable<(string name, string url, int playcount)> GetTopLisreplacedems(HtmlNode topList)
{
foreach (var item in topList.Descendants("tr").Where(x => x.HasClreplaced("chartlist-row") || x.HasClreplaced("chartlist-row\n")))
{
var itemNameLink = item.Descendants("td").First(x => x.HasClreplaced("chartlist-name")).Descendants("a").First();
var itemUrl = "https://www.last.fm" + itemNameLink.GetAttributeValue("href", null);
var scrobbleText = item.Descendants("span").First(x => x.HasClreplaced("chartlist-count-bar-value")).InnerText;
var scrobbleCount = int.Parse(Regex.Match(scrobbleText, @"[\d,.\s]+").Value, System.Globalization.NumberStyles.Any, new System.Globalization.CultureInfo("en-US"));
yield return (WebUtility.HtmlDecode(itemNameLink.InnerText), itemUrl, scrobbleCount);
}
}
var topLists = doc.DoreplacedentNode.Descendants("table").Where(x => x.HasClreplaced("chartlist") || x.HasClreplaced("chartlist\n")).ToList();
var topAlbums = Enumerable.Empty<LastFmAlbum>();
if (topLists.Any())
topAlbums = GetTopLisreplacedems(topLists.First()).Select(x => new LastFmAlbum(x.name, info, x.playcount));
var topTracks = Enumerable.Empty<LastFmTrack>();
if (topLists.Skip(1).Any())
topTracks = GetTopLisreplacedems(topLists.Skip(1).First()).Select(x => new LastFmTrack(x.name, new LastFmAlbum(null, info), x.playcount));
var imageUri = string.IsNullOrEmpty(image) ? null : new Uri(image);
return new LastFmArtistDetail(info, imageUri, topAlbums, topTracks, albumsListened, tracksListened, playcount);
}
}
catch (WebException e) when ((e.Response as HttpWebResponse)?.StatusCode == HttpStatusCode.NotFound)
{
return null;
}
}
19
Source : ChildProcessTest_Redirection.cs
with MIT License
from asmichi
with MIT License
from asmichi
[Fact]
public async Task PipesAreAsynchronous()
{
var si = new ChildProcessStartInfo(TestUtil.DotnetCommandName, TestUtil.TestChildPath, "EchoBack")
{
StdInputRedirection = InputRedirection.InputPipe,
StdOutputRedirection = OutputRedirection.OutputPipe,
StdErrorRedirection = OutputRedirection.ErrorPipe,
};
using var sut = ChildProcess.Start(si);
replacedert.True(IsAsync(sut.StandardInput));
replacedert.True(IsAsync(sut.StandardOutput));
replacedert.True(IsAsync(sut.StandardError));
using (var sr = new StreamReader(sut.StandardOutput))
{
const string text = "foobar";
var stdoutTask = sr.ReadToEndAsync();
using (var sw = new StreamWriter(sut.StandardInput))
{
await sw.WriteAsync(text);
}
replacedert.Equal(text, await stdoutTask);
}
sut.WaitForExit();
replacedert.Equal(0, sut.ExitCode);
static bool IsAsync(Stream stream)
{
return stream switch
{
FileStream fs => fs.IsAsync,
NetworkStream _ => true, // Trust the runtime; it must be truly async!
_ => throw new InvalidOperationException("Unknown stream type."),
};
}
19
Source : LastFmClient.cs
with GNU Affero General Public License v3.0
from asmejkal
with GNU Affero General Public License v3.0
from asmejkal
public async Task<LastFmUserInfo> GetUserInfo()
{
var request = WebRequest.CreateHttp($"{ApiBase}/?method=user.getinfo&user={User}&api_key={Key}&format=json");
request.Timeout = (int)RequestTimeout.TotalMilliseconds;
using (var response = (HttpWebResponse)await request.GetResponseAsync())
using (var reader = new StreamReader(response.GetResponseStream()))
{
var text = await reader.ReadToEndAsync();
var user = JObject.Parse(text)["user"];
return new LastFmUserInfo((int?)user["playcount"] ?? 0);
}
}
19
Source : LastFmClient.cs
with GNU Affero General Public License v3.0
from asmejkal
with GNU Affero General Public License v3.0
from asmejkal
public async Task<(IReadOnlyCollection<LastFmRecentTrack> tracks, bool remaining)> GetRecentTracksPage(int page, int count, DateTimeOffset? from = null)
{
var request = WebRequest.CreateHttp($"{ApiBase}/?method=user.getrecenttracks&user={User}&api_key={Key}&format=json&limit={count}&page={page}&extended=1" + (from.HasValue ? $"&from={from.Value.ToUnixTimeSeconds()}" : string.Empty));
request.Timeout = (int)RequestTimeout.TotalMilliseconds;
using (var response = (HttpWebResponse)await request.GetResponseAsync())
using (var reader = new StreamReader(response.GetResponseStream()))
{
var text = await reader.ReadToEndAsync();
var root = JObject.Parse(text);
var tracks = root["recenttracks"]?["track"] as JArray;
if (tracks != null && tracks.Any())
{
var nowPlaying = page == 1 && string.Compare((string)tracks[0]["@attr"]?["nowplaying"], "true", true) == 0;
var result = tracks.Select((x, i) =>
{
var uts = (long?)x["date"]?["uts"];
return new LastFmRecentTrack(
(string)x["name"],
i == 0 && nowPlaying,
(string)x["artist"]?["name"],
(string)x["album"]?["#text"],
GetLargestImage(x["image"]),
uts.HasValue ? DateTimeOffset.FromUnixTimeSeconds(uts.Value) : (DateTimeOffset?)null);
});
var more = page < (int)root["recenttracks"]["@attr"]["totalPages"];
return (result.ToList(), more);
}
else
{
return (Array.Empty<LastFmRecentTrack>(), false);
}
}
}
19
Source : LastFmClient.cs
with GNU Affero General Public License v3.0
from asmejkal
with GNU Affero General Public License v3.0
from asmejkal
public async Task<LastFmArtist> GetArtistInfo(string name)
{
var request = WebRequest.CreateHttp($"{ApiBase}/?method=artist.getInfo&api_key={Key}&artist={Uri.EscapeDataString(name)}&format=json&username={User}");
request.Timeout = (int)RequestTimeout.TotalMilliseconds;
using (var response = (HttpWebResponse)await request.GetResponseAsync())
using (var reader = new StreamReader(response.GetResponseStream()))
{
var text = await reader.ReadToEndAsync();
var artist = JObject.Parse(text)?["artist"];
if (artist == null)
return null;
return new LastFmArtist((string)artist["name"], imageUri: GetLargestImage(artist["image"]));
}
}
19
Source : LastFmClient.cs
with GNU Affero General Public License v3.0
from asmejkal
with GNU Affero General Public License v3.0
from asmejkal
public async Task<LastFmTrack> GetTrackInfo(string artistName, string name)
{
var request = WebRequest.CreateHttp($"{ApiBase}/?method=track.getInfo&api_key={Key}&artist={Uri.EscapeDataString(artistName)}&track={Uri.EscapeDataString(name)}&format=json&username={User}");
request.Timeout = (int)RequestTimeout.TotalMilliseconds;
using (var response = (HttpWebResponse)await request.GetResponseAsync())
using (var reader = new StreamReader(response.GetResponseStream()))
{
var text = await reader.ReadToEndAsync();
var track = JObject.Parse(text)?["track"];
if (track == null)
return null;
var artist = new LastFmArtist((string)track["artist"]["name"]);
var album = new LastFmAlbum((string)track["album"]?["replacedle"], artist, imageUri: GetLargestImage(track["album"]?["image"]));
return new LastFmTrack((string)track["name"], album, (int?)track["userplaycount"]);
}
}
19
Source : LastFmClient.cs
with GNU Affero General Public License v3.0
from asmejkal
with GNU Affero General Public License v3.0
from asmejkal
public async Task<IEnumerable<LastFmArtist>> GetTopArtists(LastFmDataPeriod period, int count)
{
if (period == LastFmDataPeriod.Day)
{
var tracks = await GetRecentTracks(StatsPeriodTimeMapping[period]);
return tracks
.SkipWhile(x => x.NowPlaying)
.GroupBy(x => x.Artist.Id)
.Select(x => x.First().Artist.WithPlaycount(x.Count()))
.OrderByDescending(x => x.Playcount);
}
else
{
var request = WebRequest.CreateHttp($"{ApiBase}/?method=user.gettopartists&user={User}&api_key={Key}&period={StatsPeriodMapping[period]}&limit={count}&format=json");
request.Timeout = (int)RequestTimeout.TotalMilliseconds;
using (var response = (HttpWebResponse)await request.GetResponseAsync())
using (var reader = new StreamReader(response.GetResponseStream()))
{
var text = await reader.ReadToEndAsync();
var root = JObject.Parse(text);
var results = root?["topartists"]?["artist"] as JArray ?? Enumerable.Empty<JToken>();
return results.Select(x => new LastFmArtist((string)x["name"], (int)x["playcount"]));
}
}
}
19
Source : LastFmClient.cs
with GNU Affero General Public License v3.0
from asmejkal
with GNU Affero General Public License v3.0
from asmejkal
public async Task<IEnumerable<LastFmAlbum>> GetTopAlbums(LastFmDataPeriod period, int count)
{
if (period == LastFmDataPeriod.Day)
{
var tracks = await GetRecentTracks(StatsPeriodTimeMapping[period]);
return tracks
.SkipWhile(x => x.NowPlaying)
.GroupBy(x => x.Album.Id)
.Select(x => x.First().Album.WithPlaycount(x.Count()))
.OrderByDescending(x => x.Playcount);
}
else
{
var request = WebRequest.CreateHttp($"{ApiBase}/?method=user.gettopalbums&user={User}&api_key={Key}&period={StatsPeriodMapping[period]}&limit={count}&format=json");
request.Timeout = (int)RequestTimeout.TotalMilliseconds;
using (var response = (HttpWebResponse)await request.GetResponseAsync())
using (var reader = new StreamReader(response.GetResponseStream()))
{
var text = await reader.ReadToEndAsync();
var root = JObject.Parse(text);
var results = root?["topalbums"]?["album"] as JArray ?? Enumerable.Empty<JToken>();
return results.Select(x => new LastFmAlbum((string)x["name"], new LastFmArtist((string)x["artist"]["name"]), (int)x["playcount"]));
}
}
}
19
Source : LastFmClient.cs
with GNU Affero General Public License v3.0
from asmejkal
with GNU Affero General Public License v3.0
from asmejkal
public async Task<IEnumerable<LastFmTrack>> GetTopTracks(LastFmDataPeriod period, int count = int.MaxValue, CancellationToken ct = default)
{
if (period == LastFmDataPeriod.Day)
{
var tracks = await GetRecentTracks(StatsPeriodTimeMapping[period]);
return tracks
.SkipWhile(x => x.NowPlaying)
.GroupBy(x => x.Id)
.Select(x => x.First().ToTrack(x.Count()))
.OrderByDescending(x => x.Playcount);
}
else
{
var retrieved = 0;
var page = 1;
var results = Enumerable.Empty<LastFmTrack>();
var pageSize = Math.Min(count, MaxTopPageSize);
while (retrieved < count)
{
ct.ThrowIfCancellationRequested();
var request = WebRequest.CreateHttp($"{ApiBase}/?method=user.gettoptracks&user={User}&api_key={Key}&period={StatsPeriodMapping[period]}&limit={pageSize}&page={page}&format=json");
request.Timeout = (int)RequestTimeout.TotalMilliseconds;
using (var response = (HttpWebResponse)await request.GetResponseAsync())
using (var reader = new StreamReader(response.GetResponseStream()))
{
ct.ThrowIfCancellationRequested();
var text = await reader.ReadToEndAsync();
ct.ThrowIfCancellationRequested();
var root = JObject.Parse(text);
var pageResults = (root?["toptracks"]?["track"] as JArray ?? Enumerable.Empty<JToken>()).ToList();
results = results.Concat(pageResults.Select(x => new LastFmTrack((string)x["name"], new LastFmAlbum(null, new LastFmArtist((string)x["artist"]["name"]), null), (int)x["playcount"])));
retrieved += pageResults.Count;
var more = page < ((int?)root?["toptracks"]?["@attr"]?["totalPages"] ?? 1);
if (!more || !pageResults.Any())
break;
}
page++;
}
return results;
}
}
19
Source : LastFmClient.cs
with GNU Affero General Public License v3.0
from asmejkal
with GNU Affero General Public License v3.0
from asmejkal
public async Task<int> GetTotalPlaycount(DateTimeOffset? from = null)
{
var request = WebRequest.CreateHttp($"{ApiBase}/?method=user.getrecenttracks&user={User}&api_key={Key}&limit=1&format=json" + (from.HasValue ? $"&from={from.Value.ToUnixTimeSeconds()}" : string.Empty));
request.Timeout = (int)RequestTimeout.TotalMilliseconds;
using (var response = (HttpWebResponse)await request.GetResponseAsync())
using (var reader = new StreamReader(response.GetResponseStream()))
{
var text = await reader.ReadToEndAsync();
var root = JObject.Parse(text);
return (int)root["recenttracks"]["@attr"]["total"];
}
}
19
Source : ChildProcessExamplesUnix.cs
with MIT License
from asmichi
with MIT License
from asmichi
private static async Task BasicAsync()
{
var si = new ChildProcessStartInfo("sh", "-c", "echo foo")
{
StdOutputRedirection = OutputRedirection.OutputPipe,
StdErrorRedirection = OutputRedirection.OutputPipe,
};
using var p = ChildProcess.Start(si);
using (var sr = new StreamReader(p.StandardOutput))
{
// "foo"
Console.Write(await sr.ReadToEndAsync());
}
await p.WaitForExitAsync();
// ExitCode: 0
Console.WriteLine("ExitCode: {0}", p.ExitCode);
}
19
Source : ChildProcessExamplesWindows.cs
with MIT License
from asmichi
with MIT License
from asmichi
private static async Task BasicAsync()
{
var si = new ChildProcessStartInfo("cmd", "/C", "echo", "foo")
{
StdOutputRedirection = OutputRedirection.OutputPipe,
StdErrorRedirection = OutputRedirection.OutputPipe,
};
using var p = ChildProcess.Start(si);
using (var sr = new StreamReader(p.StandardOutput))
{
// "foo"
Console.Write(await sr.ReadToEndAsync());
}
await p.WaitForExitAsync();
// ExitCode: 0
Console.WriteLine("ExitCode: {0}", p.ExitCode);
}
19
Source : OwinRequest.cs
with Apache License 2.0
from aspnet
with Apache License 2.0
from aspnet
public async Task<IFormCollection> ReadFormAsync()
{
var form = Get<IFormCollection>("Microsoft.Owin.Form#collection");
if (form == null)
{
string text;
// Don't close, it prevents re-winding.
using (var reader = new StreamReader(Body, Encoding.UTF8, detectEncodingFromByteOrderMarks: true, bufferSize: 4 * 1024, leaveOpen: true))
{
text = await reader.ReadToEndAsync();
}
form = OwinHelpers.GetForm(text);
Set("Microsoft.Owin.Form#collection", form);
}
return form;
}
19
Source : Template.cs
with MIT License
from aurelia
with MIT License
from aurelia
public static async Task<string> GenerateTemplatesAsync(string templateName, string targetFolder, string elementName, bool isGlobal = false)
{
string templateText;
using (var reader = new StreamReader(templateName))
{
templateText = await reader.ReadToEndAsync();
}
var customIndex = elementName.IndexOf("Custom", StringComparison.InvariantCultureIgnoreCase);
customIndex = customIndex > 0 ? customIndex : elementName.IndexOf("BindingBehavior", StringComparison.InvariantCultureIgnoreCase);
customIndex = customIndex > 0 ? customIndex : elementName.IndexOf("ValueConverter", StringComparison.InvariantCultureIgnoreCase);
elementName = elementName.Substring(0, customIndex > 0 ? customIndex : elementName.Length);
var fileName = Path.GetFileName(templateName);
var parts = fileName.Split('.');
var extension = parts[parts.Length - 2];
var pascalCaseElementName = elementName.ToPascalCase();
var kebabCase = pascalCaseElementName.PascalToKebabCase();
var fullFileName = Path.Combine(targetFolder, kebabCase, $"{kebabCase}.{extension}");
templateText = templateText.Replace("%name%", pascalCaseElementName);
templateText = templateText.Replace("%properties%", "");
Directory.CreateDirectory(Path.GetDirectoryName(fullFileName));
File.WriteAllText(fullFileName, templateText);
if (templateName.Equals("feature"))
{
AureliaHelper.AddFeatureToConfigure(targetFolder);
}
if (isGlobal && (extension.ToLower() == "js" || extension.ToLower() == "ts"))
{
AureliaHelper.AddGlobalResource(fullFileName);
}
return fullFileName;
}
19
Source : DetailViewHost.cs
with MIT License
from Auros
with MIT License
from Auros
private async Task Parse(StandardLevelDetailViewController standardLevelDetailViewController)
{
if (!_didParse)
{
var info = await _platformUserModel.GetUserInfo();
CanVote = info.platform == UserInfo.Platform.Steam || info.platform == UserInfo.Platform.Test;
_siraLog.Debug("Doing Initial BSML Parsing of the Detail View");
_siraLog.Debug("Getting Manifest Stream");
using (Stream stream = replacedembly.GetExecutingreplacedembly().GetManifestResourceStream("DiTails.Views.detail-view.bsml"))
using (var reader = new StreamReader(stream))
{
_siraLog.Debug("Reading Manifest Stream");
_bsmlContent = await reader.ReadToEndAsync();
}
if (!string.IsNullOrWhiteSpace(_bsmlContent))
{
_siraLog.Debug("Parsing Details");
try
{
BSMLParser.instance.Parse(_bsmlContent, standardLevelDetailViewController.gameObject, this);
}
catch (Exception e)
{
_siraLog.Logger.Critical(e);
}
if (rootTransform != null && mainModalTransform != null)
{
rootTransform.gameObject.name = "DiTailsDetailView";
mainModalTransform.gameObject.name = "DiTailsMainModal";
}
if (descriptionModalTransform != null && artworkModalTransform != null)
{
descriptionModalTransform.gameObject.name = "DiTailsDescriptionModal";
artworkModalTransform.gameObject.name = "DiTailsArtworkModal";
}
if (panel1Transform != null && mainOkButton != null)
{
var buttons = panel1Transform.GetComponentsInChildren<UnityEngine.UI.Button>(true).ToList();
buttons.Add(mainOkButton);
foreach (var button in buttons)
{
foreach (var image in button.GetComponentsInChildren<ImageView>(true))
{
var view = image;
IMAGESKEW(ref view) = 0f;
image.SetVerticesDirty();
}
foreach (var text in button.GetComponentsInChildren<TMP_Text>(true))
{
text.alignment = TextAlignmentOptions.Center;
if (text.fontStyle.HasFlag(FontStyles.Italic))
{
text.fontStyle -= FontStyles.Italic;
}
}
}
}
_siraLog.Debug("Parsing Complete");
_didParse = true;
}
}
}
19
Source : CustomLocaleLoader.cs
with MIT License
from Auros
with MIT License
from Auros
public async Task LoadLocales()
{
var folder = Path.Combine(UnityGame.UserDataPath, "SIRA", "Localizations");
if (!Directory.Exists(folder))
{
Directory.CreateDirectory(folder);
}
var files = new DirectoryInfo(folder).EnumerateFiles().Where(x => x.Extension == ".csv" || x.Extension == ".tsv");
for (int i = 0; i < files.Count(); i++)
{
var file = files.ElementAt(i);
using (var reader = File.OpenText(file.FullName))
{
var fileText = await reader.ReadToEndAsync();
_localizer.AddLocalizationSheet(fileText, file.Extension.EndsWith("csv") ? GoogleDriveDownloadFormat.CSV : GoogleDriveDownloadFormat.TSV, file.FullName);
}
}
}
19
Source : BaseController.cs
with Apache License 2.0
from authlete
with Apache License 2.0
from authlete
public async Task<string> ReadRequestBodyreplacedtring()
{
using (var reader = new StreamReader(Request.Body, Encoding.UTF8))
{
return await reader.ReadToEndAsync();
}
}
19
Source : StreamExtensions.cs
with MIT License
from Avanade
with MIT License
from Avanade
private static async Task<string> replacedtringAsyncImpl(this Stream stream, Encoding encoding)
{
using (var reader = new StreamReader(stream, encoding))
{
return await reader.ReadToEndAsync();
}
}
19
Source : Extention.Stream.cs
with MIT License
from awesomedotnetcore
with MIT License
from awesomedotnetcore
public static async Task<string> ReadToStringAsync(this Stream stream, Encoding encoding = null)
{
if (encoding == null)
encoding = Encoding.UTF8;
if (stream.CanSeek)
{
stream.Seek(0, SeekOrigin.Begin);
}
string resStr = string.Empty;
resStr = await new StreamReader(stream, encoding).ReadToEndAsync();
if (stream.CanSeek)
{
stream.Seek(0, SeekOrigin.Begin);
}
return resStr;
}
19
Source : LayerTests.cs
with Apache License 2.0
from aws
with Apache License 2.0
from aws
[Fact]
public async Task CreateLayer()
{
var logger = new TestToolLogger(_testOutputHelper);
var command = new PublishLayerCommand(logger, _singleLayerFunctionPath, new string[0]);
command.Region = "us-east-1";
command.TargetFramework = "netcoreapp2.1";
command.S3Bucket = this._testFixture.Bucket;
command.DisableInteractive = true;
command.LayerName = "DotnetTest-CreateLayer";
command.LayerType = LambdaConstants.LAYER_TYPE_RUNTIME_PACKAGE_STORE;
command.PackageManifest = _singleLayerFunctionPath;
try
{
replacedert.True(await command.ExecuteAsync());
replacedert.NotNull(command.NewLayerVersionArn);
var getResponse = await this._testFixture.LambdaClient.GetLayerVersionAsync(new GetLayerVersionRequest {LayerName = command.NewLayerArn, VersionNumber = command.NewLayerVersionNumber });
replacedert.NotNull(getResponse.Description);
var data = JsonMapper.ToObject<LayerDescriptionManifest>(getResponse.Description);
replacedert.Equal(LayerDescriptionManifest.ManifestType.RuntimePackageStore, data.Nlt);
replacedert.NotNull(data.Dir);
replacedert.Equal(this._testFixture.Bucket, data.Buc);
replacedert.NotNull(data.Key);
using (var getManifestResponse = await this._testFixture.S3Client.GetObjectAsync(data.Buc, data.Key))
using(var reader = new StreamReader(getManifestResponse.ResponseStream))
{
var xml = await reader.ReadToEndAsync();
replacedert.Contains("AWSSDK.S3", xml);
replacedert.Contains("Amazon.Lambda.Core", xml);
}
}
finally
{
await this._testFixture.LambdaClient.DeleteLayerVersionAsync(new DeleteLayerVersionRequest { LayerName = command.NewLayerArn, VersionNumber = command.NewLayerVersionNumber });
}
}
19
Source : LayerTests.cs
with Apache License 2.0
from aws
with Apache License 2.0
from aws
[Fact]
// This test behaves different depending on the OS the test is running on which means
// all code paths are not always being tested. Future work is needed to figure out how to
// mock the underlying calls to the dotnet CLI.
public async Task AttemptToCreateAnOptmizedLayer()
{
var logger = new TestToolLogger(_testOutputHelper);
var replacedembly = this.GetType().GetTypeInfo().replacedembly;
var fullPath = Path.GetFullPath(Path.GetDirectoryName(replacedembly.Location) + "../../../../../../testapps/TestLayerExample");
var command = new PublishLayerCommand(logger, fullPath, new string[] { "--enable-package-optimization", "true"});
command.Region = "us-east-1";
command.TargetFramework = "netcoreapp2.1";
command.S3Bucket = this._testFixture.Bucket;
command.DisableInteractive = true;
command.LayerName = "DotnetTest-AttemptToCreateAnOptmizedLayer";
command.LayerType = LambdaConstants.LAYER_TYPE_RUNTIME_PACKAGE_STORE;
command.PackageManifest = fullPath;
bool success = false;
try
{
success = await command.ExecuteAsync();
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
replacedert.False(success);
replacedert.Equal(LambdaToolsException.LambdaErrorCode.UnsupportedOptimizationPlatform.ToString(), command.LastToolsException.Code);
}
else
{
replacedert.True(success);
replacedert.NotNull(command.NewLayerVersionArn);
var getResponse = await this._testFixture.LambdaClient.GetLayerVersionAsync(new GetLayerVersionRequest { LayerName = command.NewLayerArn, VersionNumber = command.NewLayerVersionNumber });
replacedert.NotNull(getResponse.Description);
var data = JsonMapper.ToObject<LayerDescriptionManifest>(getResponse.Description);
replacedert.Equal(LayerDescriptionManifest.ManifestType.RuntimePackageStore, data.Nlt);
replacedert.NotNull(data.Dir);
replacedert.Equal(this._testFixture.Bucket, data.Buc);
replacedert.NotNull(data.Key);
using (var getManifestResponse = await this._testFixture.S3Client.GetObjectAsync(data.Buc, data.Key))
using (var reader = new StreamReader(getManifestResponse.ResponseStream))
{
var xml = await reader.ReadToEndAsync();
replacedert.Contains("AWSSDK.S3", xml);
replacedert.Contains("Amazon.Lambda.Core", xml);
}
}
}
finally
{
if(success)
{
await this._testFixture.LambdaClient.DeleteLayerVersionAsync(new DeleteLayerVersionRequest { LayerName = command.NewLayerArn, VersionNumber = command.NewLayerVersionNumber });
}
}
}
19
Source : LayerTests.cs
with Apache License 2.0
from aws
with Apache License 2.0
from aws
[Fact(Skip = "Trouble running in CodeBuild. Need to debug.")]
public async Task DeployAspNetCoreWithlayer()
{
var logger = new TestToolLogger(_testOutputHelper);
var templateTilePath = Path.Combine(_aspnercoreLayerFunctionPath, "serverless.template");
if (File.Exists(templateTilePath))
{
File.Delete(templateTilePath);
}
var publishLayerCommand = await PublishLayerAsync(_aspnercoreLayerFunctionPath, "");
try
{
var getLayerResponse = await this._testFixture.LambdaClient.GetLayerVersionAsync(new GetLayerVersionRequest {LayerName = publishLayerCommand.NewLayerArn, VersionNumber = publishLayerCommand.NewLayerVersionNumber });
replacedert.NotNull(getLayerResponse.Description);
// Make sure layer does not contain any core ASP.NET Core dependencies.
var layerManifest = JsonMapper.ToObject<LayerDescriptionManifest>(getLayerResponse.Description);
using (var getManifestResponse = await this._testFixture.S3Client.GetObjectAsync(layerManifest.Buc, layerManifest.Key))
using(var reader = new StreamReader(getManifestResponse.ResponseStream))
{
var xml = await reader.ReadToEndAsync();
replacedert.False(xml.Contains("Microsoft.AspNetCore"));
replacedert.False(xml.Contains("runtime"));
}
var templateContent = File.ReadAllText(Path.Combine(_aspnercoreLayerFunctionPath, "fake.template"));
templateContent =
templateContent.Replace("LAYER_ARN_PLACEHOLDER", publishLayerCommand.NewLayerVersionArn);
File.WriteAllText(templateTilePath, templateContent);
var command = new DeployServerlessCommand(new TestToolLogger(_testOutputHelper), _aspnercoreLayerFunctionPath, new string[] { });
command.DisableInteractive = true;
command.StackName = "DeployAspNetCoreWithlayer-" + DateTime.Now.Ticks;
command.Region = publishLayerCommand.Region;
command.S3Bucket = this._testFixture.Bucket;
command.WaitForStackToComplete = true;
command.DisableInteractive = true;
command.ProjectLocation = _aspnercoreLayerFunctionPath;
var created = await command.ExecuteAsync();
try
{
replacedert.True(created);
var lambdaFunctionName =
await TestHelper.GetPhysicalCloudFormationResourceId(_testFixture.CFClient, command.StackName, "AspNetCoreFunction");
var apiUrl = await TestHelper.GetOutputParameter(_testFixture.CFClient, command.StackName, "ApiURL");
using (var client = new HttpClient())
{
await client.GetStringAsync(new Uri(new Uri(apiUrl), "api/values"));
}
var getConfigResponse = await this._testFixture.LambdaClient.GetFunctionConfigurationAsync(new GetFunctionConfigurationRequest { FunctionName = lambdaFunctionName });
replacedert.NotNull(getConfigResponse.Layers.FirstOrDefault(x => string.Equals(x.Arn, publishLayerCommand.NewLayerVersionArn)));
var getCodeResponse = await this._testFixture.LambdaClient.GetFunctionAsync(lambdaFunctionName);
using (var client = new HttpClient())
{
var data = await client.GetByteArrayAsync(getCodeResponse.Code.Location);
var zipArchive = new ZipArchive(new MemoryStream(data), ZipArchiveMode.Read);
replacedert.NotNull(zipArchive.GetEntry("TestLayerAspNetCore.dll"));
replacedert.Null(zipArchive.GetEntry("Amazon.Lambda.Core.dll"));
replacedert.Null(zipArchive.GetEntry("AWSSDK.S3.dll"));
replacedert.Null(zipArchive.GetEntry("AWSSDK.Extensions.NETCore.Setup.dll"));
replacedert.Null(zipArchive.GetEntry("Amazon.Lambda.AspNetCoreServer.dll"));
}
}
finally
{
if (created)
{
var deleteCommand = new DeleteServerlessCommand(new TestToolLogger(_testOutputHelper), _aspnercoreLayerFunctionPath, new string[0]);
deleteCommand.DisableInteractive = true;
deleteCommand.Region = publishLayerCommand.Region;
deleteCommand.StackName = command.StackName;
await deleteCommand.ExecuteAsync();
}
}
}
finally
{
await this._testFixture.LambdaClient.DeleteLayerVersionAsync(new DeleteLayerVersionRequest { LayerName = publishLayerCommand.NewLayerArn, VersionNumber = publishLayerCommand.NewLayerVersionNumber });
if (File.Exists(templateTilePath))
{
File.Delete(templateTilePath);
}
}
}
19
Source : FileDownloader.cs
with Apache License 2.0
from awslabs
with Apache License 2.0
from awslabs
public async Task<string> ReadFilereplacedtringAsync(string url)
{
string path = ConvertFileUrlToPath(url);
using (var reader = File.OpenText(path))
{
return await reader.ReadToEndAsync();
}
}
19
Source : Retrain.cs
with Apache License 2.0
from aws-samples
with Apache License 2.0
from aws-samples
public override async Task<Context> Execute(Context context)
{
context.TrainingFileJson = "SageMaker/train.json";
var getResult = await s3.GetObjectAsync(new GetObjectRequest
{
BucketName = context.ResultsBucketName,
Key = $"{context.TrainingFileCsv}"
});
using (var reader = new StreamReader(getResult.ResponseStream))
{
var csv = reader.ReadToEndAsync().Result;
var jsonLines = ConvertToJsonLines(csv);
using (var stream = StringToStream(jsonLines))
{
await s3.PutObjectAsync(new PutObjectRequest
{
BucketName = context.TrainingBucketName,
Key = context.TrainingFileJson,
InputStream = stream,
ContentType = "application/json"
});
}
}
return context;
}
19
Source : S3Downloader.cs
with Apache License 2.0
from awslabs
with Apache License 2.0
from awslabs
public async Task<string> ReadFilereplacedtringAsync(string url)
{
GetObjectResponse response = await GetS3Object(url);
using (StreamReader reader = new StreamReader(response.ResponseStream))
{
return await reader.ReadToEndAsync();
}
}
19
Source : FileSystemFile.cs
with MIT License
from azist
with MIT License
from azist
public Task<string> ReadAllTextAsync(Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize = 1024)
{
using(var fs = this.FileStream)
using(var r = new StreamReader(fs, encoding, detectEncodingFromByteOrderMarks, bufferSize))
return r.ReadToEndAsync();
}
19
Source : FileSystemFile.cs
with MIT License
from azist
with MIT License
from azist
public Task<string> ReadAllTextAsync()
{
using(var fs = this.FileStream)
using(var r = new StreamReader(fs))
return r.ReadToEndAsync();
}
19
Source : WebSocketMiddleware.cs
with Apache License 2.0
from azizamari
with Apache License 2.0
from azizamari
private static async Task<string> ReceiveStringAsync(WebSocket socket, CancellationToken ct = default)
{
// Message can be sent by chunk.
// We must read all chunks before decoding the content
var buffer = new ArraySegment<byte>(new byte[8192]);
using (var ms = new MemoryStream())
{
WebSocketReceiveResult result;
do
{
ct.ThrowIfCancellationRequested();
result = await socket.ReceiveAsync(buffer, ct);
ms.Write(buffer.Array, buffer.Offset, result.Count);
}
while (!result.EndOfMessage);
ms.Seek(0, SeekOrigin.Begin);
if (result.MessageType != WebSocketMessageType.Text)
throw new Exception("Unexpected message");
// Encoding UTF8: https://tools.ietf.org/html/rfc6455#section-5.6
using (var reader = new StreamReader(ms, Encoding.UTF8))
{
return await reader.ReadToEndAsync();
}
}
}
19
Source : FileSystemHelpers.cs
with Apache License 2.0
from Azure-App-Service
with Apache License 2.0
from Azure-App-Service
public static async Task<string> ReadAllTextFromFileAsync(string path)
{
using (var fileStream = OpenFile(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete))
using (var streamReader = new StreamReader(fileStream))
{
return await streamReader.ReadToEndAsync();
}
}
19
Source : FileStreamingHelper.cs
with Apache License 2.0
from Azure-App-Service
with Apache License 2.0
from Azure-App-Service
public static async Task<FormValueProvider> StreamFile(this HttpRequest request, Stream targetStream)
{
Console.WriteLine("Streaming Upload Data");
if (!MultipartRequestHelper.IsMultipartContentType(request.ContentType))
{
throw new Exception($"Expected a multipart request, but got {request.ContentType}");
}
// Used to acreplacedulate all the form url encoded key value pairs in the
// request.
var formAcreplacedulator = new KeyValueAcreplacedulator();
var boundary = MultipartRequestHelper.GetBoundary(
MediaTypeHeaderValue.Parse(request.ContentType),
_defaultFormOptions.MultipartBoundaryLengthLimit);
var reader = new MultipartReader(boundary, request.Body);
var section = await reader.ReadNextSectionAsync();
while (section != null)
{
ContentDispositionHeaderValue contentDisposition;
var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out contentDisposition);
if (hasContentDispositionHeader)
{
if (MultipartRequestHelper.HasFileContentDisposition(contentDisposition))
{
await section.Body.CopyToAsync(targetStream);
}
else if (MultipartRequestHelper.HasFormDataContentDisposition(contentDisposition))
{
// Content-Disposition: form-data; name="key"
//
// value
// Do not limit the key name length here because the
// multipart headers length limit is already in effect.
var key = HeaderUtilities.RemoveQuotes(contentDisposition.Name);
var encoding = GetEncoding(section);
using (var streamReader = new StreamReader(
section.Body,
encoding,
detectEncodingFromByteOrderMarks: true,
bufferSize: 1024,
leaveOpen: true))
{
// The value length limit is enforced by MultipartBodyLengthLimit
var value = await streamReader.ReadToEndAsync();
if (String.Equals(value, "undefined", StringComparison.OrdinalIgnoreCase))
{
value = String.Empty;
}
formAcreplacedulator.Append(key.Value, value); // For .NET Core <2.0 remove ".Value" from key
if (formAcreplacedulator.ValueCount > _defaultFormOptions.ValueCountLimit)
{
throw new InvalidDataException($"Form key count limit {_defaultFormOptions.ValueCountLimit} exceeded.");
}
}
}
}
// Drains any remaining section body that has not been consumed and
// reads the headers for the next section.
section = await reader.ReadNextSectionAsync();
}
// Bind form data to a model
var formValueProvider = new FormValueProvider(
BindingSource.Form,
new FormCollection(formAcreplacedulator.GetResults()),
CultureInfo.CurrentCulture);
return formValueProvider;
}
19
Source : PushDeploymentController.cs
with Apache License 2.0
from Azure-App-Service
with Apache License 2.0
from Azure-App-Service
[HttpPost]
[HttpPut]
[DisableRequestSizeLimit]
[DisableFormValueModelBinding]
public async Task<IActionResult> OneDeploy(
[FromQuery] string type = null,
[FromQuery] bool async = false,
[FromQuery] string path = null,
[FromQuery] bool? restart = true,
[FromQuery] bool? clean = null,
[FromQuery] bool ignoreStack = false,
[FromQuery] bool trackDeploymentProgress = false
)
{
string remoteArtifactUrl = null;
using (_tracer.Step(Constants.OneDeploy))
{
try
{
if (Request.MediaTypeContains("application/json"))
{
string jsonString;
using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
{
jsonString = await reader.ReadToEndAsync();
}
var requestJson = JObject.Parse(jsonString);
if (ArmUtils.IsArmRequest(Request))
{
requestJson = requestJson.Value<JObject>("properties");
type = requestJson.Value<string>("type");
async = requestJson.Value<bool>("async");
path = requestJson.Value<string>("path");
restart = requestJson.Value<bool?>("restart");
clean = requestJson.Value<bool?>("clean");
ignoreStack = requestJson.Value<bool>("ignorestack");
}
remoteArtifactUrl = ArmUtils.IsArmRequest(Request) ? GetArticfactURLFromARMJSON(requestJson) : GetArtifactURLFromJSON(requestJson);
}
}
catch (Exception ex)
{
return StatusCode400(ex.ToString());
}
//
// 'async' is not a CSharp-ish variable name. And although it is a valid variable name, some
// IDEs confuse it to be the 'async' keyword in C#.
// On the other hand, isAsync is not a good name for the query-parameter.
// So we use 'async' as the query parameter, and then replacedign it to the C# variable 'isAsync'
// at the earliest. Hereon, we use just 'isAsync'.
//
bool isAsync = async;
ArtifactType artifactType = ArtifactType.Unknown;
try
{
artifactType = (ArtifactType)Enum.Parse(typeof(ArtifactType), type, ignoreCase: true);
}
catch
{
return StatusCode400($"type='{type}' not recognized");
}
var deploymentInfo = new ArtifactDeploymentInfo(_environment, _traceFactory)
{
ArtifactType = artifactType,
AllowDeploymentWhileScmDisabled = true,
Deployer = Constants.OneDeploy,
IsContinuous = false,
AllowDeferredDeployment = false,
IsReusable = false,
TargetRootPath = _environment.WebRootPath,
TargetChangeset = DeploymentManager.CreateTemporaryChangeSet(message: Constants.OneDeploy),
CommitId = null,
DeploymentTrackingId = trackDeploymentProgress ? Guid.NewGuid().ToString() : null,
RepositoryType = RepositoryType.None,
RemoteURL = remoteArtifactUrl,
Fetch = OneDeployFetch,
DoFullBuildByDefault = false,
Message = Constants.OneDeploy,
WatchedFileEnabled = false,
CleanupTargetDirectory = clean.GetValueOrDefault(false),
RestartAllowed = restart.GetValueOrDefault(true),
};
string error;
switch (artifactType)
{
case ArtifactType.War:
if (!OneDeployHelper.EnsureValidStack(artifactType, new List<string> { OneDeployHelper.Tomcat, OneDeployHelper.JBossEap }, ignoreStack, out error))
{
return StatusCode400(error);
}
// If path is non-null, we replacedume this is a legacy war deployment, i.e. equivalent of wardeploy
if (!string.IsNullOrWhiteSpace(path))
{
//
// For legacy war deployments, the only path allowed is webapps/<directory-name>
//
if (!OneDeployHelper.EnsureValidPath(artifactType, OneDeployHelper.WwwrootDirectoryRelativePath, ref path, out error))
{
return StatusCode400(error);
}
if (!OneDeployHelper.IsLegacyWarPathValid(path))
{
return StatusCode400($"path='{path}' is invalid. When type={artifactType}, the only allowed paths are webapps/<directory-name> or /home/site/wwwroot/webapps/<directory-name>. " +
$"Example: path=webapps/ROOT or path=/home/site/wwwroot/webapps/ROOT");
}
deploymentInfo.TargetRootPath = Path.Combine(_environment.WebRootPath, path);
deploymentInfo.Fetch = LocalZipHandler;
// Legacy war deployment is equivalent to wardeploy
// So always do clean deploy.
deploymentInfo.CleanupTargetDirectory = true;
artifactType = ArtifactType.Zip;
}
else
{
// For type=war, if no path is specified, the target file is app.war
deploymentInfo.TargetFileName = "app.war";
}
break;
case ArtifactType.Jar:
if (!OneDeployHelper.EnsureValidStack(artifactType, new List<string> { OneDeployHelper.JavaSE }, ignoreStack, out error))
{
return StatusCode400(error);
}
deploymentInfo.TargetFileName = "app.jar";
break;
case ArtifactType.Ear:
if (!OneDeployHelper.EnsureValidStack(artifactType, new List<string> { OneDeployHelper.JBossEap }, ignoreStack, out error))
{
return StatusCode400(error);
}
deploymentInfo.TargetFileName = "app.ear";
break;
case ArtifactType.Lib:
if (!OneDeployHelper.EnsureValidPath(artifactType, OneDeployHelper.LibsDirectoryRelativePath, ref path, out error))
{
return StatusCode400(error);
}
deploymentInfo.TargetRootPath = OneDeployHelper.GetAbsolutePath(_environment, OneDeployHelper.LibsDirectoryRelativePath);
OneDeployHelper.SetTargetSubDirectoyAndFileNameFromRelativePath(deploymentInfo, path);
break;
case ArtifactType.Startup:
deploymentInfo.TargetRootPath = OneDeployHelper.GetAbsolutePath(_environment, OneDeployHelper.ScriptsDirectoryRelativePath);
OneDeployHelper.SetTargetSubDirectoyAndFileNameFromRelativePath(deploymentInfo, OneDeployHelper.GetStartupFileName());
break;
case ArtifactType.Script:
if (!OneDeployHelper.EnsureValidPath(artifactType, OneDeployHelper.ScriptsDirectoryRelativePath, ref path, out error))
{
return StatusCode400(error);
}
deploymentInfo.TargetRootPath = OneDeployHelper.GetAbsolutePath(_environment, OneDeployHelper.ScriptsDirectoryRelativePath);
OneDeployHelper.SetTargetSubDirectoyAndFileNameFromRelativePath(deploymentInfo, path);
break;
case ArtifactType.Static:
if (!OneDeployHelper.EnsureValidPath(artifactType, OneDeployHelper.WwwrootDirectoryRelativePath, ref path, out error))
{
return StatusCode400(error);
}
OneDeployHelper.SetTargetSubDirectoyAndFileNameFromRelativePath(deploymentInfo, path);
break;
case ArtifactType.Zip:
deploymentInfo.Fetch = LocalZipHandler;
deploymentInfo.TargetSubDirectoryRelativePath = path;
// Deployments for type=zip default to clean=true
deploymentInfo.CleanupTargetDirectory = clean.GetValueOrDefault(true);
break;
default:
return StatusCode400($"Artifact type '{artifactType}' not supported");
}
return await PushDeployAsync(deploymentInfo, isAsync, HttpContext);
}
}
19
Source : SchematizedMediaTypeFormatter.cs
with MIT License
from AzureAD
with MIT License
from AzureAD
private static async Task<string> ReadFromStream(Stream readStream)
{
if (null == readStream)
{
throw new ArgumentNullException(nameof(readStream));
}
StreamReader reader = null;
try
{
reader = new StreamReader(readStream, SchematizedMediaTypeFormatter.Encoding);
string result = await reader.ReadToEndAsync().ConfigureAwait(false);
return result;
}
finally
{
if (reader != null)
{
reader.Close();
reader = null;
}
}
}
19
Source : Function1.cs
with MIT License
from Beffyman
with MIT License
from Beffyman
[ExpectedQueryParameter(nameof(HttpMethods.Post), "command", typeof(User))]
[FunctionName("Function1")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
string name = req.Query["name"];
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
dynamic data = JsonConvert.DeserializeObject(requestBody);
name = name ?? data?.name;
return name != null
? (ActionResult)new OkObjectResult($"Hello, {name}")
: new BadRequestObjectResult("Please preplaced a name on the query string or in the request body");
}
19
Source : Function1.cs
with MIT License
from Beffyman
with MIT License
from Beffyman
[ExpectedBodyParameter(nameof(HttpMethods.Post), typeof(User))]
[ExpectedQueryParameter("Get", "name", typeof(string))]
[ProducesResponseType(typeof(string), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(string), StatusCodes.Status400BadRequest)]
[HeaderParameter("ID", typeof(Guid))]
[FunctionName("Function1")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", nameof(HttpMethods.Post), Route = "helloMe")] HttpRequest req,
ILogger log,
CancellationToken token = default)
{
log.LogInformation("C# HTTP trigger function processed a request.");
if (!req.Headers.ContainsKey("ID"))
{
return new BadRequestObjectResult("Header ID was not found");
}
Guid header = Guid.Parse(req.Headers["ID"]);
string name = null;
if (req.Query.ContainsKey("name"))
{
string queryName = req.Query["name"];
name = queryName;
}
else
{
if (!HttpMethods.IsPost(req.Method))
{
return new BadRequestObjectResult("POST requires a body with Name field");
}
if (req.ContentType.Contains("application/json", StringComparison.CurrentCultureIgnoreCase))
{
using (var reader = new StreamReader(req.Body))
{
name = JsonConvert.DeserializeObject<User>(await reader.ReadToEndAsync())?.Name;
}
}
else if (req.ContentType.Contains("application/x-msgpack", StringComparison.CurrentCultureIgnoreCase))
{
name = (await MessagePack.MessagePackSerializer.DeserializeAsync<User>(req.Body, ContractlessStandardResolver.Instance)).Name;
}
else if (req.ContentType.Contains("application/x-protobuf", StringComparison.CurrentCultureIgnoreCase))
{
name = Serializer.Deserialize<User>(req.Body)?.Name;
}
else
{
return new BadRequestObjectResult("Content-Type of body not supported. Supported Content-Types are the following: [application/json],[application/x-msgpack],[application/x-protobuf]");
}
}
if (name != null)
{
return new OkObjectResult($"Hello, {name}");
}
else
{
return new BadRequestObjectResult("Please preplaced a name on the query string or in the request body");
}
}
19
Source : USMT.cs
with GNU General Public License v3.0
from belowaverage-org
with GNU General Public License v3.0
from belowaverage-org
private static async void StarreplacedchLog(string LogFile)
{
try
{
string logFilePath = Path.Combine(PayloadPathTarget, LogFile);
FileSystemWatcher logFileWatcher = new FileSystemWatcher(PayloadPathTarget, LogFile)
{
NotifyFilter = NotifyFilters.LastWrite,
EnableRaisingEvents = true
};
FileStream logStream = File.Open(logFilePath, FileMode.OpenOrCreate, FileAccess.Read, FileShare.ReadWrite);
StreamReader logReader = new StreamReader(logStream);
long lastPosition = 0;
bool firstRead = true;
while (Running)
{
logStream.Position = lastPosition;
string log = await logReader.ReadToEndAsync();
lastPosition = logStream.Length;
if (log != "" && !firstRead)
{
string startsWith = "PercentageCompleted, ";
if (log.Contains(startsWith))
{
int start = log.LastIndexOf(startsWith) + startsWith.Length;
int end = log.LastIndexOf("\r\n");
if (int.TryParse(log.Substring(start, end - start), out int percent))
{
Logger.UpdateProgress(percent);
Logger.Verbose(log, true);
}
}
else
{
Logger.Verbose(log, true);
}
}
firstRead = false;
logFileWatcher.WaitForChanged(WatcherChangeTypes.Changed, 3000);
}
logStream.Close();
logFileWatcher.Dispose();
}
catch(Exception e)
{
Logger.Exception(e, "Failed to hook to the log file: " + LogFile + ".");
}
}
19
Source : CustomEnricherMiddleware.cs
with MIT License
from BerkEmreCabuk
with MIT License
from BerkEmreCabuk
public async Task Invoke(HttpContext context)
{
int currentSeq = 0;
if (context.Request.Headers[HeaderKeyConstants.RequestSequence].Any())
{
currentSeq = Convert.ToInt32(context.Request.Headers[HeaderKeyConstants.RequestSequence].FirstOrDefault()) + 1;
context.Request.Headers[HeaderKeyConstants.RequestSequence] = currentSeq.ToString();
}
context.Request.EnableBuffering();
var payload = "";
var req = context.Request;
using (StreamReader reader = new StreamReader(req.Body, Encoding.UTF8, true, 1024, true))
{
payload = await reader.ReadToEndAsync();
}
req.Body.Position = 0;
using (LogContext.PushProperty(LogKeyConstants.Payload, payload))
using (LogContext.PushProperty(LogKeyConstants.QueryString, context.Request.QueryString.Value))
using (LogContext.PushProperty(LogKeyConstants.HttpMethod, context.Request.Method.ToString()))
using (LogContext.PushProperty(LogKeyConstants.Url, context.Request.GetDisplayUrl()))
using (LogContext.PushProperty(LogKeyConstants.Version, context.Request.Headers[HeaderKeyConstants.Version].FirstOrDefault()))
using (LogContext.PushProperty(LogKeyConstants.CorrelationId, context.Request.Headers[HeaderKeyConstants.CorrelationId].FirstOrDefault()))
using (LogContext.PushProperty(LogKeyConstants.RemoteIpAddress, context.Connection.RemoteIpAddress.ToString()))
using (LogContext.PushProperty(LogKeyConstants.RequestSequence, currentSeq.ToString()))
{
await _next.Invoke(context);
}
}
19
Source : RequestLogMiddleware.cs
with MIT License
from bing-framework
with MIT License
from bing-framework
private async Task<string> FormatRequestAsync(HttpRequest request)
{
request.EnableBuffering();
request.Body.Seek(0, SeekOrigin.Begin);
var text = await new StreamReader(request.Body).ReadToEndAsync();
request.Body.Seek(0, SeekOrigin.Begin);
return text?.Trim().Replace("\r", "").Replace("\n", "");
}
19
Source : RequestLogMiddleware.cs
with MIT License
from bing-framework
with MIT License
from bing-framework
private async Task<string> FormatResponseAsync(HttpResponse response)
{
if (response.Hreplacedtarted)
return string.Empty;
response.Body.Seek(0, SeekOrigin.Begin);
var text = await new StreamReader(response.Body).ReadToEndAsync();
response.Body.Seek(0, SeekOrigin.Begin);
return text?.Trim().Replace("\r", "").Replace("\n", "");
}
See More Examples