<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Rob on Medium]]></title>
        <description><![CDATA[Stories by Rob on Medium]]></description>
        <link>https://medium.com/@robdotnet?source=rss-ebac3b5714b5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*HhPP198uiLHvmsLvyTDg6g.jpeg</url>
            <title>Stories by Rob on Medium</title>
            <link>https://medium.com/@robdotnet?source=rss-ebac3b5714b5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 14:01:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@robdotnet/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[C# — Get all places in town for a specific activity]]></title>
            <link>https://robdotnet.medium.com/c-get-all-places-in-town-for-a-specific-activity-5a7a486c4c84?source=rss-ebac3b5714b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a7a486c4c84</guid>
            <category><![CDATA[google-api]]></category>
            <category><![CDATA[activites]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[places-api]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <dc:creator><![CDATA[Rob]]></dc:creator>
            <pubDate>Thu, 16 Feb 2023 07:25:57 GMT</pubDate>
            <atom:updated>2023-02-16T07:25:57.519Z</atom:updated>
            <content:encoded><![CDATA[<h3>C# — Get all places in town for a specific activity</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VGJaL5NLJBtu6wcc" /><figcaption>Photo by <a href="https://unsplash.com/es/@gabinvallet?utm_source=medium&amp;utm_medium=referral">Gabin Vallet</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Sometimes you want to do a certain activity, for example bouldering, and you are looking for an appropriate provider in your region.<br>For this purpose, you can easily use Google Maps nowadays and you will get a list of different places where you can go bouldering.<br>If you want to use this data for your own application, you first have to create an account at Google and generate an API Key.<br>Attention: Only create API Keys for interfaces you really need to avoid misuse.</p><h3>API Key bei Google einrichten</h3><p>To do this, we go to the <a href="https://console.cloud.google.com/">Google Console</a> and create an API Key with access to the <strong>Places API</strong> and <strong>Geocode API</strong> interfaces.</p><p>Then we can use the API key to receive data from Google.</p><h3>Setup Google Client</h3><p>To connect to Google, we need to copy the following code into our application.</p><pre>public class GoogleMapsApiClient<br>{<br>    private readonly string googleApiKey;<br>    private readonly HttpClient httpClient;<br>    private readonly static string geocodingBaseUrl = &quot;https://maps.googleapis.com/maps/api/geocode/json&quot;;<br>    private static readonly string nearbySearchBaseUrl = &quot;https://maps.googleapis.com/maps/api/place/nearbysearch/json&quot;;<br>    private static readonly string placeDetailsBaseUrl = &quot;https://maps.googleapis.com/maps/api/place/details/json&quot;;<br><br>    /// &lt;summary&gt;<br>    /// HttpClient instance to be used for the requests<br>    /// &lt;/summary&gt;<br>    /// &lt;param name=&quot;httpClient&quot;&gt;&lt;/param&gt;<br>    public GoogleMapsApiClient(string apiKey, HttpClient httpClient)<br>    {<br>        this.googleApiKey = apiKey;<br>        this.httpClient = httpClient;<br>    }<br><br>    public async Task&lt;IList&lt;GoogleMapsPlaceData&gt;&gt; LookupNearbyPlaces(string location, int radiusInMeters, string keyword)<br>    {<br><br>        if (string.IsNullOrWhiteSpace(location))<br>        {<br>            throw new ArgumentException(&quot;Location argument cannot be empty&quot;);<br>        }<br><br>        // Lookup the coordinates of the location around which the search should take place<br><br>        NameValueCollection queryString = HttpUtility.ParseQueryString(string.Empty);<br><br>        queryString.Add(&quot;key&quot;, googleApiKey);<br>        queryString.Add(&quot;address&quot;, location);<br>        var response = await httpClient.GetStringAsync(geocodingBaseUrl + &quot;?&quot; + queryString.ToString());<br><br>        var geocodingData = JsonSerializer.Deserialize&lt;GeocodingData&gt;(response);<br><br>        if (geocodingData.results == null || geocodingData.results.Length == 0)<br>        {<br>            throw new LookupException($&quot;Location \&quot;{location}\&quot; not found or error occured (response status: \&quot;{geocodingData.status}\&quot;).&quot;);<br>        }<br><br>        float locationLat = geocodingData.results[0].geometry.location.lat;<br>        float locationLng = geocodingData.results[0].geometry.location.lng;<br><br>        // Now that we have coordinates of the place, find places for given keyword within given radius<br><br>        PlacesData placesFoundInRadius = null;<br>        int maxPages = 30;<br>        string nextPageToken = null;<br><br>        while (true)<br>        {<br>            queryString = HttpUtility.ParseQueryString(string.Empty);<br><br>            queryString.Add(&quot;key&quot;, googleApiKey);<br>            if (string.IsNullOrEmpty(nextPageToken))<br>            {<br>                queryString.Add(&quot;location&quot;, $&quot;{locationLat.ToString(CultureInfo.InvariantCulture)},{locationLng.ToString(CultureInfo.InvariantCulture)}&quot;);<br>                queryString.Add(&quot;keyword&quot;, keyword);<br>                queryString.Add(&quot;radius&quot;, radiusInMeters.ToString());<br>            }<br>            else<br>            {<br>                queryString.Add(&quot;pagetoken&quot;, nextPageToken);<br>                // Requesting next page too fast results in INVALID_REQUEST, hence the delay. This is a known &quot;feature&quot;<br>                Thread.Sleep(3);<br>            }<br><br>            response = await httpClient.GetStringAsync(nearbySearchBaseUrl + &quot;?&quot; + queryString.ToString());<br><br>            var placesData = JsonSerializer.Deserialize&lt;PlacesData&gt;(response);<br><br>            if (placesFoundInRadius == null)<br>            {<br>                placesFoundInRadius = placesData;<br>            }<br>            else<br>            {<br>                placesFoundInRadius.results.AddRange(placesData.results);<br>            }<br><br>            nextPageToken = string.IsNullOrEmpty(placesData.next_page_token) || (maxPages -= 1) == 0 ? null : placesData.next_page_token;<br>            if (nextPageToken == null)<br>            {<br>                break;<br>            }<br>        }<br><br>        var places = new ConcurrentBag&lt;GoogleMapsPlaceData&gt;();<br><br>        // Get details for each place (in parallel)<br><br>        Parallel.ForEach(<br>            placesFoundInRadius.results.Select(p =&gt; p.place_id),<br>            new ParallelOptions { MaxDegreeOfParallelism = 6 },<br>            async placeId =&gt;<br>            {<br>                var place = await GetById(placeId);<br>                places.Add(place);<br>            });<br><br>        return places.ToList();<br>    }<br><br>    public async Task&lt;GoogleMapsPlaceData&gt; GetById(string placeId)<br>    {<br>        var queryString1 = HttpUtility.ParseQueryString(string.Empty);<br><br>        queryString1.Add(&quot;key&quot;, googleApiKey);<br>        queryString1.Add(&quot;place_id&quot;, placeId);<br>        queryString1.Add(&quot;fields&quot;, &quot;name,formatted_address,formatted_phone_number,website,opening_hours,rating,user_ratings_total&quot;);<br><br>        var response = httpClient.GetStringAsync(placeDetailsBaseUrl + &quot;?&quot; + queryString1.ToString()).Result;<br>        var placeDetailsData = JsonSerializer.Deserialize&lt;PlaceDetailsData&gt;(response);<br><br>        if (placeDetailsData.result == null)<br>        {<br>            throw new LookupException($&quot;Could not retrieve details for place with id = \&quot;{placeId}\&quot; (response status: \&quot;{placeDetailsData.status}\&quot;).&quot;);<br>        }<br><br>        return new GoogleMapsPlaceData()<br>        {<br>            Id = placeId,<br>            Name = placeDetailsData.result.name,<br>            Address = placeDetailsData.result.formatted_address,<br>            Phone = placeDetailsData.result.formatted_phone_number,<br>            WebsiteUrl = placeDetailsData.result.website,<br>            Rating = placeDetailsData.result.rating,<br>            TotalRates = placeDetailsData.result.user_ratings_total,<br>            OpeningTimes = placeDetailsData.result.opening_hours?.weekday_text,<br>        };<br>    }<br>}</pre><p>And the <strong>model</strong> looks like:</p><pre>public class GoogleMapsPlaceData<br>{<br>    public string Id { get; set; }<br>    public string Name { get; set; }<br>    public string Address { get; set; }<br>    public string Phone { get; set; }<br>    public string WebsiteUrl { get; set; }<br>    public double Rating { get; set; }<br>    public int TotalRates { get; set; }<br>    public string[] OpeningTimes { get; set; }<br>}</pre><h3>Initialize Client</h3><pre>public class Google <br>{<br>    public static async Task&lt;IList&lt;GoogleMapsPlaceData&gt;&gt; GetPlacesNearBy(string region, string keyWord, int radius)<br>    {<br>        //TODO: Insert your Goole API Key here<br>        var apiKey = Environment.GetEnvironmentVariable(EnvironmentVariableKeys.GOOGLE_APIKEY);<br>        var httpClient = new HttpClient();<br>        var apiClient = new GoogleMapsApiClient(apiKey, httpClient);<br>        return await apiClient.LookupNearbyPlaces(region, radius, keyWord);<br>    }<br>}</pre><h3>Aufruf der API</h3><p>Then we can easily find suitable providers by providing the parameters for the radius, activity and location.</p><pre>var serviceResult = await Google.GetPlacesNearBy(&quot;Nürnberg&quot;, &quot;Restaurant&quot;, 10000);</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a7a486c4c84" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[C# — Get public and school holidays for a specific region]]></title>
            <link>https://medium.com/c-sharp-programming/c-get-public-and-school-holidays-for-a-specific-region-7c8e698013c0?source=rss-ebac3b5714b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c8e698013c0</guid>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[holidays]]></category>
            <category><![CDATA[school-holidays]]></category>
            <category><![CDATA[public-holidays]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <dc:creator><![CDATA[Rob]]></dc:creator>
            <pubDate>Tue, 07 Feb 2023 07:59:08 GMT</pubDate>
            <atom:updated>2023-02-16T08:07:49.772Z</atom:updated>
            <content:encoded><![CDATA[<h3>C# — Get public and school holidays for a certain region</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bLq1YBmrgNO2EitF" /><figcaption>Photo by <a href="https://unsplash.com/pt-br/@linkhoang?utm_source=medium&amp;utm_medium=referral">Link Hoang</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Recently I was working on a feature for a new app where I needed to find out if a certain day, for example 02/06/2023 is a vacation or a vacation day within a certain region.<br>After some searching and analyzing the available C# solutions, I came across the following API:</p><p><a href="https://www.openholidaysapi.org/">https://openholidaysapi.org</a></p><p>I included those in my project and used them for HTTP requests.</p><p>Code Snippet: <strong>Is Working Day</strong></p><pre>/// &lt;summary&gt;<br>/// Checks if the specified day is a working day<br>/// &lt;/summary&gt;<br>/// &lt;param name=&quot;dateTime&quot;&gt;Day to be checked&lt;/param&gt;<br>/// &lt;param name=&quot;countryCode&quot;&gt;The country code of the country to be checked&lt;/param&gt;<br>/// &lt;param name=&quot;division&quot;&gt;The state or region to be tested&lt;/param&gt;<br>/// &lt;returns&gt;Information if it is a working day&lt;/returns&gt;<br>public bool IsWorkingDay(DateTime dateTime, string countryCode, string division)<br>{<br>    var endpoint = &quot;https://openholidaysapi.org/PublicHolidays&quot;;<br>    endpoint = $&quot;{endpoint}?countryIsoCode={countryCode}&amp;validFrom={dateTime.Year}-{dateTime.Month}-{dateTime.Day}&quot; +<br>        $&quot;&amp;validTo={dateTime.Year}-{dateTime.Month}-{dateTime.Day}&quot;;<br><br>    var client = new RestClient(endpoint);<br>    var request = new RestRequest();<br>    request.AddHeader(&quot;Content-Type&quot;, &quot;application/json&quot;);<br>    request.AddHeader(&quot;Accept&quot;, &quot;application/json&quot;);<br>    var response = client.Execute(request);<br><br>    if (response.ResponseStatus == ResponseStatus.Completed)<br>    {<br>        return JsonSerializer.Deserialize&lt;IEnumerable&lt;DaysOff&gt;&gt;(response.Content)<br>            .ToList()<br>            .Any(_ =&gt; _.subdivisions.Any(s =&gt; s.shortName == division));<br>    }<br>    else<br>        return false;<br>}</pre><p><strong>Code Snippet: Is School day</strong></p><pre>/// &lt;summary&gt;<br>/// Checks if the specified day is a school day<br>/// &lt;/summary&gt;<br>/// &lt;param name=&quot;dateTime&quot;&gt;Day to be checked&lt;/param&gt;<br>/// &lt;param name=&quot;countryCode&quot;&gt;The country code of the country to be checked&lt;/param&gt;<br>/// &lt;param name=&quot;division&quot;&gt;The state or region to be tested&lt;/param&gt;<br>/// &lt;returns&gt;Information if it is a school day&lt;/returns&gt;<br>public bool IsSchoolDay(DateTime dateTime, string countryCode, string division)<br>{<br>    var endpoint = &quot;https://openholidaysapi.org/SchoolHolidays&quot;;<br>    endpoint = $&quot;{endpoint}?countryIsoCode={countryCode}&amp;validFrom={dateTime.Year}-{dateTime.Month}-{dateTime.Day}&quot; +<br>        $&quot;&amp;validTo={dateTime.Year}-{dateTime.Month}-{dateTime.Day}&quot;;<br><br>    var client = new RestClient(endpoint);<br>    var request = new RestRequest();<br>    request.AddHeader(&quot;Content-Type&quot;, &quot;application/json&quot;);<br>    request.AddHeader(&quot;Accept&quot;, &quot;application/json&quot;);<br>    var response = client.Execute(request);<br><br>    if (response.ResponseStatus == ResponseStatus.Completed)<br>    {<br>        return !(JsonSerializer.Deserialize&lt;IEnumerable&lt;DaysOff&gt;&gt;(response.Content)<br>            .ToList()<br>            .Any(_ =&gt; _.subdivisions.Any(s =&gt; s.shortName == division)));<br>    }<br>    else<br>        return false;<br>}</pre><h3>Namespace and Response Class</h3><p>In order to send <strong>HTTPRequests </strong>I used the restclient from RestSharp, which needs to be included as well as the JSON Deserialization library from System.</p><pre>using RestSharp;<br>using System.Text.Json;</pre><p>After the request was sent we can deserialize it to the following class:</p><pre>class Name<br>{<br>    public string language { get; set; }<br>    public string text { get; set; }<br>}<br><br>class DaysOff<br>{<br>    public string id { get; set; }<br>    public string startDate { get; set; }<br>    public string endDate { get; set; }<br>    public string type { get; set; }<br>    public List&lt;Name&gt; name { get; set; }<br>    public bool nationwide { get; set; }<br>    public List&lt;Subdivision&gt; subdivisions { get; set; }<br>    public List&lt;object&gt; comment { get; set; }<br>}<br><br>class Subdivision<br>{<br>    public string code { get; set; }<br>    public string shortName { get; set; }<br>}</pre><h4>Country, Division and Language Codes</h4><p>The belonging country and division codes can be found here:</p><p><strong>Country and Division Codes<br></strong><a href="https://service.unece.org/trade/locode/2022-2%20SubdivisionCodes.htm">https://service.unece.org/trade/locode/2022-2%20SubdivisionCodes.htm</a><br><strong>Language Codes</strong><br><a href="https://www.iso.org/iso-639-language-codes.html">https://www.iso.org/iso-639-language-codes.html</a></p><p>Now it is easy to find out if a day in a region is a vacation or a school day.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c8e698013c0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/c-sharp-programming/c-get-public-and-school-holidays-for-a-specific-region-7c8e698013c0">C# — Get public and school holidays for a specific region</a> was originally published in <a href="https://medium.com/c-sharp-programming">Any Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Effortlessly Create CRUD APIs in C#]]></title>
            <link>https://robdotnet.medium.com/effortlessly-create-crud-apis-in-c-bcc759691a91?source=rss-ebac3b5714b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/bcc759691a91</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[crud]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[repositories]]></category>
            <category><![CDATA[generics]]></category>
            <dc:creator><![CDATA[Rob]]></dc:creator>
            <pubDate>Wed, 01 Feb 2023 15:02:30 GMT</pubDate>
            <atom:updated>2023-02-08T07:42:11.987Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to create a generic CRUD API in C# - A step by step guide!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RI4P2qMdmR2N4y8I" /><figcaption>Photo by <a href="https://unsplash.com/@douglasamarelo?utm_source=medium&amp;utm_medium=referral">Douglas Lopes</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The article should help you by implementing a generic CRUD API in order to save time by providing different endpoints. It is based on .NET Core 6.</p><h3>Step 1: Setup the solution</h3><p>In order to have a loose coupled relationship between the API and their clients, we create 4 different projects. One for the UI, one for the API and a Contract and a Coreproject.</p><p>So you would have at least the following solution structure with the corresponding projects:</p><p>App.sln<br>- App.Contracts.csproj<br>- App.Core.csproj<br>- App.UI.csproj<br>- App.API.csproj</p><blockquote>In the example we are using the latest version of .NET Core.</blockquote><h3>Step 2: Create BaseEntity and Model</h3><p>After we setup the solution with their projects, we create an abstract class BaseEntity, so we have properties for each entity on which we can rely on.</p><p><strong>BaseEntity.cs</strong></p><pre>public abstract class BaseEntity<br>{<br>    public string Id { get; set; } = Guid.NewGuid().ToString();<br>    public DateTime CreatedDate { get; set; } = DateTime.Now;        <br>}</pre><p><strong>Tax.cs as Model</strong></p><pre>public class Tax : BaseEntity<br>{   <br>    public int Value { get; set; }<br>    public string Name{ get; set; } = string.Empty;<br>    public string CountryId { get; set; }<br>}</pre><h3>Step 3: Define Interfaces</h3><p>At first we’ll need to define the neccessary interfaces, on which the UI (or other clients) and the API can rely on.</p><h4>3.1 Create generic IRepository interface</h4><p>In order to have an basic idea of fetching data, we proceed by creating a genericIRepositoryinterface within our App.Contracts project.</p><pre>public interface IRepository&lt;T&gt; where T : BaseEntity<br>{<br>    Task&lt;T&gt; Add(T entity);<br>    Task&lt;T&gt; Update(T entity);<br>    void Delete(string entityId);<br>    Task&lt;IEnumerable&lt;T&gt;&gt; GetAll(GetRequest&lt;T&gt;? request);<br>    Task&lt;T&gt;? GetById(string entityId);<br>}</pre><h4>3.2 Create GetRequest</h4><p>In order to retrieve the filter, paging and sorting commands from the client, we create a GetRequest DTO in the Contracts project.</p><pre>public class GetRequest&lt;T&gt; where T : BaseEntity<br>{<br>    public Expression&lt;Func&lt;T, bool&gt;&gt;? Filter { get; set; } = null;<br>    public Func&lt;IQueryable&lt;T&gt;, IOrderedQueryable&lt;T&gt;&gt;? OrderBy { get; set; } = null;<br>    public int? Skip { get; set; } = null;<br>    public int? Take { get; set; } = null;<br>}</pre><h4>3.3 Create generic IApiController interface</h4><p>After that, we create the IApiController interface, within the same project as the IRepository interface so the API conrollers are able to follow the same structure.</p><pre>public interface IApiController&lt;T&gt; where T : BaseEntity<br>{<br>    public Task&lt;IEnumerable&lt;T&gt;&gt;? GetAll(GetRequest&lt;T&gt;? request);<br>    public Task&lt;T&gt;? Get(string id);<br>    public Task&lt;T&gt; Post(T entity);<br>    public Task&lt;T&gt;? Put(T entity);<br>    public void Delete(string id);<br>}</pre><h3>Step 4: Implement interfaces</h3><h4>4.1 Implement IRepository</h4><p>Since we created the IRepository interface, we can implement it in our Coreproject. In the examples below you can see two sample implemenations of the interface. One for SQL and one for MongoDB.</p><p><strong>Example 1: IRepository for SQL Database</strong></p><pre>public class SQLRepository&lt;T&gt; : IRepository&lt;T&gt; where T : BaseEntity<br>{<br>    //The context is added in Step 5.1<br>    private readonly MasterContext _context;<br><br>    public SQLRepository(MasterContext context)<br>    {<br>        _context = context;<br>    }<br><br>    public async Task&lt;T&gt; Add(T entity)<br>    {<br>        var addedEntity = (await _context.AddAsync(entity)).Entity;<br>        _context.SaveChanges();<br>        return addedEntity;<br>    }<br><br>    public void Delete(string entityId)<br>    {<br>        var entity = _context.Find&lt;T&gt;(entityId);<br>        if(entity != null) _context.Remove(entity);<br>        _context.SaveChanges();<br>    }<br><br>    public async Task&lt;IEnumerable&lt;T&gt;&gt; GetAll(GetRequest&lt;T&gt; request)<br>    {<br>        IQueryable&lt;T&gt; query = _context.Set&lt;T&gt;();<br><br>        if (request.Filter != null)<br>        {<br>            query = query.Where(request.Filter);<br>        }<br><br>        if (request.OrderBy != null)<br>        {<br>            query = request.OrderBy(query);<br>        }<br><br>        if (request.Skip.HasValue)<br>        {<br>            query = query.Skip(request.Skip.Value);<br>        }<br><br>        if (request.Take.HasValue)<br>        {<br>            query = query.Take(request.Take.Value);<br>        }<br><br>        return query.ToList();<br>    }<br><br>    public async Task&lt;T&gt;? GetById(string entityId)<br>    {<br>        return await _context.FindAsync&lt;T&gt;(entityId);<br>    }<br><br>    public async Task&lt;T&gt; Update(T entity)<br>    {<br>        var updatedEntity = _context.Update(entity).Entity;<br>        await _context.SaveChangesAsync();<br>        return updatedEntity;<br>    }<br>}</pre><p>The GetAll method is the main method that implements the generic filtering, sorting, and paging functionality. The method takes four optional parameters:</p><ul><li>filter: This is an expression that defines the filter criteria. The entities that match the filter criteria will be returned.</li><li>orderBy: This is a function that defines the sorting criteria. The entities will be sorted based on the sorting criteria.</li><li>skip: This is an integer that defines the number of entities to skip. This is useful for implementing paging.</li><li>take: This is an integer that defines the number of entities to take. This is also useful for implementing paging.</li></ul><p><strong>Example 2: IRepository for MongoDb</strong></p><pre>public class MongoRepository&lt;T&gt; : IRepository&lt;T&gt; where T : BaseEntity<br>{    <br>    private readonly IMongoDatabase _database;<br>    private readonly IMongoCollection&lt;T&gt; _collection;<br><br>    public MongoRepository()<br>    {<br>        var client = new MongoClient(&quot;MONGODB_CONNECTIONSTRING&quot;)<br>        _collection = _database.GetCollection&lt;T&gt;(&quot;MONGODB_COLLECTION&quot;);<br>    }<br><br>    public async Task&lt;T&gt; Add(T entity)<br>    {<br>        await _collection.InsertOneAsync(entity);<br>        return entity;<br>    }<br><br>    public void Delete(string entityId)<br>    {<br>        var filter = Builders&lt;T&gt;.Filter.Eq(s =&gt; s.Id, entityId);<br>        _collection.DeleteOne(filter);<br>    }<br><br>    public async Task&lt;IEnumerable&lt;T&gt;&gt; GetAll(GetRequest&lt;T&gt;? request)<br>    {<br>        var query = (await _collection.FindAsync(request.Filter))<br>            .ToList()<br>            .AsQueryable();<br><br>        if(request != null)<br>        {<br>            if (request.OrderBy != null)<br>            {<br>                query = request.OrderBy(query);<br>            }<br><br>            if (request.Skip.HasValue)<br>            {<br>                query = query.Skip(request.Skip.Value);<br>            }<br><br>            if (request.Take.HasValue)<br>            {<br>                query = query.Take(request.Take.Value);<br>            }<br>        }<br><br>        return query;<br>    }<br><br>    public async Task&lt;T&gt;? GetById(string entityId)<br>    {<br>        var filter = Builders&lt;T&gt;.Filter.Eq(s =&gt; s.Id, entityId);<br>        return (await _collection.FindAsync(filter))<br>             .SingleOrDefault();<br>    }<br><br>    public async Task&lt;T&gt; Update(T entity)<br>    {<br>        var filter = Builders&lt;T&gt;.Filter.Eq(s =&gt; s.Id, entity.Id);            <br>        var result = await _collection.ReplaceOneAsync(filter, entity);<br>        return entity;<br>    }<br>}</pre><h4>4.2 Implement IAPIController</h4><p>Within our API project which has a dependency on the Coreand the Contractproject, we implement the IApiController, we’ve created earlier.</p><pre>public class CrudBaseController&lt;T&gt; : ControllerBase, IApiController&lt;T&gt;<br>    where T : BaseEntity<br>{<br>    private readonly IRepository&lt;T&gt; _repository;<br><br>    public CrudBaseController(IRepository&lt;T&gt; repository)<br>    {<br>        _repository = repository;<br>    }<br><br>    [HttpPost(&quot;GetAll&quot;)]<br>    public async Task&lt;IEnumerable&lt;T&gt;&gt;? GetAll([FromBody] GetRequest&lt;T&gt;? request = null)<br>    {<br>        return await _repository.GetAll(request);<br>    }<br><br>    [HttpGet(&quot;{id}&quot;)]<br>    public async Task&lt;T&gt;? Get(Guid id)<br>    {<br>        return await _repository.GetById(id);<br>    }<br><br>    [HttpPost]<br>    public async Task&lt;T&gt; Post(T entity)<br>    {<br>        return await _repository.Add(entity);<br>    }<br><br>    [HttpPut]<br>    public async Task&lt;T&gt;? Put(T entity)<br>    {<br>        return await _repository.Update(entity);<br>    }<br><br>    [HttpDelete(&quot;{id}&quot;)]<br>    public void Delete(Guid id)<br>    {<br>        _repository.Delete(id);<br>    }<br>}</pre><h3>Step 5: Register Services and add DbContext</h3><p>In this scenario i am going to use MySQL Datbase and register the Repository and the DBContext in the Program.csProgram.cs file of the API project.</p><h4>5.1 Add DbContext</h4><p>Add the DbContext for the SQL Repository, in order to connect to it.</p><pre>public class MasterContext : DbContext<br>{<br>  public DbSet&lt;Tax&gt; Taxes { get; set; }<br><br>  protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)<br>  {<br>      optionsBuilder.UseMySql(&quot;YOUR_CONNECTION&quot;,<br>          new MySqlServerVersion(new Version(4, 9, 7)), options =&gt; options.EnableRetryOnFailure())<br>          .LogTo(Console.WriteLine, LogLevel.Information)<br>          .EnableSensitiveDataLogging()<br>          .EnableDetailedErrors();<br>  }<br><br>  protected override void OnModelCreating(ModelBuilder modelBuilder)<br>  {<br>      base.OnModelCreating(modelBuilder);<br><br>      modelBuilder.Entity&lt;Tax&gt;(entity =&gt;<br>      {<br>          entity.HasKey(e =&gt; e.Id);<br>          entity.Property(e =&gt; e.Value);<br>          entity.Property(e =&gt; e.Name);<br>          entity.Property(e =&gt; e.CountryId);<br>      });<br>  }<br>}</pre><h4>5.2 Register Services</h4><pre>services.AddDbContext&lt;MasterContext&gt;();<br>services.AddScoped&lt;IRepository&lt;Tax&gt;, SQLRepository&lt;Tax&gt;&gt;();</pre><h3>Step 6: Use CrudBaseController</h3><p>Now, you can easily use the CrudBaseController in order to provide CRUD actions foreach entity to clients.</p><pre>[Route(&quot;api/[controller]&quot;)]<br>[ApiController]<br>public class TaxesController : CrudBaseController&lt;Tax&gt;<br>{<br>    public TaxesController(IRepository&lt;Tax&gt; repository) : base(repository)<br>    {<br>    }<br>}</pre><h3>Step 7: Call the API with Blazor</h3><p>There are many client applications out there to test the API. In this article we are using Blazor and HTTPClient. So just open the UI project and add the APIController class below for requesting the API.</p><pre>public class APIController&lt;T&gt; : IApiController&lt;T&gt; where T : BaseEntity<br>{<br>    private readonly HttpClient _httpClient;<br>    private readonly string _endpoint;<br><br>    public APIController(HttpClient httpClient, string endpoint)<br>    {<br>        _httpClient = httpClient;<br>        _endpoint = endpoint;<br>    }<br><br>    public async void Delete(string id)<br>    {<br>       await _httpClient.DeleteAsync($&quot;{_endpoint}/{id}&quot;);<br>    }<br><br>    public async Task&lt;IEnumerable&lt;T&gt;&gt;? GetAll(GetRequest&lt;T&gt;? request = null)<br>    {<br>        var dataJson = request != null ?<br>            new StringContent(JsonSerializer.Serialize(request), Encoding.UTF8, &quot;application/json&quot;) :<br>            new StringContent(JsonSerializer.Serialize(new GetRequest&lt;T&gt;()), Encoding.UTF8, &quot;application/json&quot;);<br><br>        var response = await _apiService._httpClient.PostAsync($&quot;{_endpoint}/GetAll&quot;, dataJson);<br><br>        return JsonSerializer.Deserialize&lt;IEnumerable&lt;T&gt;&gt;(await response.Content.ReadAsStringAsync(),<br>            new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });<br>    }<br><br>    public async Task&lt;T&gt;? Get(string id)<br>    {<br>        return await JsonSerializer.DeserializeAsync&lt;T&gt;<br>            (await _httpClient.GetStreamAsync($&quot;{_endpoint}/{id}&quot;), <br>                new JsonSerializerOptions() { PropertyNameCaseInsensitive = true });<br>    }<br><br>    public async Task&lt;T&gt; Post(T entity)<br>    {<br>        var dataJson =<br>          new StringContent(JsonSerializer.Serialize(entity), Encoding.UTF8, &quot;application/json&quot;);<br><br>        var response = await _httpClient.PostAsync(_endpoint, dataJson);<br>        if (response.IsSuccessStatusCode)<br>            return await JsonSerializer.DeserializeAsync&lt;T&gt;(await response.Content.ReadAsStreamAsync());<br>        else<br>            return null;<br>    }<br><br>    public async Task&lt;T&gt;? Put(T entity)<br>    {<br>        var countryJson =<br>           new StringContent(JsonSerializer.Serialize(entity), Encoding.UTF8, &quot;application/json&quot;);<br><br>        var response = await _httpClient.PutAsync(_endpoint, countryJson);<br><br>        if (response.IsSuccessStatusCode)<br>            return await JsonSerializer.DeserializeAsync&lt;T&gt;(await response.Content.ReadAsStreamAsync());<br>        else<br>            return null;<br>    }</pre><p>After that we just need to register the service and the enpoint in Program.cs and use it in our blazor component.</p><pre>builder.Services.AddHttpClient&lt;APIService&gt;(client =&gt;<br>{<br>    client.BaseAddress = new Uri(&quot;https://localhost:1245/api/&quot;);    <br>});<br><br>builder.Services.AddScoped&lt;APIController&lt;Tax&gt;, TaxDataService&gt;();</pre><pre>public partial class TaxOverview<br>{    <br>    [Inject]<br>    APIController&lt;Tax&gt; DataService { get; set; }<br>  <br>    public IEnumerable&lt;Tax&gt; Taxes { get; set; }    <br>  <br>    protected override async Task OnInitializedAsync()<br>    {<br>        Taxes = (await DataService.Get()).ToList();<br><br>        // Filter with Expression<br>        var taxRequest = new GetRequest&lt;Tax&gt;<br>        {<br>            Filter = (_) =&gt; _.Country.Id == country.CountryId,<br>        };<br>        var TaxesForCountry= (await TaxDataService.Get(taxRequest)).ToList();<br>    }<br>}</pre><h3>Conclusion</h3><p>Creating a generic C# API is a great way to save time and reduce the risk of errors when developing software applications. By following the steps outlined in this article, you can create a generic API that can be used for multiple data types, making it easier for developers to use in their projects.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bcc759691a91" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DevOps: Productivity Boost with Azure Devops Templates (DevOps 2019)]]></title>
            <link>https://robdotnet.medium.com/devops-productivity-boost-with-azure-devops-templates-devops-2019-836a961e6aab?source=rss-ebac3b5714b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/836a961e6aab</guid>
            <category><![CDATA[azure-devops]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Rob]]></dc:creator>
            <pubDate>Fri, 27 Jan 2023 07:57:54 GMT</pubDate>
            <atom:updated>2023-01-27T07:57:54.715Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*njuLLdYqRa074WslBE5VQA.png" /></figure><p>With CI/CD templates in Azure DevOps, recurring build and release tasks can be created and reused once so that a pipeline doesn’t have to be created and maintained over and over again. This has the advantage that the code is changed in a central location and thus the effort is significantly reduced with increasing pipelines and projects.</p><h3>To whom the article is addressed</h3><p>The article is addressed to every developer, IT project manager and infrastructure manager who uses DevOps 2019 and has multiple source code management repositories (GIT, TFS) and projects with the same SDK (.NET 4.8, .NET 6, Angular 11) and would like to significantly reduce the effort required to create new pipelines.</p><blockquote>I cannot recommend to use these templates for newer versions of DevOps.</blockquote><h3>About Azure Devops CI/CD</h3><p>Azure DevOps is a cloud solution from Mircrosoft that is used by development teams to achieve the following requirements:</p><p>1. Managing source code in an audit-proof manner so that code is not lost and can be recovered.<br>2. Build and test source code to ensure code quality.<br>3. Delivering applications to customers and distributing development resources to developers in the form of NUGET packages.</p><h3>How to Setup the DevOps template</h3><p>To create a template yourself, the following steps must be performed:<br>1. Create a repository for the templates (here: TemplateRepo)<br>2. Add a YAML file to the repository (template.yml)<br>(3). Copy one of the following examples for the template. They are based on .NET 6 and .NET 4.8. If you are using an other target you will need to define different task and build them for your own purposes.</p><h4><strong>Template .NET 6</strong></h4><pre>parameters:<br>  buildConfiguration: &#39;Release&#39;<br>  runtime: &#39;win-x64&#39;<br>  createNugetPackage: false<br>  pool: &#39;DEV&#39;<br>  testProjects: &#39;**/Tests/*.csproj&#39;<br>  projects: &#39;**\*.csproj;!**\*.Tests.csproj;!**\*.Test.csproj&#39;<br>  solution: &#39;**/.sln&#39;  <br>  testFilterCriteria: &#39;TestCategory!=Manual&#39;<br>  selfContained: true<br><br>jobs:<br>- job: Build<br>  pool: ${{ parameters.pool }}<br>  steps:<br>  <br>  # Validate Parameters<br>  - task: PowerShell@2<br>    displayName: &#39;Validate Parameter&#39;<br>    inputs:<br>      targetType: &#39;inline&#39;<br>      script: |<br>        $buildConfiguration = &#39;${{ parameters.buildConfiguration }}&#39;<br>        if(($buildConfiguration -eq &#39;&#39;)<br>        { <br>          echo &#39;##vso[task.logissue type=error;]Missing parameter buildConfiguration&#39;<br>        }<br>  <br>  # Install SDK<br>  - task: UseDotNet@2<br>     displayName: &#39;Install SDK&#39;<br>     condition: &#39;succeeded()&#39;<br>     inputs:<br>       packageType: &#39;sdk&#39;<br>       version: &#39;6.x&#39;<br>  <br>  # Build Application<br>  - task: DotNetCoreCLI@2<br>    displayName: &#39;Build Application&#39;<br>    condition: &#39;succeeded()&#39;<br>    inputs:<br>      command: build<br>      projects: ${{ parameters.solution }}<br>      arguments: &#39;--configuration ${{ parameters.buildConfiguration }}&#39;<br><br>  # Test Application<br>  - task: DotNetCoreCLI@2<br>    displayName: &#39;Test Application&#39;<br>    condition: &#39;succeeded()&#39;<br>    inputs:<br>      command: test<br>      projects: ${{ parameters.testprojects }}<br>      arguments: &#39;--configuration ${{ parameters.buildConfiguration }} --filter ${{ parameters.testFilterCriteria }} --collect &quot;Code coverage&quot;&#39;<br>  <br>  # Prepare publish artifacts<br>  - task: DotNetCoreCLI@2<br>    displayName: &#39;Prepare publish artifacts&#39;<br>    condition: &#39;succeeded()&#39;<br>    inputs:<br>      command: publish<br>      publishWebProjects: false #Note: Change, if required<br>      zipAfterPublish: false #Note: Change, if required<br>      projects: {{ parameters.projects }}<br>      arguments: &#39;--configuration ${{ parameters.buildConfiguration }} --output ${{ Build.ArtifactStagingDirectory }}\Binaries --runtime ${{ parameters.runtime }} --self contained ${{ parameters.selfContained }}&#39;<br>      <br>  # Provide Parameter for Release Pipeline<br>  - task: PowerShell@2<br>    displayName: &#39;Provide parameter for release pipeline&#39;<br>    condition: &#39;succeeded()&#39;<br>    inputs:<br>      targetType: inline<br>      script: |<br>        $variable = @{ Values = @{<br>          PublishNuget = &#39;${{ parameters.createNugetPackage }}&#39;<br>        }} $variable | ConvertTo-Json | Out-File $(Build.ArtifactStagingDirectory\parameters.txt <br>        Get-Content $(Build.ArtifactStagingDirectory)\parameters.txt <br><br>  # Package Nuget<br>  - task: PowerShell@2<br>    displayName: &#39;Create Nuget Package&#39;<br>    condition: &#39;and(succeeded(), eq( ${{ parameters.createNugetPackage }}, true))&#39;<br>    inputs:<br>      command: pack<br>      packagesToPack: ${{ parameters.projects }}<br>  <br>  # Publish Artifacts<br>  - task: PublishBuildArtifacts@1<br>    displayName: &#39;Publish Artifacts&#39;<br>    condition: &#39;succeeded()&#39;<br>    inputs:<br>      pathToPublish: $(Build.ArtifactStagingDirectory)<br>      artifactName: drop<br><br>  # Delete all files of build directory<br>  - task: DeleteFiles@1<br>    displayName: &#39;Delete Binaries&#39;<br>    condition: &#39;succeeded()&#39;<br>    inputs:<br>      SourceFolder: &#39;$(Build.BinariesDirectory)&#39;<br>      Contents: &#39;**/*&#39;<br><br>  # Delete all files of source directory<br>  - task: DeleteFiles@1<br>    displayName: &#39;Delete Sources&#39;<br>    condition: &#39;succeeded()&#39;<br>    inputs:<br>      SourceFolder: &#39;$(Build.SourcesDirectory)&#39;<br>      Contents: |<br>        **/* <br>        .gitignore<br><br></pre><h4>Template .NET 4.8</h4><pre>parameters:<br>  buildConfiguration: &#39;Release&#39;<br>  buildPlatform: &#39;any cpu&#39;<br>  runtime: &#39;win-x64&#39;<br>  createNugetPackage: false<br>  pool: &#39;DEV&#39;<br>  testProjects: &#39;**/Tests/*.csproj&#39;<br>  projects: &#39;**\*.csproj;!**\*.Tests.csproj;!**\*.Test.csproj&#39;  <br>  solution: &#39;**/.sln&#39;<br>  testFilterCriteria: &#39;TestCategory!=Manual&#39;  <br><br>jobs:<br>- job: Build<br>  pool: ${{ parameters.pool }}<br>  steps:<br> <br>  # Validate Parameters <br>  - task: PowerShell@2<br>    displayName: &#39;Validate Parameter&#39;<br>    inputs:<br>      targetType: &#39;inline&#39;<br>      script: |<br>        $buildConfiguration = &#39;${{ parameters.buildConfiguration }}&#39;<br>        if(($buildConfiguration -eq &#39;&#39;)<br>        { <br>          echo &#39;##vso[task.logissue type=error;]Missing parameter buildConfiguration&#39;<br>        }<br>  <br>  # Install SDK<br>  - task: UseDotNet@2<br>     displayName: &#39;Install SDK&#39;<br>     condition: &#39;succeeded()&#39;<br>     inputs:<br>       packageType: &#39;sdk&#39;<br>       version: &#39;5.x&#39;<br><br>  # Restore NuGet<br>  - task: NuGetCommand@2<br>     displayName: &#39;Restore NuGet&#39;<br>     condition: &#39;succeeded()&#39;<br>     inputs:<br>       command: restore<br>       restoreSolution: &#39;{{ parameters.solution }}&#39;<br>       feedsToUse: &#39;select&#39;<br>       vstsFeed: &#39;/34234234-23d3-...&#39; #TODO: Set your NuGet feed here<br>       includeNugetOrg: true<br>       noCache: true<br><br>  # Build Application<br>  - task: MSBuild@1<br>    displayName: &#39;Build Application&#39;<br>    condition: &#39;succeeded()&#39;<br>    inputs:<br>      solution: &#39;{{ parameters.solution }}&#39;<br>      configuration: &#39;${{ parameters.buildConfiguration }}&#39;<br>      clean: true<br>      msbuildArguments: &#39;--output=$(Build.BinariesDirectory)&#39;<br><br>  # Test Application<br>  - task: VSTest@2<br>    displayName: &#39;Test Application&#39;<br>    condition: &#39;succeeded()&#39;<br>    inputs:<br>      testSelector: &#39;testAssemblies&#39; #NOTE: Check the filter criteria<br>      testAssemblyVer2: |<br>        **\*test*.dll<br>        **\*Test.dll<br>        !**\*TestAdapter.dll<br>        !**\obj\**<br>      searchFolder: &#39;$(System.DefaultWorkingDirectory)&#39;<br>      testFiltercriteria: &#39;${{ parameters.testFilterCriteria }}&#39;<br>      codeCoverageEnabled: true #NOTE: change if you don&#39;t want to use code coverage<br>      testRunTitle: &#39;Tests&#39;<br>      platform: &#39;${{ parameters.buildPlatform }}&#39;<br>      configuration: &#39;${{ parameters.buildConfiguration }}&#39;<br><br>  # Prepare publish artifacts<br>  - task: VSTest@2<br>    displayName: &#39;Prepare publish artifacts&#39;<br>    condition: &#39;succeeded()&#39;<br>    inputs:<br>      SourceFolder: &#39;$(Build.BinariesDirectory)&#39; #NOTE: A filter on .xml files is included for excluding debug informations<br>      Contents: |<br>        **<br>        !*.xml<br>        !*.pdb<br>        !*Test*<br>      TargetFolder: &#39;$Build.ArtifactStagingDirectory)\Binaries&#39;<br>      <br>  # Provide Parameter for Release Pipeline<br>  - task: PowerShell@2<br>    displayName: &#39;Provide parameter for release pipeline&#39;<br>    condition: &#39;succeeded()&#39;<br>    inputs:<br>      targetType: inline<br>      script: |<br>        $variable = @{ Values = @{<br>          PublishNuget = &#39;${{ parameters.createNugetPackage }}&#39;<br>        }} $variable | ConvertTo-Json | Out-File $(Build.ArtifactStagingDirectory\parameters.txt <br>        Get-Content $(Build.ArtifactStagingDirectory)\parameters.txt <br><br>  # Package Nuget<br>  - task: NuGetCommand@2<br>    displayName: &#39;Create Nuget Package&#39;<br>    condition: &#39;and(succeeded(), eq( ${{ parameters.createNugetPackage }}, true))&#39;<br>    inputs:<br>      command: pack<br>      versionScheme: &#39;off&#39;<br>      includeReferenceProjects: true      <br>      packagesToPack: ${{ parameters.projects }}<br>      configuartion: ${{ parameters.buildConfiguration }}<br>  <br>  # Publish Artifacts<br>  - task: PublishBuildArtifacts@1<br>    displayName: &#39;Publish Artifacts&#39;<br>    condition: &#39;succeeded()&#39;<br>    inputs:<br>      pathToPublish: $(Build.ArtifactStagingDirectory)<br>      artifactName: drop<br><br>  # Delete all files of build directory<br>  - task: DeleteFiles@1<br>    displayName: &#39;Delete Binaries&#39;<br>    condition: &#39;succeeded()&#39;<br>    inputs:<br>      SourceFolder: &#39;$(Build.BinariesDirectory)&#39;<br>      Contents: &#39;**/*&#39;<br><br>  # Delete all files of source directory<br>  - task: DeleteFiles@1<br>    displayName: &#39;Delete Sources&#39;<br>    condition: &#39;succeeded()&#39;<br>    inputs:<br>      SourceFolder: &#39;$(Build.SourcesDirectory)&#39;<br>      Contents: |<br>        **/* <br>        .gitignore</pre><p>4. Set the pipeline as a template<br>Menu: Pipeline / Builds / 3 Dots Button / Set as template</p><h3>How to use the Azure Devops Template</h3><p>The templates are now located within a specific branch (dev, master, …) under which the .yml file was created in the repository. This must be taken into account when executing the pipeline afterwards, as execution under a different branch will not work if the .yml file was not created there.</p><p>To use a template for a project, the following steps must be performed:</p><ol><li>Create a .yml file in the repository of the project where you want to use the template.</li><li>Copy the following content into the newly created .yml file</li></ol><pre>trigger:<br>- master<br>- dev<br><br>resources:<br> repositories:<br>  - repository: templates<br>    type: git<br>    name: ProjetCollection/TemplateRepo<br>jobs:<br> - template: net60.yml@templates<br>   parameters:<br>    createNugetPackage: true<br>    pool: &#39;MyAgentPool&#39;</pre><h4>Parameter Description</h4><p><strong>Each parameter has a default value, so the template could work without setting the parameters if the agent pool name equals DEV. If the name of your pool differs, you need at least set the name of the agent pool.</strong></p><p><strong>buildConfiguration </strong><br>- Descr.: The build configuration of the application<br>- Values: Release, Debug</p><p><strong>runtime</strong>:<br>- Descr.: The runtime of the application<br>- Values: any cpu, x64, Win32, x86</p><p><strong>createNugetPackage</strong>:<br>- Descr.: Should the pipeline create a new NuGet package <br>- Values: true, false</p><p><strong>pool</strong>:<br>- Descr.: Set your particular application pool. You can find you pool in the project settings menu, agent pools<br>- Values: Default, …, …</p><p><strong>testProjects</strong>:<br>- Descr.: The projects which should be tested. <br>- Values: AppTests.csproj, …, …</p><p><strong>projects</strong>:<br>- Descr.: The projects which binaries should be deployed. <br>- Values: App.csproj, …, …</p><p><strong>solution</strong>:<br>- Descr.: The solution to build. <br>- Values: App.csproj, …, …</p><p><strong>testFilterCriteria</strong>:<br>- Descr.: Set FilterCriteria for your tests so that some tests would be skipped by the pipeline<br>- Values: TestCategory != Manual, …</p><p><strong>selfContained (.NET 6)</strong>:<br>- Descr.: Should the application deployed as selfContained, so the application can run on it’s own without configuring the host in advance<br>- Values: true, false</p><h3>Release Pipeline — Parameter from Build Pipeline</h3><p>In DevOps 2019, there are release pipelines that can be used to deploy artifacts.<br>To use the artifacts of the build pipeline, we need to reference the artifacts and read the file with the parameters.</p><pre>- powershell : |<br>  $parameters = Get-Content -Path $(System.ArtifactsDirectory)\**\**parameters.txt -Raw | ConvertFrom-Json <br>  $publishNuget = $parameters.Values.PublishNuget <br>  Write-Host &quot;##vso[task.setvariable variable=PublishNuget]$publishNuget<br></pre><p>After that we can use the parameter from the build pipeline like an ordinary release variable: $(PublishNuget)</p><h3>Additional Notes</h3><p>Some parts of the template may vary from your requirements and environment, so it will be neccessary to change them. They are marked with <strong>TODO and NOTE.</strong></p><p>Feel free to ask! There are many parts not covered here in the article, cause you can do a lot of stuff with Azure DevOps. Hence, don’t hesitate to comment or contact me via LinkedIn for further support.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=836a961e6aab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Cloudflare API with C#]]></title>
            <link>https://robdotnet.medium.com/using-cloudflare-api-with-c-ed690512ef1a?source=rss-ebac3b5714b5------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed690512ef1a</guid>
            <category><![CDATA[cloudflare]]></category>
            <category><![CDATA[cloudflare-api]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[cdn]]></category>
            <category><![CDATA[image-upload]]></category>
            <dc:creator><![CDATA[Rob]]></dc:creator>
            <pubDate>Sun, 22 Jan 2023 23:32:26 GMT</pubDate>
            <atom:updated>2023-01-24T08:12:30.967Z</atom:updated>
            <content:encoded><![CDATA[<p>The article explains how you can use the Cloudflare API in C# in order to upload, get and delete images.</p><p>For this you will need your particular <strong>endpoint </strong>and <strong>token </strong>of Cloudflare.</p><p>Cloudflare helps your application to improve performance in the content delivery process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZcuUGCZ4-yyHhU51kyo2oA.jpeg" /></figure><h3>UPLOAD Images</h3><p><strong>Parameter</strong></p><p>IFormFile file: Is the Image you wanna upload — I know, file is not the best naming convention, cause it is an image. You can receive the image as a form request including the form in the body of the request.</p><p>Bool isPrivate: Defines if the image should visible to the public. If yes, it will be signed.</p><p><strong>Return Values</strong></p><p>String Url: The url where the image is accessible. If the image is private and signed, you will not get the image unless you use the method GetSignedUrl.</p><p>String Id: The Id of the image, which we’ll need to delete the image.</p><pre>public static async Task&lt;(string url, string id)&gt; UploadImage(IFormFile file, bool isPrivate = false)<br>{<br>    var endpoint = Environment.GetEnvironmentVariable(EnvironmentVariableKeys.CLOUDFLARE_ENDPOINT);<br>    var token = Environment.GetEnvironmentVariable(EnvironmentVariableKeys.CLOUDFLARE_TOKEN);<br><br>    var client = new RestClient(endpoint);<br>    client.Timeout = -1;<br>    var request = new RestRequest(Method.POST);<br>    request.AddHeader(&quot;Authorization&quot;, $&quot;Bearer {token}&quot;);<br><br>    using (var ms = new MemoryStream())<br>    {<br>        file.CopyTo(ms);<br>        var fileBytes = ms.ToArray();<br>        request.AddFileBytes(&quot;file&quot;, fileBytes, file.FileName, file.ContentType);<br>    }<br>    <br>    if(isPrivate)<br>        request.AddParameter(&quot;requireSignedURLs&quot;, &quot;true&quot;);<br><br>    IRestResponse response = await client.ExecutePostTaskAsync(request);<br><br>    var cloudflareResponse = JsonConvert.DeserializeObject&lt;CloudflareResponse&gt;(response.Content);<br><br>    if (cloudflareResponse.success)<br>        return (cloudflareResponse.result.variants[0], cloudflareResponse.result.id);<br><br>    else return (string.Empty, string.Empty);<br>}</pre><h3>GET Images</h3><p>Cloudflare delivers 100 images one time by default. So you’ll need paging in order to receive more than 100 images.</p><pre>public async static Task&lt;CloudflareGetResponse&gt; GetAllImages(int page)<br>{<br>    var endpoint = Environment.GetEnvironmentVariable(EnvironmentVariableKeys.CLOUDFLARE_ENDPOINT);<br>    var token = Environment.GetEnvironmentVariable(EnvironmentVariableKeys.CLOUDFLARE_TOKEN);<br><br>    endpoint = $&quot;{endpoint}?page={page}&amp;per_page=100&quot;;<br><br>    var client = new RestClient(endpoint);<br>    client.Timeout = -1;<br>    var request = new RestRequest(Method.GET);<br>    request.AddHeader(&quot;Authorization&quot;, $&quot;Bearer {token}&quot;);<br><br>    IRestResponse response = await client.ExecuteGetTaskAsync(request);<br><br>    var cloudflareResponse = JsonConvert.DeserializeObject&lt;CloudflareGetResponse&gt;(response.Content);<br><br>    if (cloudflareResponse.success)<br>        return cloudflareResponse;<br><br>    else return new CloudflareGetResponse();<br>}<br><br>public class Result<br>{<br>    public List&lt;ResultItem&gt; images { get; set; }<br>}<br><br>public class CloudflareGetResponse<br>{<br>    public Result result { get; set; }<br>    public bool success { get; set; }<br>    public List&lt;object&gt; errors { get; set; }<br>    public List&lt;object&gt; messages { get; set; }<br>}<br><br>public class ResultItem<br>{<br>    public string id { get; set; }<br>    public string filename { get; set; }<br>    public DateTime uploaded { get; set; }<br>    public bool requireSignedURLs { get; set; }<br>    public List&lt;string&gt; variants { get; set; }<br>}<br><br>public class CloudflareResponse<br>{<br>    public ResultItem result { get; set; }<br>    public bool success { get; set; }<br>    public List&lt;object&gt; errors { get; set; }<br>    public List&lt;object&gt; messages { get; set; }<br>}</pre><h3>DELETE Images</h3><p>In order to delete one image in Cloudflare we’ll need to provide the id of the corresponding image in Cloudflare, we received during the upload. So it’s helpful to <strong>save the Id of the image in the database</strong> after uploading it.</p><pre>public static async Task&lt;bool&gt; DeleteImage(string imageId)<br>{<br>    try<br>    {<br>        if (string.IsNullOrEmpty(imageId))<br>            return false;<br><br>        var endpoint = Environment.GetEnvironmentVariable(EnvironmentVariableKeys.CLOUDFLARE_ENDPOINT) + &quot;/&quot; + imageId;<br>        var token = Environment.GetEnvironmentVariable(EnvironmentVariableKeys.CLOUDFLARE_TOKEN);<br><br>        var client = new RestClient(endpoint);<br>        client.Timeout = -1;<br>        var request = new RestRequest(Method.DELETE);<br>        request.AddHeader(&quot;Authorization&quot;, $&quot;Bearer {token}&quot;);<br><br>        IRestResponse response = await client.ExecuteTaskAsync(request);<br><br>        var cloudflareResponse = JsonConvert.DeserializeObject&lt;CloudflareResponse&gt;(response.Content);<br><br>        if (cloudflareResponse != null &amp;&amp; cloudflareResponse.success)<br>            return true;<br><br>        else return false;<br>    }<br>    catch(Exception ex)<br>    {<br>        Log.Error(ex.Message);<br>        return false;<br>    }<br>    <br>}</pre><h3><strong>GET Signed Url</strong></h3><p>In order to access signed urls you need to encode the url. The url provided here to GetSignedUrl is not public accessible, so it will be encoded here.<br>This is one way how you can achieve this. In this case you will need to create a Cloudflare API Key.</p><pre>public static string GetSignedUrl(string url)<br>{<br>  return GenerateSignedUrl(url);<br>}<br><br>        <br>private static string GenerateSignedUrl(string url)<br>{<br>    var key = Environment.GetEnvironmentVariable(EnvironmentVariableKeys.CLOUDFLARE_APIKEY);            <br>    var exp = Convert.ToInt64((DateTime.Now.AddDays(1) - new DateTime(1970, 1, 1, 0, 0, 0)).TotalMilliseconds);<br><br>    url = $&quot;{url}?exp={exp}&quot;;<br><br>    var signurl = new Uri(url).PathAndQuery;<br>    var sig = CalcHmac(signurl, key);<br><br>    url = $&quot;{url}&amp;sig={sig}&quot;;<br><br>    return url;<br>}<br><br>private static string CalcHmac(string data, string token)<br>{<br>    byte[] key = Encoding.ASCII.GetBytes(token);<br>    HMACSHA256 myhmacsha256 = new HMACSHA256(key);<br>    byte[] byteArray = Encoding.ASCII.GetBytes(data);<br>    MemoryStream stream = new MemoryStream(byteArray);<br>    string result = myhmacsha256.ComputeHash(stream).Aggregate(&quot;&quot;, (s, e) =&gt; s + String.Format(&quot;{0:x2}&quot;, e), s =&gt; s);<br>    return result;<br>}</pre><h3>Last words</h3><p>I know, there are always things to improve, so I would be happy to get feedback from you, in order to improve the documentation afterwards.<br>Feel free to ask and comment the article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed690512ef1a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>