投稿時間:2022-04-05 05:27:31 RSSフィード2022-04-05 05:00 分まとめ(31件)

カテゴリー等 サイト名等 記事タイトル・トレンドワード等 リンクURL 頻出ワード・要約等/検索ボリューム 登録日
AWS AWS Partner Network (APN) Blog Contentful Delivers Secure and Low-Latency Media Files Worldwide Using Amazon CloudFront and Lambda@Edge https://aws.amazon.com/blogs/apn/contentful-delivers-secure-and-low-latency-media-files-worldwide-using-amazon-cloudfront-and-lambda-at-edge/ Contentful Delivers Secure and Low Latency Media Files Worldwide Using Amazon CloudFront and Lambda EdgeIn the digital first era being a content platform means serving thousands of requests per second to users all over the world Learn how Contentful delivers media files using Amazon CloudFront with Lambda Edge achieving low latency on every region worldwide while also running custom code at the edge that enables security features and high availability With Lambda Edge Contentful can easily ship code that runs close to the user to deliver secure assets 2022-04-04 19:05:37
AWS AWS Machine Learning Blog Build an MLOps sentiment analysis pipeline using Amazon SageMaker Ground Truth and Databricks MLflow https://aws.amazon.com/blogs/machine-learning/build-an-mlops-sentiment-analysis-pipeline-using-amazon-sagemaker-ground-truth-and-databricks-mlflow/ Build an MLOps sentiment analysis pipeline using Amazon SageMaker Ground Truth and Databricks MLflowAs more organizations move to machine learning ML to drive deeper insights two key stumbling blocks they run into are labeling and lifecycle management Labeling is the identification of data and adding labels to provide context so an ML model can learn from it Labels might indicate a phrase in an audio file a car … 2022-04-04 19:43:42
海外TECH MakeUseOf The Best Free Family Tree Templates for Microsoft Word and Excel https://www.makeuseof.com/tag/free-family-tree-templates-microsoft-word-excel/ excel 2022-04-04 19:45:20
海外TECH MakeUseOf How to Interview Someone for a Blog Post https://www.makeuseof.com/interview-someone-for-blog-post/ expert 2022-04-04 19:30:21
海外TECH MakeUseOf You Can Now Share YouTube Videos on Snapchat Using Stickers https://www.makeuseof.com/share-youtube-videos-snapchat-stickers/ snapchat 2022-04-04 19:10:03
海外TECH DEV Community Deadliner https://dev.to/yassineldeeb/deadliner-3g8f DeadlinerAnnouncing DeadlinerManage your deadline gently by updating the wallpaper of your desktop with the time left ️Set deadline️Update wallpaper dynamicallyLess annoying way for reminding youFull Customization‍‍Cross PlatformEfficientLearn more YouTube VideoLanding pageSource Code 2022-04-04 19:40:07
海外TECH DEV Community Bhailang: The viral Gen-Z programming language https://dev.to/aniket762/bhailang-the-viral-gen-z-programming-language-39dn Bhailang The viral Gen Z programming languageThere are about different programming languages but you sure haven t seen any like the “Bhailang Bhai i e brother in Hindi is a very common affectionate way of addressing your friends especially in India Two Indian software developers recently created a toy programming language that broke the internet The Bhailang makes coding fun for beginners and guarantees laughs The syntax is made in a way that it feels like you aren t coding but just casually talking to your friend What is Bhai LangBhailang is a dynamically typed programming language based on an inside joke written in Typescript The programming language s code starts with “hello bhai and finishes with “bye bhai This scripting language is making the technical side of life a lot more fun and is enough to bring a smile to any coder s face The origin story Aniket Singh a software developer currently working in Amazon and Rishabh Tripathi currently working as a software developer in Groww are the creators of Bhailang Their bromance started from their college days at MNIT Bhopal interning at Appointy and then JP Morgan enhanced this duo Starting from building projects like Proximo to building a viral programming language Bhailang this couple showed the power of friendship or what we say bhaichara in Hindi In a social media post Aniket wrote We always had a curiosity about what it takes to create a programming language but we always thought that it would be a tedious and complicated work But guess what We were wrong It s actually quite fun The actual Idea for Bhailang originated from an internal joke a couple of years back when we had just started programming since then this idea was lurking around in the back of our heads Finally a couple of weeks back we started the development work and here we are with bhailang Bhailang is simple and made for fun toy language which is written in typescript Learn the Bhai language Let s jump straight into the syntax of this programming language to get the essence of Bhailang The installation is pretty straight forward but if you just want to begin you can also try out their playground As we do with all programming languages first let s learn how to run a Hello World program but since it is the Bhailang let s print Hello Bhai instead Install the npm packagenpm i g bhailangCreate a file helloBhai bhai and add the following code Please ignore this bhaihi bhai bol bhai Hello Bhai bye bhaiLet s understand the above code The entire code is enveloped between hi bhai and bye bhai Anything outside this is ignored by the compiler If you want to print something as in our case Hello Bhai can be done by adding bol bhai before it Bol bhai means tell brother in Hindi And that s it We are ready to run our first program in Bhailang Run the file on your terminal with the following commandbhailang helloBhai bhai If everything went you should see any output like this If you have an error the Bhailang compiler won t just show you the error but will also talk to you like a friend and say Bro what are you doing It is very cool right Now that we have our Hello Bhai program setup let s get a bit more into the technicalities of Bhailang as a programming language Bhailang BlockAs mentioned before hi bhai is the entry point and bye bhai is the end point This is called the Bhailang block anything outside this block will be ignored A semicolon is a must after each syntax otherwise you can hear the Shark Ashneer Grover every time Ignoredhi bhai commentbye bhai IgnoredDeclaring Variablebhai yea hai is the keyword to declare any type of variable The keyword literally means bro this is Here s an example hi bhai bhai yea hai a bhai yea hai b bye bhaiData Typesnumbers and string are similar to other languages NULL values are defined by nulla which means useless in Hindi sahi correct and galat wrong are the boolean values which are true and false respectively hi bhai bhai yea hai a bhai yea hai b Bhai bhai yea hai c nulla bhai yea hai d sahi bhai yea hai e galat bye bhai Console OutputAs developers we are obsessed with our console It becomes vital to know how we display data on our console Bhailang uses a pretty creative way when it comes to console output bol bhai is used to print output on the console Bol bhai typically means tell me brother hi bhai bhai yea hai a bol bhai a bye bhai ConditionalsBhailang also supports conditional programming The if else block is now agar bhai warna bhai block Try running the following code to see it live hi bhai bhai ye hai a agar bhai a bol bhai “This is even warna bhai bol bhai “This is odd bye bhaiLoopsLastly you can create loops in Bhailang as well jab tak hai block will be executed until the specific condition is sahi true If the condition becomes galat false statements within the block stop executing Use bas kar bhai to break the loop Use agla dekh bhai to continue within the loopThe most distinguishing feature of Bhailang is the way they display the errors Here are some examples Syntax ErrorDivisible by Zero ExceptionInfinite loop Create your own BhailangThese two bhais not only made the effort to build an entire programming language with a compiler and interpreter but these community driven folks also kept the complete source code open on Github DulLabs bhai lang A toy programming language written in Typescript Bhai Lang This is official repository for bhai lang Bhai lang is a toy programming language written in Typescript Installationnpm i g bhailangUsageCreate a new file test bhai Edit the file with a text editorYou can also try out your code on Bhai Lang PlayGroundhi bhai bol bhai Hello bhai bye bhaiRunbhailang test bhaiOutputhello bhaiDocumentationGeneralhi bhai is the entrypoint for the program and all program must end with bye bhai Anything outside of it will be ignored This will be ignoredhi bhai Write code herebye bhaiThis tooVariablesVariables can be declared using bhai ye hai hi bhai bhai ye hai a bhai ye hai b two bhai ye hai c a a b c bye bhaiTypesNumbers and strings… View on GitHubSo what are you waiting for You can also create Bhailang in your own language The source code is attached with an MIT license so you can explore and have fun with the code and create your very own Outro Learning a new language is always fun But understanding the way Bhailang was created and how you can build your own language makes it a whole different game In case you have some questions regarding the article or want to discuss something under the sun feel free to connect with me on LinkedIn If you run an organisation and want me to write for you please do connect with me 2022-04-04 19:32:13
海外TECH DEV Community Python f-strings Are More Powerful Than You Might Think https://dev.to/martinheinz/python-f-strings-are-more-powerful-than-you-might-think-2oop Python f strings Are More Powerful Than You Might ThinkFormatted string literals also called f strings have been around since Python so we all know what they are and how to use them There are however some facts and handy features of f string that you might not know about So let s take a tour of some awesome f string features that you ll want to use in your everyday coding Date and Time FormattingApplying number formatting with f strings is pretty common but did you know that you can also format dates and timestamp strings import datetimetoday datetime datetime today print f today Y m d print f today Y f strings can format date and time as if you used datetime strftime method This is extra nice when you realize that there are more formats than just the few mentioned in the docs Python s strftime supports also all the formats supported by the underlying C implementation which might vary by platform and that s why it s not mentioned in docs With that said you can take advantage of these formats anyway and use for example F which is an equivalent of Y m d or T which is an equivalent of H M S also worth mentioning are x and X which are locales preferred date and time formats respectively Usage of these formats is obviously not limited to f strings Refer to the Linux manpages for full list of formats Variable Names and DebuggingOne of the more recent additions to f string features starting with Python is ability to print variable names along with the value x y print f x x y y x y print f x y Better x y print f x f x This feature is called debugging and can be applied in combination with other modifiers It also preserves whitespaces so f x and f x will produce different strings repr and str When printing class instances str method of the class is used by default for string representation If we however want to force usage of repr we can use the r conversion flag class User def init self first name last name self first name first name self last name last name def str self return f self first name self last name def repr self return f User s name is self first name self last name user User John Doe print f user John Doeprint f user r User s name is John DoeWe could also just call repr some var inside the f string but using the conversion flag is a nice native and concise solution Superior PerformancePowerful features and syntax sugar oftentimes comes with performance penalty that s however not the case when it comes to f strings python m timeit s x y Hello World f x y from string import Templatex y Hello World print f x y nsec per loop Fast print x y nsec per loopprint join x y nsec per loopprint s s x y nsec per loopprint format x y nsec per loopprint Template x y substitute x x y y usec per loop Slow The above samples were tested with timeit module like so python m timeit s x y Hello World f x y and as you can see f strings are actually the fastest of all formatting options Python provides So even if you prefer using some of the older formatting options you might consider switching to f strings just for the performance boost Full Power of Formatting SpecF strings support Python s Format Specification Mini Language so you can embed a lot of formatting operations into their modifiers text hello world Center text print f text hello world number Set separatorprint f number number Add leading zerosprint f number Python s formatting mini language includes much more than just the options to format numbers and dates It allows us to align or center text add leading zeros spaces set thousands separator and more All this is obviously available not just for f strings but for all the other formatting options too Nested F StringsIf basic f strings aren t good enough for your formatting needs you can even nest them into each other number print f f number f gt s You can embed f strings inside f strings for tricky formatting problems like adding a dollar sign to a right aligned float as shown above Nested f strings can also be used in case you need to use variables in the format specifier part This can also make the f string more readable import decimalwidth precision value decimal Decimal print f output value width precision output Conditionals FormattingBuilding on top of the above example with nested f strings we can go a bit farther and use ternary conditional operators inside the inner f string import decimalvalue decimal Decimal print f Result value if value lt else Result value decimal Decimal print f Result value if value lt else Result This can become very unreadable very quickly so you might want to break it into multiple lines instead Lambda ExpressionsIf you want to push limits of f strings and also make whoever reads your code angry then with a little bit of effort you can also use lambdas print f lambda x x Parenthesis around the lambda expression are in this case mandatory because of the which would be otherwise interpreted by f string Closing ThoughtsAs we ve seen here f strings really are quite powerful and have many more features than most people think Most of these unknown features are however mentioned in Python docs so I do recommend reading through docs pages of not just f strings but any other module feature of Python you might be using Diving into the docs will oftentimes help you uncover some very useful features that you won t find even when digging through StackOverflow 2022-04-04 19:15:47
海外TECH DEV Community Creating and Using HTTP Client SDKs in .NET 6 https://dev.to/nikiforovall/creating-and-using-http-client-sdks-in-net-6-2a79 Creating and Using HTTP Client SDKs in NET TL DRLearn three ways you can develop HTTP Client SDKs in NET Source code TL DRKey TakeawaysIntroductionWriting HTTP Client SDKClient LifetimeConsuming API ClientsConsuming API Clients HttpClientFactoryExtending HTTP Client SDKs Adding cross cutting concerns via DelegatingHandlerThird Party ExtensionsTesting HTTP Client SDKsWriting HTTP Client SDK Declarative approachConsuming API Clients RefitWriting HTTP Client SDK Automated approachChoosing the right approachSummaryReference Key TakeawaysWriting and maintaining HTTP Client SDKs is a very important skill for modern NET developers working with distributed systems In order to properly manage HTTP connections you need to design your API Clients to be ready to be consumed from any Dependency Injection container A good client SDK is composable providing straightforward ways to configure and extend it Testing HTTP Client SDKs can be very beneficial in certain scenarios and it gives you additional confidence in your code There are many ways of developing HTTP Client SDKs This article helps you to choose the right one according to your scenario IntroductionToday s cloud based microservice based or internet of things applications often depend on communicating with other systems across a network Each service runs in its process and solves a bounded set of problems Communication between services is based on a lightweight mechanism often an HTTP resource API From a NET developer perspective we want to provide a consistent and manageable way of integrating with a particular service in the form of a distributable package Preferably we also want to ship the service integration code we develop as a NuGet package and share it with other people teams or even organizations In this article I will share many aspects of creating and using HTTP Client SDKs using NET Client SDKs provide a meaningful abstraction layer over remote service Essentially it allows making Remote Procedure Calls RPC The responsibility of a Client SDK is to serialize some data send it to remote deserialize and process a response The main benefits of API SDKs It speedups the API integration processProvides a consistent and standard approachGives somewhat control to service owners over the way APIs are consumed Writing HTTP Client SDKThroughout this article we will write full functioning Dad Jokes API Client It serves dad jokes let s have some fun It is a good idea to start from the contract public interface IDadJokesApiClient Task lt JokeSearchResponse gt SearchAsync string term CancellationToken cancellationToken Task lt Joke gt GetJokeByIdAsync string id CancellationToken cancellationToken Task lt Joke gt GetRandomJokeAsync CancellationToken cancellationToken public class JokeSearchResponse public bool Success get init public List lt Joke gt Body get init new public class Joke public string Punchline get set default public string Setup get set default public string Type get set default The contract is created based on an API you are integrating with My general recommendations are to develop common purpose APIs and follow Robustness Principle and Principle of least astonishment But it is totally fine if you want to modify and transform data contract based on your needs Just think about it from a consumer perspective The bread and butter of HTTP based integrations is HttpClient It contains everything you need to successfully work with HTTP abstractions public class DadJokesApiClient IDadJokesApiClient private readonly HttpClient httpClient public DadJokesApiClient HttpClient httpClient gt this httpClient httpClient Usually we deal with JSON over HTTP APIs so in NET System Net Http Json namespace was added to BCL It provides many extension methods for HttpClient and HttpContent that perform serialization and deserialization using System Text Json If you don t have something complex and exotic I would suggest using System Net Http Json because it frees you from writing boilerplate code Not only it is boring but it also is not trivial to get it right in the most efficient and bug free way from the get go I suggest you check Steves Gordon blog post sending and receiving JSON using HttpClientpublic async Task lt Joke gt GetRandomJokeAsync CancellationToken cancellationToken var jokes await this httpClient GetFromJsonAsync lt JokeSearchResponse gt ApiUrlConstants GetRandomJoke cancellationToken if jokes is Body Count or Success false consider creating custom exceptions for situations like this throw new InvalidOperationException This API is no joke return jokes Body First Tip You may want to create some centralized place to manage the endpoints URLs like this public static class ApiUrlConstants public const string JokeSearch joke search public const string GetJokeById joke public const string GetRandomJoke random joke Tip If you need to deal with complex URIs use Flurl It provides fluent URL building experience public async Task lt Joke gt GetJokeByIdAsync string id CancellationToken cancellationToken ApiUrlConstants GetJokeById id var path ApiUrlConstants GetJokeById AppendPathSegment id var joke await this httpClient GetFromJsonAsync lt Joke gt path cancellationToken return joke new Next we need to specify required headers or some other required configuration We want to provide a flexible mechanism for configuring HttpClient used as part of SDK In this case we need to supply credentials in the custom header and specify a well known Accept header Tip Expose high level building blocks as HttpClientExtensions It makes it easy to discover API specific configuration For example if you have a custom authorization mechanism it should be supported by SDK at least provide documentation for it public static class HttpClientExtensions public static HttpClient AddDadJokesHeaders this HttpClient httpClient string host string apiKey var headers httpClient DefaultRequestHeaders headers Add ApiConstants HostHeader new Uri host Host headers Add ApiConstants ApiKeyHeader apiKey return httpClient Client LifetimeTo construct DadJokesApiClient we need to create HttpClient As you know HttpClient implements IDisposable because there is an underlying unmanageable resource TCP connection There is a limited amount of concurrent TCP connections that can be opened simultaneously on a single machine So it brings an important question Should I create HttpClient every time I need it or only once during an application startup HttpClient is actually a shared object This means that under the covers it is reentrant and thread safe Instead of creating a new instance of HttpClient for each execution you should share a single instance of HttpClient However this comes with its own set of issues For example the client will keep connections open for the lifespan of the application it won t respect the DNS TTL settings and it will never get DNS updates So this isn t a perfect solution either Basically you need to manage a pool of TCP connections that are disposed from time to time to respect DNS updates This is exactly what HttpClientFactory does The official documentation describes HttpClientFactory as being an opinionated factory for creating HttpClient instances to be used in your applications We will see how to use it in a moment Each time you get an HttpClient object from the IHttpClientFactory a new instance is returned But each HttpClient uses an HttpMessageHandler that s pooled and reused by the IHttpClientFactory to reduce resource consumption Pooling of handlers is desirable as each handler typically manages its own underlying HTTP connections Some handlers also keep connections open indefinitely which can prevent the handler from reacting to DNS changes HttpMessageHandler has a limited lifetime Down below you can see how HttpClientFactory comes into play when using HttpClient managed by DI Consuming API ClientsThe very basic scenario is a console application without a dependency injection container The goal here is to give consumers the fastest way possible to integrate Create static factory method that creates an API Client public static class DadJokesApiClientFactory public static IDadJokesApiClient Create string host string apiKey var httpClient new HttpClient BaseAddress new Uri host ConfigureHttpClient httpClient host apiKey return new DadJokesApiClient httpClient internal static void ConfigureHttpClient HttpClient httpClient string host string apiKey ConfigureHttpClientCore httpClient httpClient AddDadJokesHeaders host apiKey internal static void ConfigureHttpClientCore HttpClient httpClient httpClient DefaultRequestHeaders Accept Clear httpClient DefaultRequestHeaders Accept Add new application json Finally we can use IDadJokesApiClient from the console application var host var apiKey lt token gt var client DadJokesApiClientFactory Create host apiKey var joke await client GetRandomJokeAsync Console WriteLine joke Setup joke Punchline Consuming API Clients HttpClientFactoryThe next step is to configure HttpClient as part of a Dependency Injection container I will not go into details there is a lot of good stuff on the internet Once again there is a really good article from Steve s Gordon HttpClientFactory in ASP NET CoreTo add pooled HttpClient to DI you need to use IServiceCollection AddHttpClient from Microsoft Extensions Http Provide a custom extension method to add typed HttpClient in DI public static class ServiceCollectionExtensions public static IHttpClientBuilder AddDadJokesApiClient this IServiceCollection services Action lt HttpClient gt configureClient gt services AddHttpClient lt IDadJokesApiClient DadJokesApiClient gt httpClient gt DadJokesApiClientFactory ConfigureHttpClientCore httpClient configureClient httpClient Use extension method like the following var host var apiKey lt token gt var services new ServiceCollection services AddDadJokesApiClient httpClient gt httpClient BaseAddress new host httpClient AddDadJokesHeaders host apiKey var provider services BuildServiceProvider var client provider GetRequiredService lt IDadJokesApiClient gt var joke await client GetRandomJokeAsync logger Information joke Setup joke Punchline As you see you can use IHttpClientFactory outside of ASP NET Core For example console applications workers lambdas etc Let s see it running The interesting part here is that clients created by DI automatically logs outgoing requests It makes development and troubleshooting so much easier SourceContext EventId patternSystem Net Http HttpClient IDadJokesApiClient LogicalHandler Id Name RequestPipelineStart System Net Http HttpClient IDadJokesApiClient ClientHandler Id Name RequestStart System Net Http HttpClient IDadJokesApiClient ClientHandler Id Name RequestEnd System Net Http HttpClient IDadJokesApiClient LogicalHandler Id Name RequestPipelineEnd The most common scenario is web applications Here is NET MinimalAPI example var builder WebApplication CreateBuilder args var services builder Services var configuration builder Configuration var host configuration DadJokesClient host services AddDadJokesApiClient httpClient gt httpClient BaseAddress new host httpClient AddDadJokesHeaders host configuration DADJOKES TOKEN var app builder Build app MapGet async IDadJokesApiClient client gt await client GetRandomJokeAsync app Run punchline They are all paid actors anyway setup We really shouldn t care what people at the Oscars say type actor Extending HTTP Client SDKs Adding cross cutting concerns via DelegatingHandlerHttpClient provide an extension point message handler A message handler is a class that receives an HTTP request and returns an HTTP response A wide variety of problems could be expressed as cross cutting concerns For example logging authentication caching header forwarding auditing etc Aspect oriented programming aims to encapsulate cross cutting concerns into aspects to retain modularity Typically a series of message handlers are chained together The first handler receives an HTTP request does some processing and gives the request to the next handler At some point the response is created and goes back up the chain supports the most common requirements for most applicationspublic abstract class HttpMessageHandler IDisposable plug a handler into a handler chainpublic abstract class DelegatingHandler HttpMessageHandler Task Assume you need to copy a list of headers from ASP NET Core HttpContext and pass them to all outgoing requests made by Dad Jokes API client public class HeaderPropagationMessageHandler DelegatingHandler private readonly HeaderPropagationOptions options private readonly IHttpContextAccessor contextAccessor public HeaderPropagationMessageHandler HeaderPropagationOptions options IHttpContextAccessor contextAccessor this options options this contextAccessor contextAccessor protected override Task lt HttpResponseMessage gt SendAsync HttpRequestMessage request CancellationToken cancellationToken if this contextAccessor HttpContext null foreach var headerName in this options HeaderNames var headerValue this contextAccessor HttpContext Request Headers headerName request Headers TryAddWithoutValidation headerName string headerValue return base SendAsync request cancellationToken public class HeaderPropagationOptions public IList lt string gt HeaderNames get set new List lt string gt Now we want to plug DelegatingHandler into HttpClient request pipeline For non IHttpClientFactory scenarios we want clients to specify a list of DelegatingHandler so we can build an underlying chain for HttpClient DadJokesApiClientFactory cspublic static IDadJokesApiClient Create string host string apiKey params DelegatingHandler handlers var httpClient new HttpClient if handlers Length gt handlers Aggregate a b gt a InnerHandler b return b httpClient new handlers httpClient BaseAddress new Uri host ConfigureHttpClient httpClient host apiKey return new DadJokesApiClient httpClient So without DI container extended DadJokesApiClient could be constructed like this var loggingHandler new LoggingMessageHandler outermostvar authHandler new AuthMessageHandler var propagationHandler new HeaderPropagationMessageHandler var primaryHandler new HttpClientHandler the default handler used by HttpClientDadJokesApiClientFactory Create host apiKey loggingHandler authHandler propagationHandler primaryHandler LoggingMessageHandler ➝AuthMessageHandler ➝HeaderPropagationMessageHandler ➝HttpClientHandlerFor DI container scenarios on another hand we want to provide auxiliary extension method to easily plug HeaderPropagationMessageHandler by using IHttpClientBuilder AddHttpMessageHandler public static class HeaderPropagationExtensions public static IHttpClientBuilder AddHeaderPropagation this IHttpClientBuilder builder Action lt HeaderPropagationOptions gt configure builder Services Configure configure builder AddHttpMessageHandler sp gt return new HeaderPropagationMessageHandler sp GetRequiredService lt IOptions lt HeaderPropagationOptions gt gt Value sp GetRequiredService lt IHttpContextAccessor gt return builder Here is how extended MinimalAPI example looks like var builder WebApplication CreateBuilder args var services builder Services var configuration builder Configuration var host configuration DadJokesClient host services AddDadJokesApiClient httpClient gt httpClient BaseAddress new host httpClient AddDadJokesHeaders host configuration DADJOKES TOKEN AddHeaderPropagation o gt o HeaderNames Add X Correlation ID var app builder Build app MapGet async IDadJokesApiClient client gt await client GetRandomJokeAsync app Run Sometimes functionality like this is reused by other services You might want to take it one step further and factor out all shared code into a common NuGet package and use it in HTTP Client SDKs Third Party ExtensionsNot only we can write our own message handlers There is a lot of useful NuGet packages provided and supported by NET OSS community Here are my favorites Resiliency patterns retry cache fallback etc Very often in distrusted systems world you need to ensure high availability by incorporating some resilience policies Luckily we have a built in solution to build and define policies in NET Polly There is out of the box integration with IHttpClientFactory provided by Polly This uses a convenience method IHttpClientBuilder AddTransientHttpErrorPolicy It configures a policy to handle errors typical of HTTP calls HttpRequestException HTTP XX status codes server errors HTTP status code request timeout services AddDadJokesApiClient httpClient gt httpClient BaseAddress new host AddTransientHttpErrorPolicy builder gt builder WaitAndRetryAsync new TimeSpan FromSeconds TimeSpan FromSeconds TimeSpan FromSeconds For example transient errors might be handled proactively by using Retry and Circuit Breaker patterns Usually we use a retry pattern when there is a hope that downstream service will self correct eventually Waiting between retries provides an opportunity for a downstream service to stabilize It is common to use retries based on the Exponential Backoff algorithm On paper it sounds great but in real world scenarios the retry pattern may be overused Additional retries might be the source of additional load or spikes In the worst case resources in the caller may then become exhausted or excessively blocked waiting for replies which will never come causing an upstream cascading failure This is when the Circuit Breaker pattern comes into play It detects the level of faults and prevents calls to a downstream service when a fault threshold is exceeded Use this pattern when there is no chance of succeeding for example where a subsystem is completely offline or struggling under load The idea behind Circuit Breaker is pretty straightforward although you might build something more complex on top of it When faults exceed the threshold calls are placed through the circuit so instead of processing a request we practice the fail fast approach throwing an exception immediately Polly is really powerful and it provides a way to combine resilience strategies See PolicyWrap Here is a classification of the strategies you might want to use Designing reliable systems could be a challenging task I suggest you investigate the subject on your own Here is a good introduction NET microservices Architecture e book Implement resilient applicationsAuthentication in OAuth OIDC If you need to manage user and client access tokens I suggest using IdentityModel AspNetCore It acquires caches and rotates tokens for you see the docs adds user and client access token managementservices AddAccessTokenManagement options gt options Client Clients Add identity provider new ClientCredentialsTokenRequest Address ClientId my awesome service ClientSecret secret Scope api optional registers HTTP client that uses the managed client access token adds the access token handler to HTTP client registrationservices AddDadJokesApiClient httpClient gt httpClient BaseAddress new host AddClientAccessTokenHandler Testing HTTP Client SDKsBy this time you should be pretty comfortable designing and writing your own HTTP Client SDKs The only thing that is left is to write some tests to ensure expected behavior Note it might be a good idea to skip extensive unit testing and write more integration or ee to ensure proper integration For now I will show you how to unit test DadJokesApiClient As you have seen previously HttpClient is extensible Furthermore we can replace the standard HttpMessageHandler with the test version So instead of sending actual requests over the wire we will use the mock This technique opens tons of opportunities because we can simulate all kinds of behaviors of HttpClient that otherwise could be hard to replicate in a normal situation Let s define reusable methods to create a mock of HttpClient that we will pass as a dependency to DadJokesApiClient public static class TestHarness public static Mock lt HttpMessageHandler gt CreateMessageHandlerWithResult lt T gt T result HttpStatusCode code HttpStatusCode OK var messageHandler new Mock lt HttpMessageHandler gt messageHandler Protected Setup lt Task lt HttpResponseMessage gt gt SendAsync ItExpr IsAny lt HttpRequestMessage gt ItExpr IsAny lt CancellationToken gt ReturnsAsync new HttpResponseMessage StatusCode code Content new StringContent JsonSerializer Serialize result return messageHandler public static HttpClient CreateHttpClientWithResult lt T gt T result HttpStatusCode code HttpStatusCode OK var httpClient new HttpClient CreateMessageHandlerWithResult result code Object BaseAddress new return httpClient From this point unit testing is a pretty simple process public class DadJokesApiClientTests Theory AutoData public async Task GetRandomJokeAsync SingleJokeInResult Returned Joke joke Arrange var response new JokeSearchResponse Success true Body new joke var httpClient CreateHttpClientWithResult response var sut new DadJokesApiClient httpClient Act var result await sut GetRandomJokeAsync Assert result Should BeEquivalentTo joke Fact public async Task GetRandomJokeAsync UnsuccessfulJokeResult ExceptionThrown Arrange var response new JokeSearchResponse var httpClient CreateHttpClientWithResult response var sut new DadJokesApiClient httpClient Act Assert await FluentActions Invoking gt sut GetRandomJokeAsync Should ThrowAsync lt InvalidOperationException gt Using HttpClient is the most flexible approach You have full control over integration with APIs But there is a downside you need to write a lot of boilerplate code In some situations an API you are integrating with is trivial so you don t really need all capabilities provided by HttpClient HttpRequestMessage HttpResponseMessage Pros Full control over behavior and data contracts You can even write smart API Client and move some logic inside SDK if it makes sense for a particular scenario For example you can throw custom exceptions transform requests and responses provide default values for headers etc Full control over serialization and deserialization processEasy to debug and troubleshoot A stack trace is simple and you can always spin up the debugger to see what is happening under the hood Cons Need to write a lot of repetitive codeSomeone should maintain a code base in case of API changes and bugs This is a tedious and error prone process Writing HTTP Client SDK Declarative approachThe less code the fewer bugs Refit is an automatic type safe REST library for NET It turns your REST API into a live interface Refit uses System Text Json as the default JSON serializer Every method must have an HTTP attribute that provides the request method and relative URL using Refit public interface IDadJokesApiClient lt summary gt Searches jokes by term lt summary gt Get joke search Task lt JokeSearchResponse gt SearchAsync string term CancellationToken cancellationToken default lt summary gt Gets a joke by id lt summary gt Get joke id Task lt Joke gt GetJokeByIdAsync string id CancellationToken cancellationToken default lt summary gt Gets a random joke lt summary gt Get random joke Task lt JokeSearchResponse gt GetRandomJokeAsync CancellationToken cancellationToken default Refit generates type that implements IDadJokesApiClient based on information provided by Refit HttpMethodAttribute Consuming API Clients RefitThe approach is the same as for vanilla HttpClient integration but instead of constructing a client manually we use static method provided by Refit public static class DadJokesApiClientFactory public static IDadJokesApiClient Create HttpClient httpClient string host string apiKey httpClient BaseAddress new Uri host ConfigureHttpClient httpClient host apiKey return RestService For lt IDadJokesApiClient gt httpClient For DI container scenarios we can use Refit HttpClientFactoryExtensions AddRefitClient extension method public static class ServiceCollectionExtensions public static IHttpClientBuilder AddDadJokesApiClient this IServiceCollection services Action lt HttpClient gt configureClient var settings new RefitSettings ContentSerializer new SystemTextJsonContentSerializer new JsonSerializerOptions PropertyNameCaseInsensitive true WriteIndented true return services AddRefitClient lt IDadJokesApiClient gt settings ConfigureHttpClient httpClient gt DadJokesApiClientFactory ConfigureHttpClient httpClient configureClient httpClient Usage var builder WebApplication CreateBuilder args var configuration builder Configuration Log Logger new LoggerConfiguration WriteTo Console CreateBootstrapLogger builder Host UseSerilog ctx cfg gt cfg WriteTo Console var services builder Services services AddDadJokesApiClient httpClient gt var host configuration DadJokesClient host httpClient BaseAddress new host httpClient AddDadJokesHeaders host configuration DADJOKES TOKEN var app builder Build app MapGet async Task lt Joke gt IDadJokesApiClient client gt var jokeResponse await client GetRandomJokeAsync return jokeResponse Body First unwraps JokeSearchResponse app Run Note since the contract of the generated client should match the underlying data contract we no longer have control of contract transformation and this responsibility is delegated to consumers Let s see how the code above works in practice The output of MinimalAPI example is different because I ve added Serilog logging punchline Forgery setup Why was the blacksmith charged with type forgery As usual there are some pros and some cons Pros Easy to use and develop API clients Highly configurable Flexible enough to get things done No need for additional unit testingCons Hard to troubleshoot Sometimes it can be hard to understand how the generated code works For example there is a mismatch in configuration Requires other team members to understand how to read and write code developed with Refit Still consumes some time for medium large APIs Honorable mentions RestEase RESTFulSense Writing HTTP Client SDK Automated approachThere is a way to fully automate HTTP Client SDKs The OpenAPI Swagger specification uses JSON and JSON Schema to describe a RESTful web API The NSwag project provides tools to generate client code from these OpenAPI specifications Everything can be automated via CLI distributed via NuGet tool or build target or NPM Actually Dad Jokes API doesn t provide OpenAPI so I had to write it manually Fortunately it was quite easy to do openapi info title Dad Jokes API version servers url paths joke id get description operationId GetJokeById parameters name id in path description required true schema type string responses description successful operation content application json schema ref components schemas Joke random joke get description operationId GetRandomJoke parameters responses description successful operation content application json schema ref components schemas JokeResponse joke search get description operationId SearchJoke parameters responses description successful operation content application json schema ref components schemas JokeResponse components schemas Joke type object required id punchline setup type properties id type string type type string setup type string punchline type string JokeResponse type object properties sucess type boolean body type array items ref components schemas Joke Now we want to generate HTTP Client SDK automatically Let s use NSwagStudio Here is how the generated IDadJokesApiClient looks like XML comments are deleted for brevity System CodeDom Compiler GeneratedCode NSwag NJsonSchema v Newtonsoft Json v public partial interface IDadJokesApiClient System Threading Tasks Task lt Joke gt GetJokeByIdAsync string id System Threading Tasks Task lt Joke gt GetJokeByIdAsync string id System Threading CancellationToken cancellationToken System Threading Tasks Task lt JokeResponse gt GetRandomJokeAsync System Threading Tasks Task lt JokeResponse gt GetRandomJokeAsync System Threading CancellationToken cancellationToken System Threading Tasks Task lt JokeResponse gt SearchJokeAsync System Threading Tasks Task lt JokeResponse gt SearchJokeAsync System Threading CancellationToken cancellationToken As usual we want to provide the registration of typed client as an extension method public static class ServiceCollectionExtensions public static IHttpClientBuilder AddDadJokesApiClient this IServiceCollection services Action lt HttpClient gt configureClient gt services AddHttpClient lt IDadJokesApiClient DadJokesApiClient gt httpClient gt configureClient httpClient Usage var builder WebApplication CreateBuilder args var configuration builder Configuration var services builder Services services AddDadJokesApiClient httpClient gt var host configuration DadJokesClient host httpClient BaseAddress new host httpClient AddDadJokesHeaders host configuration DADJOKES TOKEN var app builder Build app MapGet async Task lt Joke gt IDadJokesApiClient client gt var jokeResponse await client GetRandomJokeAsync return jokeResponse Body First app Run Let s run it and enjoy the last joke of this article punchline And it s really taken off setup So I invested in a hot air balloon company type air Pros Based on the well known specificationSupported by rich set of tools and vibrant communityFully automated new SDK can be generated as part of CI CD process every time OpenAPI specification is changedGenerate SDKs for multiple programming languagesRelatively easy to troubleshoot since we can see the code generated by the toolchain Cons Can t be applied without proper OpenAPI specificationHard to customize and control the contract of generated API ClientHonorable mentions AutoRest Visual Studio Connected Services Choosing the right approachWe have three different ways of producing SDK clients The selection process can be simplified to the next categoriesI m a simple man woman non binary I want to have full control over my HTTP Client integration Use manual approach I m a busy man woman non binary but I still want to have somewhat control Use a declarative approach I m a lazy man woman non binary Do the thing for me Use an automated approach Decision chart SummaryWe ve reviewed different ways of developing HTTP Client SDKs Choosing the right approach depends on use case and requirements but I hope this article gives you nice foundations for making the best design decisions Thank you Reference 2022-04-04 19:03:25
Apple AppleInsider - Frontpage News Keychron Q3 Review: An excellent base for mechanical keyboard customization https://appleinsider.com/articles/22/04/04/keychron-q3-review-an-excellent-base-for-mechanical-keyboard-customization?utm_medium=rss Keychron Q Review An excellent base for mechanical keyboard customizationIf you re looking for a tenkeyless mechanical keyboard built around a Mac centric experience the Keychron Q might be the best keyboard for your money When it comes to a customizable solidly designed typing experience the new Keychron Q hits virtually all of the marks and only misses a few relatively minor metrics The Keychron Q unlike other models in the company s lineup really focuses on customization It stands out compared to other Q series with its design that provides a more familiar with comfortable experience Read more 2022-04-04 19:08:48
海外TECH Engadget The DeLorean EV will be unveiled on August 18th https://www.engadget.com/delorean-ev-concept-unveiling-august-18th-193552485.html?src=rss The DeLorean EV will be unveiled on August thAfter years of teasing the DeLorean Motor Company announced on Monday that it will unveil an all electric vehicle on August th promising to share its official name at the same time Details on the concept car are scant but what the automaker did share is that it worked with Italdesign best known for its work with Volkswagen to design the upcoming car Judging from the DeLorean s website the vehicle will feature the iconic gull wing doors of the DMC Let s clear things up a bit The next generation of DeLorean is coming into focus August For more information read the press release here DeLorean DeloreanEVolved firstlookpic twitter com HtiODqvーDeLorean Motor Company deloreanmotorco April To be clear the company making the DeLorean EV isn t the same one that produced the DMC The DeLorean Motor Company of Texas is known for restoring vintage DeLorean vehicles billing itself as the largest source of parts for the defunct brand that made the original We ll also note it s been talking about electrification since when it said it was working on making an all electric DeLorean with a mile range nbsp 2022-04-04 19:35:52
海外科学 NYT > Science Stopping Climate Change Is Doable, but Time Is Short, U.N. Panel Warns https://www.nytimes.com/2022/04/04/climate/climate-change-ipcc-un.html Stopping Climate Change Is Doable but Time Is Short U N Panel WarnsA major new scientific report offers a road map for how countries can limit global warming but warns that the margin for error is vanishingly small 2022-04-04 19:29:15
海外科学 NYT > Science On Its Way to the U.S., Russian Oil Tanker Makes Giant U-Turn https://www.nytimes.com/2022/04/02/climate/oil-tankers-russia.html On Its Way to the U S Russian Oil Tanker Makes Giant U TurnThe ship originally sailing to Philadelphia apparently lost its buyer in the middle of the Atlantic A number of tankers carrying Russian oil face similar problems 2022-04-04 19:22:35
ニュース BBC News - Home Channel 4 privatisation to go ahead https://www.bbc.co.uk/news/entertainment-arts-60985496?at_medium=RSS&at_campaign=KARANGA industry 2022-04-04 19:45:46
ニュース BBC News - Home Easter flight cancellations to continue for days https://www.bbc.co.uk/news/business-60990119?at_medium=RSS&at_campaign=KARANGA absence 2022-04-04 19:27:53
ニュース BBC News - Home Sacramento shooting: One arrest made after six shot dead https://www.bbc.co.uk/news/world-us-canada-60990658?at_medium=RSS&at_campaign=KARANGA shooting 2022-04-04 19:09:35
ニュース BBC News - Home Gummies: Woman dies after eating cannabis gummy sweet https://www.bbc.co.uk/news/uk-england-london-60989389?at_medium=RSS&at_campaign=KARANGA cannabis 2022-04-04 19:05:56
ビジネス ダイヤモンド・オンライン - 新着記事 40代で年収が高い職種ランキング【技術(IT・通信)】2位ITコンサル、1位は? - DIAMONDランキング&データ https://diamond.jp/articles/-/300949 diamond 2022-04-05 04:55:00
ビジネス ダイヤモンド・オンライン - 新着記事 マッキンゼー流!日本企業の利益水準が低いのは「あるスキル」の格差が要因だった【動画】 - マッキンゼー流!リーダーの新教科書 ―戦略とファイナンス― https://diamond.jp/articles/-/292541 マッキンゼー流日本企業の利益水準が低いのは「あるスキル」の格差が要因だった【動画】マッキンゼー流リーダーの新教科書ー戦略とファイナンスーマッキンゼー流企業価値を持続的に創造していく経営の極意とはまた求められる思考法とスキルとは第回は、事業の「稼ぐ力」を高めるために必須の「機能スキル」について解説。 2022-04-05 04:50:00
ビジネス ダイヤモンド・オンライン - 新着記事 中国・習近平がEU首脳に語った「ウクライナ危機」の4つの解決方法 - 加藤嘉一「中国民主化研究」揺れる巨人は何処へ https://diamond.jp/articles/-/300948 2022-04-05 04:45:00
ビジネス ダイヤモンド・オンライン - 新着記事 GAFA撤退でロシアのネット空間はどうなる? 「IT鎖国の先輩」中国の例から考える - DOL特別レポート https://diamond.jp/articles/-/300331 言論統制 2022-04-05 04:40:00
ビジネス ダイヤモンド・オンライン - 新着記事 ウクライナ侵攻でまさかの「2%物価目標」達成、日銀は金融政策修正のチャンスを逃すな - 政策・マーケットラボ https://diamond.jp/articles/-/300919 ウクライナ侵攻でまさかの「物価目標」達成、日銀は金融政策修正のチャンスを逃すな政策・マーケットラボ日本の物価環境は、新型コロナ対応に乗り出した年春頃と今とで大きく変わった。 2022-04-05 04:35:00
ビジネス ダイヤモンド・オンライン - 新着記事 【京都教育大学附属高校】華麗なる卒業生人脈!日本航空会長、裏千家家元、BONNIE PINK、女優の山村紅葉、国民民主の前原誠司… - 日本を動かす名門高校人脈 https://diamond.jp/articles/-/300842 bonniepink 2022-04-05 04:30:00
ビジネス ダイヤモンド・オンライン - 新着記事 温泉、ビール、ねこ、チョコ、夜景、定年力…挑戦してみよう!ユニークな資格10選 - DX時代を生き抜くための「リスキリング」 https://diamond.jp/articles/-/300945 資格 2022-04-05 04:27:00
ビジネス ダイヤモンド・オンライン - 新着記事 「日本の有事」の医療を支える自衛隊病院が、相次ぎ閉鎖される深刻な理由 - DOL特別レポート https://diamond.jp/articles/-/300503 自衛隊病院 2022-04-05 04:25:00
ビジネス ダイヤモンド・オンライン - 新着記事 「カミカゼドローン」100機にロシア兵が逃げ惑う…日本の防衛政策転換は急務 - DOL特別レポート https://diamond.jp/articles/-/300997 防衛政策 2022-04-05 04:22:00
ビジネス ダイヤモンド・オンライン - 新着記事 新社会人が知るべき、日本の経済「格差」が拡大している真の理由とは? - 今週のキーワード 真壁昭夫 https://diamond.jp/articles/-/300947 世界経済 2022-04-05 04:20:00
ビジネス ダイヤモンド・オンライン - 新着記事 容器持参の「量り売り店」の開業が相次ぐ理由とは - News&Analysis https://diamond.jp/articles/-/299175 newsampampanalysis 2022-04-05 04:15:00
ビジネス ダイヤモンド・オンライン - 新着記事 中国がロシアを飲み込み「モンゴル帝国」再出現?日本の難しい舵取り - 上久保誠人のクリティカル・アナリティクス https://diamond.jp/articles/-/300946 上久保誠人 2022-04-05 04:10:00
ビジネス 東洋経済オンライン 製造部門が「営業」の目標にムカつく納得の理由 組織間の摩擦を解決するにはどうしたらいいか | 消費・マーケティング | 東洋経済オンライン https://toyokeizai.net/articles/-/578609?utm_source=rss&utm_medium=http&utm_campaign=link_back 売り上げ 2022-04-05 04:30:00
海外TECH reddit Match Thread: Crystal Palace vs Arsenal [English Premier League] https://www.reddit.com/r/Gunners/comments/twa0pt/match_thread_crystal_palace_vs_arsenal_english/ Match Thread Crystal Palace vs Arsenal English Premier League HT Crystal Palace Arsenal Crystal Palace scorers Jean Philippe Mateta Jordan Ayew Venue Selhurst Park Auto refreshing reddit comments link Follow us on Twitter Join us on Discord LINE UPS Crystal Palace Vicente Guaita Marc Guehi Joachim Andersen Tyrick Mitchell Nathaniel Clyne Cheikhou Kouyate Jeff Schlupp Conor Gallagher Jean Philippe Mateta Wilfried Zaha Jordan Ayew Subs James Mcarthur Will Hughes Luka Milivojevic Odsonne Edouard James Tomkins Eberechi Eze Jack Butland Joel Ward Christian Benteke Arsenal Aaron Ramsdale Gabriel Ben White Nuno Tavares Cedric Soares Martin Odegaard Granit Xhaka Thomas Partey Alexandre Lacazette Emile Smith Rowe Bukayo Saka Subs Gabriel Martinelli Rob Holding Marcelo Flores Zak Swanson Edward Nketiah Bernd Leno Albert Sambi Lokonga Mazeed Ogungbo Mohamed Elneny MATCH EVENTS via ESPNFC Corner Arsenal Conceded by Nathaniel Clyne Attempt saved Gabriel Magalhães Arsenal header from very close range is saved in the top centre of the goal Assisted by Emile Smith Rowe with a cross First Half ends Crystal Palace Arsenal submitted by u GunnersMatchBot to r Gunners link comments 2022-04-04 19:01:13

コメント

このブログの人気の投稿

投稿時間:2021-06-17 05:05:34 RSSフィード2021-06-17 05:00 分まとめ(1274件)

投稿時間:2021-06-20 02:06:12 RSSフィード2021-06-20 02:00 分まとめ(3871件)

投稿時間:2020-12-01 09:41:49 RSSフィード2020-12-01 09:00 分まとめ(69件)