<?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 Atakan Korez on Medium]]></title>
        <description><![CDATA[Stories by Atakan Korez on Medium]]></description>
        <link>https://medium.com/@atakankorez?source=rss-5368f4ac89d2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*TjcpsEsv26RtgXsxa5Fuhw.jpeg</url>
            <title>Stories by Atakan Korez on Medium</title>
            <link>https://medium.com/@atakankorez?source=rss-5368f4ac89d2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 12:26:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@atakankorez/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[What is Implicit Inner Join and Why be careful about it?]]></title>
            <link>https://medium.com/@atakankorez/what-is-implicit-inner-join-and-why-be-careful-about-it-be273d964090?source=rss-5368f4ac89d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/be273d964090</guid>
            <category><![CDATA[sql-tips]]></category>
            <category><![CDATA[innerjoin]]></category>
            <category><![CDATA[sql-best-practices]]></category>
            <category><![CDATA[sql-queries]]></category>
            <category><![CDATA[leftjoin]]></category>
            <dc:creator><![CDATA[Atakan Korez]]></dc:creator>
            <pubDate>Wed, 14 Feb 2024 22:42:59 GMT</pubDate>
            <atom:updated>2024-02-14T22:42:59.491Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*wT01k_ItzouUJSjzfzOc0g.jpeg" /></figure><p>In relational databases, SQL (Structured Query Language) plays a pivotal role in managing and retrieving data. One of the fundamental concepts in SQL is joining tables to combine data from multiple sources. While there are various types of joins, this blog will delve into the often-misunderstood <em>“implicit inner join”</em> and explore its usage with concrete examples.</p><h4>Understanding Implicit Inner Joins</h4><p>An implicit inner join is a simple and concise way to combine data from two or more tables based on a specified condition. Unlike explicit joins, which use the JOIN keyword, implicit inner joins leverage the WHERE clause to define the join condition. Let&#39;s dive into some examples to illustrate this concept.</p><pre>-- USERS TABLE --<br>    | USER_ID | FIRST_NAME |  LAST_NAME |<br>    |---------|------------|------------|<br>    |     123 |       Fred | Flintstone |<br>    |     456 |     Barney |     Rubble |<br><br><br>-- DEPARTMENTS TABLE --<br>    |    ID | USER_ID |       DEP_NAME  |<br>    |-------|---------|-----------------|<br>    | 98765 |     123 |           Mine  |</pre><p>So as you would expect, an INNER JOIN produces just one row where the User_ID values match in both tables.</p><pre>SELECT * FROM Users u <br>INNER JOIN Departments d ON u.User_ID = d.User_ID<br><br>    | USER_ID | FIRST_NAME |  LAST_NAME |    ID |       DEP_NAME  |<br>    |---------|------------|------------|-------|-----------------|<br>    |     123 |       Fred | Flintstone | 98765 |            Mine |</pre><p>And by changing to LEFT JOIN we get all records in Departments but not all have information from Dep_Name, so we get NULLs in those columns.</p><pre>SELECT * FROM Users u <br>LEFT JOIN Departments d ON u.User_ID = d.User_ID<br><br><br>    | USER_ID | FIRST_NAME |  LAST_NAME |     ID |       DEP_NAME  |<br>    |---------|------------|------------|--------|-----------------|<br>    |     123 |       Fred | Flintstone |  98765 |            Mine |<br>    |     456 |     Barney |     Rubble | (null) |          (null) |</pre><p>But what happens if we only want <strong>SOME</strong> records from the joined table?</p><pre>SELECT * FROM Users u <br>LEFT JOIN Departments d ON u.User_ID = d.User_ID<br>WHERE d.Dep_Name = &#39;Mine&#39; <br><br><br>    | USER_ID | FIRST_NAME |  LAST_NAME |    ID |       DEP_NAME  |<br>    |---------|------------|------------|-------|-----------------|<br>    |     123 |       Fred | Flintstone | 98765 |            Mine |</pre><p>Well if we use a WHERE condition, the effect is the same as an INNER JOIN, now we don’t get all User records and this is an I<strong>mplicit Inner Join</strong>.</p><p>We don’t get all user records because we have now insisted that all result rows <strong>MUST</strong> have a certain value in a column that might be NULL. So, we could alter the WHERE condition to permit NULLs.</p><pre>SELECT * FROM Users u <br>LEFT JOIN Departments d ON u.User_ID = d.User_ID<br>WHERE d.Dep_Name = &#39;Mine&#39; OR d.Dep_Name IS NULL<br><br>    | USER_ID | FIRST_NAME |  LAST_NAME |     ID |       DEP_NAME  |<br>    |---------|------------|------------|--------|-----------------|<br>    |     123 |       Fred | Flintstone |  98765 |            Mine |<br>    |     456 |     Barney |     Rubble | (null) |          (null) |</pre><p><strong>OR</strong>; Instead of using the WHERE clause on the joined table we add to the join conditions (i.e.after ON ) — <em>I recommend this version</em></p><pre>SELECT * FROM Users u <br>LEFT JOIN Departments d ON u.User_ID = d.User_ID AND d.Dep_Name = &#39;Mine&#39;<br><br><br>    | USER_ID | FIRST_NAME |  LAST_NAME |     ID |       DEP_NAME  |<br>    |---------|------------|------------|--------|-----------------|<br>    |     123 |       Fred | Flintstone |  98765 |            Mine |<br>    |     456 |     Barney |     Rubble | (null) |          (null) |</pre><p>So, be careful when using outer joins that your where clause does not override the NULLs that an outer join allows.</p><h4>Conclusion</h4><p>Even though <strong><em>implicit inner joins</em></strong> offer a concise approach to table combining in SQL, it’s crucial to use this feature consciously. While it can be tempting to rely on the simplicity of implicit joins, especially for straightforward queries, it’s essential to consider readability and maintainability.</p><p>In scenarios where the join condition is clear and the query remains simple, implicit inner joins can be a pragmatic choice. However, for more complex queries or when working collaboratively on code, using the explicit INNER JOIN syntax is generally considered more effective in terms of code readability.</p><p>As you work on SQL queries, strike a balance between simplicity and readability, opting for <strong><em>implicit inner joins</em></strong> when appropriate. By making informed choices, you&#39;ll ensure that your SQL code is not only functional but also readable to your colleagues and future maintainers.</p><p><em>If you found this blog post helpful, please give it a clap. Thanks for reading…</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be273d964090" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Easy and effective State Management for Angular with Signals]]></title>
            <link>https://medium.com/@atakankorez/easy-and-effective-state-management-for-angular-with-signals-9dc81e904c18?source=rss-5368f4ac89d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/9dc81e904c18</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[angular-development]]></category>
            <category><![CDATA[angular-17]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[rxjs]]></category>
            <dc:creator><![CDATA[Atakan Korez]]></dc:creator>
            <pubDate>Thu, 30 Nov 2023 22:56:55 GMT</pubDate>
            <atom:updated>2023-12-02T22:28:35.779Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SR_Wt-Z_t9aNKdslc8TyCA.jpeg" /></figure><p>In this blog, we will delve into a simple and effective State Management technique using the novel <a href="https://angular.io/guide/signals"><strong>Signals </strong></a>architecture introduced in Angular 16. (You can access my blog post, in which I examine the Angular Signals structure in depth → <a href="https://medium.com/@atakankorez/angular-signals-in-every-aspect-20875d9cac27">Link</a>)</p><p>While Angular’s architecture is inherently rule-based and might seem complex, grasping its core logic reveals a developer-friendly structure. However, when it comes to state management within this seemingly intricate architecture, complexity can inevitably arise. In larger projects, achieving efficient state management calls for a commitment to the principle of simplicity. A pragmatic approach involves focusing solely on managing essential states and avoiding unnecessary intricacies.</p><p>To achieve this, leveraging existing libraries like <a href="https://ngrx.io/"><strong><em>NgRx</em></strong></a><strong><em>, </em></strong><a href="https://opensource.salesforce.com/akita/"><strong><em>Akita</em></strong></a>, and <a href="https://mobx.js.org/README.html"><strong><em>MobX</em></strong> </a>is an option. However, a recent consensus suggests that, to sidestep the complexities and boilerplate structures introduced by these libraries, a more viable approach may involve utilizing Angular’s injectable services without relying on additional frameworks. This preference is grounded in the reactive nature of injectable services, their provision of initial values, and their ease of writing, development, and maintenance.</p><p>Understanding state management terminology like actions, reducers, etc., may not be necessary for projects of any size. Also, <em>NgRx</em>’s use of BehaviorSubject introduces below challenges:</p><ol><li>Requires strong RxJS knowledge.</li><li>This may lead to excessive memory consumption and leaks in long or large data streams.</li><li>Synchronization or reliability issues in scenarios with multiple threads or asynchronous processes.</li></ol><p>Considering these, a signal-based architecture offers optimized change detection and synchronization. Choosing this approach, with the ability to snapshot values instantly, could be preferred in state management. Simply design a store using the signal concept, as demonstrated in a scenario where vehicle information entered in one component is listed in another.</p><p><em>VehicleStateManagementService</em>:</p><pre>import { Injectable, WritableSignal, signal } from &#39;@angular/core&#39;;<br><br>@Injectable({<br>  providedIn: &#39;root&#39;,<br>})<br>export class VehicleStateManagementService {<br>  constructor() {}<br>  private vehicles: WritableSignal&lt;{ brand: string; model: string; isElectric: boolean }[]&gt; = signal([]);<br><br>  addVehicle(model: string, year: number, isElectric: boolean) {<br>    this.vehicles.mutate((data) =&gt;<br>      data.push({<br>        brand: brand,<br>        model: model,<br>        isElectric: isElectric,<br>      })<br>    );<br>  }<br><br>  getAllVehicles() {<br>    return this.vehicles();<br>  }<br>}</pre><p>If you take a look at the above example, in the 9th line, the collection within the signal named vehicles has the vehicle object with the <strong>brand</strong> and <strong>model </strong>information added in addVehicle method, and in the getAllVehicles method, the collection, which is the value of this signal, is returned.</p><p>Now, let’s look at the components that will use this service — <em>createVehicle </em>and <em>listVehicle</em>:</p><pre>import { Component, inject } from &#39;@angular/core&#39;;<br>import { CommonModule } from &#39;@angular/common&#39;;<br>import { VehicleStateManagementService} from &#39;src/app/services/vehicle-state-management.service&#39;;<br> <br>@Component({<br>  selector: &#39;app-create-vehicle&#39;,<br>  standalone: true,<br>  imports: [CommonModule],<br>  template: `<br>    &lt;input type=&quot;text&quot; #txtBrand placeholder=&quot;Brand&quot;&gt; &lt;br&gt;<br>    &lt;input type=&quot;text&quot; #txtModel placeholder=&quot;Model&quot;&gt; &lt;br&gt;<br>    &lt;input type=&quot;checkbox&quot; #chkIsElectric placeholder=&quot;IsElectric&quot;&gt; &lt;br&gt;<br>    &lt;button (click)=&quot;createVehicle(txtBrand.value, txtModel.value, chkIsElectric.value)&quot;&gt;Create Vehicle&lt;/button&gt;<br>  `,<br>})<br>export class CreateVehicleComponent {<br>  vehicleStateManagementService: VehicleStateManagementService = inject(VehicleStateManagementService);<br>  createVehicle(brand: string, model: string, isElectric:boolean) {<br>    this.vehicleStateManagementService.createVehicle(model, name, isElectric);<br>  }<br>}</pre><pre>import { Component, OnInit, inject } from &#39;@angular/core&#39;;<br>import { CommonModule } from &#39;@angular/common&#39;;<br>import { VehicleStateManagementService} from &#39;src/app/services/vehicle-state-management.service&#39;;<br> <br>@Component({<br>  selector: &#39;app-list-vehicle&#39;,<br>  standalone: true,<br>  imports: [CommonModule],<br>  template: `<br>    &lt;ul&gt;<br>      &lt;li *ngFor=&quot;let vehicle of vehicles&quot;&gt;Brand:{{vehicle.brand}}, Model: {{vehicle.model}}, ElectrictyCar:{vehicle.isElectric}} &lt;/li&gt;<br>    &lt;/ul&gt;<br>  `,<br>})<br>export class ListVehicleComponent implements OnInit {<br>  vehicleStateManagementService: VehicleStateManagementService= inject(VehicleStateManagementService);<br> <br> <br>  vehicles: { brand: string, model: string, brand: boolean}[];<br>  ngOnInit() {<br>    this.vehicles = this.VehicleStateManagementService.getVehicles()<br>  }<br>}</pre><p>As seen below components, the vehicle information added in the <em>CreateVehicleComponent </em>is dynamically transferred to the <em>ListVehicleComponent </em>through the signal-based service. In other words, the changes resulting from adding a vehicle are instantly reflected in the component responsible for listing.</p><h4>Conclusion</h4><p>In this blog, I have demonstrated how state management in Angular applications can be handled with <em>Signals </em>without using any third-party libraries. I particularly emphasized that this approach allows for a simple and straightforward way of managing this process, especially in large projects.</p><p>By reducing complexity, this approach enables projects to be developed more effectively and efficiently. I hope you consider using this method in your future projects.</p><p><em>If you found this blog post helpful, please give it a clap. Thanks for reading…</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9dc81e904c18" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[New insane performance method for searching for values: Search Values]]></title>
            <link>https://medium.com/@atakankorez/new-insane-performance-method-for-searching-for-values-search-values-c3700a016b57?source=rss-5368f4ac89d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3700a016b57</guid>
            <category><![CDATA[microsoft-net]]></category>
            <category><![CDATA[net8]]></category>
            <category><![CDATA[net-core]]></category>
            <category><![CDATA[searchoperation]]></category>
            <category><![CDATA[microsoft-net-development]]></category>
            <dc:creator><![CDATA[Atakan Korez]]></dc:creator>
            <pubDate>Sat, 25 Nov 2023 22:15:50 GMT</pubDate>
            <atom:updated>2023-11-25T22:15:50.638Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*NSRkZ0SoSmcb4TmpNUg_Ag.jpeg" /></figure><p>In the latest advancements of .NET 8, a groundbreaking feature called <strong>Search Values</strong> has emerged, offering a paradigm shift in the efficiency of searching for values within datasets. It’s a class that provides an immutable, read-only set of values optimized for efficient searching. Let’s delve into the technical nuances and key insights of it.</p><h4>Introduction to Search Values in .NET 8</h4><p>NET 8 introduces a new type, <strong>Search Values</strong>, designed to revolutionize the efficiency of value searches in datasets. Microsoft has strategically integrated this feature into both .NET and ASP.NET Core, significantly harnessing its capabilities to enhance speed and memory utilization.</p><p>Underlying its efficiency is the methodological optimization within the create method. <strong>Search Values</strong> are designed to intelligently optimize searches based on the length of values, employing vectorization and hardware acceleration for further efficiency. Below is an example usage of Search Value:</p><pre>    private static readonly char[] Base64CharsArr =<br>    [<br>        &#39;A&#39;, &#39;B&#39;, &#39;C&#39;, &#39;D&#39;, &#39;E&#39;, &#39;F&#39;, &#39;G&#39;, &#39;H&#39;, &#39;I&#39;, &#39;J&#39;, &#39;K&#39;, &#39;L&#39;, &#39;M&#39;, &#39;N&#39;, &#39;O&#39;, &#39;P&#39;, &#39;Q&#39;, &#39;R&#39;, &#39;S&#39;, &#39;T&#39;, &#39;U&#39;, &#39;V&#39;, &#39;W&#39;,<br>        &#39;X&#39;, &#39;Y&#39;, &#39;Z&#39;, &#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;, &#39;f&#39;, &#39;g&#39;, &#39;h&#39;, &#39;i&#39;, &#39;j&#39;, &#39;k&#39;, &#39;l&#39;, &#39;m&#39;, &#39;n&#39;, &#39;o&#39;, &#39;p&#39;, &#39;q&#39;, &#39;r&#39;, &#39;s&#39;, &#39;t&#39;,<br>        &#39;u&#39;, &#39;v&#39;, &#39;w&#39;, &#39;x&#39;, &#39;y&#39;, &#39;z&#39;, &#39;0&#39;, &#39;1&#39;, &#39;2&#39;, &#39;3&#39;, &#39;4&#39;, &#39;5&#39;, &#39;6&#39;, &#39;7&#39;, &#39;8&#39;, &#39;9&#39;, &#39;+&#39;, &#39;/&#39;, &#39;=&#39;<br>    ];<br><br>    private static readonly SearchValues&lt;char&gt; Base64SearchVal = SearchValues.Create(Base64Chars);</pre><p>Microsoft’s adoption of search values extends beyond .NET and ASP.NET Core to critical components, such as HTTP character matching. The runtime architecture incorporates search values extensively for tasks like matching ASCII letters and potentially Base64 scenarios.</p><p>Let’s make some benchmark tests to evaluate the performance of Search Values!</p><p>The benchmark tests focus on validating whether a given string adheres to the criteria of a valid Base64 string. Criteria include characters from A to Z (uppercase and lowercase), numbers 0 to 9, and specific symbols such as ‘+’, ‘/’, and ‘=’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*RMldqC-jLEI-d6Ddjyo4BQ.jpeg" /><figcaption>Base64 Char List</figcaption></figure><p>Search values’ competitors in these benchmark tests are: Naive method with for loop, Span, and Linq.</p><pre> public string ExampleText { get; set; }<br><br> [Benchmark]<br> public bool IsBase64_SearchValues()<br> {<br>     return ExampleText.AsSpan().IndexOfAnyExcept(Base64SearchVal) == -1;<br> }<br> <br> [Benchmark]<br> public bool IsBase64_Span()<br> {<br>     return ExampleText.AsSpan().IndexOfAnyExcept(Base64CharsArr) == -1;<br> }<br><br><br> [Benchmark]<br> public bool IsBase64_Linq()<br> {<br>  return ExampleText.All(x =&gt; Base64CharsArr.Contains(x));<br> }<br><br> [Benchmark]<br> public bool IsBase64_Naive()<br> {<br>  for (var i = 0; i &lt; ExampleText.Length; i++)<br>     {<br>         var chr = ExampleText[i];<br>         if (!Base64CharsArr.Contains(chr))<br>         {<br>             return false;<br>         }<br>     }<br><br>     return true;<br> }</pre><p>The text values used in the benchmark tests are; A valid text of 10 characters, a non-valid text of 11 characters, a valid text of 60 characters, a valid text of 1Kb size, and a valid text of 10Kb size.</p><p>The Results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*sWhlq9reRHBNtoQGZNRC-w.jpeg" /></figure><p>As can be seen from the results, the performance of Search Values is incredible. While the performance difference with other methods is around 50x for short and simple texts, it is around 250x for larger texts (such as 1Kb, 10Kb).</p><p>The performance increase comes from <strong>Search Values</strong>’ create method. Because this method is optimized to take into account the length of the search values. It achieves performance increase by working with vectors after certain values. For details:<a href="https://source.dot.net/#System.Private.CoreLib/src/libraries/System.Private.CoreLib/src/System/SearchValues/SearchValues.cs,39adda97c6ae7a96"> .Net Source Browser</a></p><h4>Conclusion</h4><p>The introduction of <strong>Search Values</strong> in .NET 8 represents a groundbreaking leap forward in efficient value searches within datasets. Integrated seamlessly into.NET and ASP.NET Core, this feature employs advanced optimizations, including vectorization and hardware acceleration, leading to remarkable performance gains. Benchmark tests showcase Search Values outperforming(insane) competitors making it a powerful tool for developers seeking heightened efficiency in.NET 8.</p><p>Microsoft’s strategic adoption of Search Values extends its impact beyond.NET and ASP.NET Core, influencing critical components like HTTP character matching. The runtime architecture extensively incorporates Search Values, particularly in tasks involving matching ASCII letters and potential Base64 scenarios. This innovation underscores Microsoft’s commitment to delivering cutting-edge solutions that elevate the efficiency and capabilities of the.NET ecosystem.</p><p><em>If you found this blog post helpful, please give it a clap. Thanks for reading…</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3700a016b57" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Every new feature coming with C# 12]]></title>
            <link>https://medium.com/@atakankorez/every-new-feature-coming-with-c-12-0182d4657095?source=rss-5368f4ac89d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/0182d4657095</guid>
            <category><![CDATA[c-sharp-language]]></category>
            <category><![CDATA[c-sharp-development]]></category>
            <category><![CDATA[csharp-12]]></category>
            <category><![CDATA[dot-net-framework]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <dc:creator><![CDATA[Atakan Korez]]></dc:creator>
            <pubDate>Sat, 18 Nov 2023 20:06:34 GMT</pubDate>
            <atom:updated>2023-11-29T08:04:34.557Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*PnLIEoJhxWEwZjBS07Gp_g.jpeg" /></figure><p>The evolution of C# is a continuous process that drives the language to new heights of expressiveness, productivity, and performance. With the release of C# 12, developers are set to experience a range of new features and enhancements that will shape the future of C# programming. This blog post will delve into the key features of C# 12, highlighting their significance and providing insights into their practical applications. Let’s start!</p><h4>Primary Constructors</h4><p>To grasp the essence of primary constructors, let’s first revisit the existing feature introduced in C# 9 → records.</p><p>In C# 9, developers gained the ability to create records, essentially classes with default implementations for common scenarios. For instance, declaring a record ‘user’ with a ‘name’ property allowed for easy instantiation and utilization:</p><pre>public record User(string Name);<br><br>// Usage<br>var user = new User(&quot;Atakan&quot;);</pre><p>This record feature streamlined the process of creating classes with properties. However, in C# 12, primary constructors extend this convenience to traditional classes. Consider the following example, where a class User is declared with name and age parameters:</p><pre>public class User(string name, int age)<br>{<br>    public string Name// Name used directly in function members<br>    {<br>        get =&gt; name;<br>        set =&gt; name= value ?? throw new ArgumentNullException(nameof(name));<br>    }<br><br>    public int Age {get; set;} = age; // name used for initialization<br>}</pre><p>In the above example, the constructor parameters name and age can serve different purposes for class.</p><p>The primary constructor feature in C# 12 offers flexibility by allowing its usage in various contexts. The primary constructor streamlines code and enhances code maintainability, whether applied to properties, methods, or constructors. For instance, the primary constructor parameter name can be employed within a method:</p><pre>// Primary Constructor<br>public class User(string name)<br>{<br>    public void Method1()<br>    {<br>      /* Utilizing the &#39;name&#39; parameter as a private field - not readonly <br>        So, you can assign a value to it */ <br>        name = &quot;Atakan&quot;;      <br>        Console.WriteLine(name);<br>    }<br>}</pre><p>Primary constructors in C# 12 mark a significant step towards code simplification and improved developer experience. It is important for developers to pay attention to the following points when using them:</p><ul><li>Primary constructor parameters may not be stored if they aren’t needed</li><li>Primary constructor parameters aren’t members of the class. For example, a primary constructor parameter named param can’t be accessed as this.param</li><li>Primary constructor parameters can be assigned to</li><li>Primary constructor parameters don’t become properties, except in record types</li></ul><h4>Collection Expressions</h4><p>C# 12 release introduces a groundbreaking feature known as <strong>Collection Expressions</strong>. This enhancement revolutionizes the initialization of arrays and other data structures, providing developers with a more concise and expressive syntax.</p><p>Traditionally, declaring and initializing an array in C# involved verbose syntax, as exemplified below:</p><pre>int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8};</pre><p>The collection Expressions feature enables developers to achieve the same result with a more concise syntax:</p><pre>int[] numbers = [1, 2, 3, 4, 5, 6, 7, 8];</pre><p>This syntax not only enhances readability but also brings uniformity to array initialization. However, it’s crucial to note that explicit type declaration is now mandatory which means you can’t use var keyword with this new feature!</p><p>The power of Collection Expressions extends beyond arrays, encompassing various data structures. For instance, initializing a span or a jagged 2D array becomes more intuitive:</p><pre>Span&lt;int&gt; span = [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;];<br>int[][] jaggedArray = [[1, 2, 3], [4, 5, 6]];</pre><blockquote><strong>Bonus →</strong> Empty Dictionary Initialization</blockquote><blockquote>While not officially part of the planned C# 12 features, developers gain the ability to initialize an empty dictionary using angle brackets.</blockquote><pre>Dictionary&lt;string, string&gt; dic = [];</pre><h4>Ref Readonly Parameters</h4><p>The RefReadonly parameters are a new feature in C# 12 that allows you to pass references to data that should not be modified. This can improve performance and make your code more readable. When you pass a reference to a variable as a ref readonly parameter, the compiler ensures that the variable’s value cannot be changed inside the method. This means that you can safely pass the reference to a method without worrying about the method modifying the variable’s value.</p><pre>public void Swap(ref readonly int x, ref readonly int y)<br>{<br>    int temp = x;<br>    x = y;<br>    y = temp;<br>}</pre><p>In blow example, the Swap method takes two ref readonly parameters: x and y. The ref readonly modifier indicates that the method cannot modify the values of x and y. Inside the method, the values of x and y are swapped using a temporary variable. This ensures that the original values of x and y remain unchanged.</p><h4>Default Lambda Parameters</h4><p>The upcoming C# 12 release introduces a highly anticipated quality-of-life feature known as <strong>Default Lambda Parameters</strong>. This feature enhances the flexibility of lambda expressions by allowing developers to set default values for parameters, streamlining code, and simplifying invocations.</p><p>Consider a scenario where a lambda expression defines a parameter, such as in the example below:</p><pre>var ageLambda = (string name, int age) =&gt; $&quot;{name} is {age} years old&quot;;</pre><p>Traditionally, when invoking this lambda, both parameters must be explicitly provided:</p><pre>string result = ageLambda(&quot;Atakan&quot;, 40);</pre><p>Default Lambda Parameters enable developers to set default values for parameters within the lambda expression:</p><pre>var ageLambdaWithDefault = (name = &quot;Atakan&quot; , age = 40) =&gt; $&quot;{name} is {age} years old&quot;;<br><br>string result = ageLambdaWithDefault(); <br>// I can also specify any value, for e.g. --&gt; ageLambdaWithDefault(&quot;Korez&quot;, 35); </pre><h4>Alias Any Type</h4><p>This feature challenges traditional constraints by relaxing rules on the usage of the using alias directive, particularly in the context of pointer types, array types, and more.</p><p><strong>Alias Any Type </strong>essentially redefines the possibilities of the using alias directive in C# 12. Previously restricted in certain contexts, such as pointer types and array types, Alias Any Type breaks these barriers, ushering in a new era of flexibility in type definitions.</p><p>One illustrative example of Alias Any Type’s transformative power is the creation of a 2D point type. With the following declaration:</p><pre>using Point2D = int X, int Y;</pre><p>Developers can now use Point2D as a concise, tuple-like structure, reminiscent of a struct:</p><pre>var point = new Point2D(3, 7);</pre><p>This opens up possibilities for implicit conversions, allowing developers to seamlessly integrate Point2D into their codebase.</p><h4>Inline Arrays</h4><p>In the latest strides towards optimizing performance, C# 12 introduces a feature known as <strong>Inline Arrays</strong>. Originally utilized by the runtime team at Microsoft and library authors, this feature is now being made public to benefit a broader spectrum of developers.</p><p>The primary aim is to enhance the performance of applications leveraging .NET or associated libraries. So, Inline Arrays provide a performant solution through fixed-size stack-allocated buffers. An <em>inline array</em> is declared similar to the following struct:</p><pre>[System.Runtime.CompilerServices.InlineArray(10)]<br>public struct Buffer<br>{<br>    private int _element0;<br>}</pre><p>You use them like any other array:</p><pre>var buffer = new Buffer();<br>for (int i = 0; i &lt; 10; i++)<br>{<br>    buffer[i] = i;<br>}<br><br>foreach (var i in buffer)<br>{<br>    Console.WriteLine(i);<br>}</pre><p>Inline Arrays address performance concerns by offering developers a fixed-size stack-allocated buffer. The key objective is to align the performance characteristics of a stack-allocated buffer with those of an unsaved fixed-size buffer. While the inner workings may delve into intricate details of performance optimization, developers can leverage Inline Arrays to enhance the speed and efficiency of their code.</p><h4><strong>Experimental Attribute</strong></h4><p>This attribute provides a mechanism for developers to label features as experimental or risky, signaling potential changes or removal in future updates. It serves as a marker for features that are considered experimental or risky. By applying this attribute to a specific feature or code block, developers convey that the associated functionality is subject to evaluation and may undergo changes or removal in future updates.</p><p>To designate a feature as experimental, developers can utilize the Experimental Attribute by providing a diagnostic ID. Here’s a simple illustration:</p><pre>[Experimental(&quot;RiskyID&quot;)]<br>public class ExperimentalFeature<br>{<br>    // Feature implementation<br>}</pre><p>When attempting to use the marked feature, developers receive a compilation error, emphasizing the experimental nature of the code:</p><pre>// Compilation error due to experimental feature<br>var instance = new ExperimentalFeature(); </pre><p>To proceed with using an experimental feature, developers must explicitly suppress the compilation error. This intentional step signals an awareness of the risks associated with the feature:</p><pre>#pragma warning disable RiskyId<br>var instance = new ExperimentalFeature();<br>#pragma warning restore RiskyId</pre><h4><strong>Interceptors</strong></h4><p>C# 12 introduces a revolutionary feature called <strong>Interceptors</strong>, offering developers the ability to intercept and modify method invocations during compile time. Although in preview, this feature opens new doors for code manipulation without directly altering the source.</p><p>Interceptors allow developers to intercept method invocations and replace them with custom code during compile time. This powerful capability introduces a paradigm shift in code manipulation, enabling developers to enhance or modify behavior without directly modifying the original source code.</p><p>Consider the following example class with two methods:</p><pre>public class Example<br>{<br>    public void MethodOne() =&gt; Console.WriteLine(&quot;Hello from method one&quot;);<br>    public void MethodTwo(string name) =&gt; Console.WriteLine($&quot;Hello from method two, {name}&quot;);<br>}</pre><p>Now, let’s create an Interceptor to modify the behavior of MethodOne:</p><pre>[InterceptsLocation(&quot;C:\\Path\\To\\Your\\File\\Example.cs&quot;, 6, 9)]<br>public static class Interception<br>{<br>    public static void InterceptMethodOne(this Example example)<br>    {<br>        Console.WriteLine(&quot;Hello from Interceptor&quot;);<br>    }<br>}</pre><p>In this example, the InterceptMethodOne extension method intercepts the original MethodOne at the specified location in the source code.</p><p>To use the Interceptor, no modifications are needed in the original class. Simply instantiate the Example class and call the methods as usual:</p><pre>class Program<br>{<br>    static void Main()<br>    {<br>        Example example = new Example();<br>        example.MethodOne(); // Outputs: Hello from Interceptor<br>        example.MethodTwo(&quot;Atakan&quot;); // Outputs: Hello from method two, Atakan<br>    }<br>}</pre><p>Interceptors can also handle method parameters. For instance, modifying MethodTwo using an Interceptor:</p><pre>[InterceptsLocation(&quot;C:\\Path\\To\\Your\\File\\Example.cs&quot;, 7, 9)]<br>public static class Interception<br>{<br>    public static void InterceptMethodTwo(this Example example, string name)<br>    {<br>        Console.WriteLine($&quot;Hello from Interceptor, {name}&quot;);<br>    }<br>}</pre><p>Now, invoking MethodTwo triggers the Interceptor:</p><pre>class Program<br>{<br>    static void Main()<br>    {<br>        Example example = new Example();<br>        example.MethodTwo(&quot;Atakan&quot;); // Outputs: Hello from Interceptor, Atakan<br>    }<br>}</pre><h4>Conclusion</h4><p>C# 12 marks a significant milestone in the evolution of the C# language, bringing a plethora of new features and enhancements that empower developers to write more expressive, maintainable, and performant code. From the streamlined object initialization with primary constructors to the concise array creation with inline arrays, C# 12 introduces a range of features that enhance productivity and code quality.</p><p>I encourage you to delve into the exciting world of C# 12 and explore the boundless opportunities it presents for crafting exceptional code. As you embark on this journey of discovery, remember that the C# community is always here to support and guide you. Together, let’s embrace the power of C# 12 and shape the future of software development.</p><p><em>If you found this blog post helpful, please give it a clap. Thanks for reading…</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0182d4657095" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Control Flow Syntax: Is Angular starting to look like Razor?]]></title>
            <link>https://medium.com/@atakankorez/control-flow-syntax-is-angular-starting-to-look-like-razor-008f51d0e4a2?source=rss-5368f4ac89d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/008f51d0e4a2</guid>
            <category><![CDATA[angular-17]]></category>
            <category><![CDATA[razor]]></category>
            <category><![CDATA[ngfor]]></category>
            <category><![CDATA[ngswitch]]></category>
            <category><![CDATA[ngif]]></category>
            <dc:creator><![CDATA[Atakan Korez]]></dc:creator>
            <pubDate>Sun, 12 Nov 2023 22:18:00 GMT</pubDate>
            <atom:updated>2023-11-12T22:18:00.169Z</atom:updated>
            <content:encoded><![CDATA[<h3>Control Flow Syntax: Is Angular starting to look like Razor Engine?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*-0JtZWOXkX4SIor6NLgjdg.jpeg" /></figure><p>In this blog, we delve into the feature known as Control Flow Syntax in Angular 17. Unlike traditional directives such as *ngIf,*ngFor, and *ngSwitch, which are inherently present in the architecture, <em>Control Flow Syntax</em> enables a more programmatic approach using if/else, for, and switch structures.</p><p>Before delving into the new syntax of the mentioned directives, let’s first examine how these directives have functioned in Angular until now.</p><h4>Understanding Angular Structural Directives</h4><p>Angular has provided us with built-in structural directives, known as Structural Directives, allowing us to add, remove, or manipulate any HTML element on the page. In other words, these directives empower us to interact with the structure of the DOM. For instance, consider the following code block:</p><pre>&lt;div *ngIf=&quot;condition&quot;&gt;<br>  &lt;ul&gt;<br>    &lt;li *ngFor=&quot;let person of persons&quot;&gt;<br>      {{person}}<br>    &lt;/li&gt;<br>  &lt;/ul&gt;<br>&lt;/div&gt;</pre><p>As evident from the example code, this process, executed in conjunction with structural directives such as *ngIf and *ngFor that commences with the asterisk character and fundamentally involves the transformation of the Angular compiler into JavaScript code. All these fragments essentially enable us to use directives with the asterisk character within an ng-template, applying syntactic sugar. In other words, the Angular compiler transforms the above example into the following in the background.</p><pre>&lt;ng-template [ngIf]=&quot;condition&quot;&gt;<br>&lt;div&gt;<br>  &lt;ng-template&gt;<br>  &lt;ul&gt;<br>    &lt;ng-template [ngFor]=&quot;persons&quot; let-person&gt;<br>    &lt;li&gt;<br>      {{person}}<br>    &lt;/li&gt;<br>    &lt;/ng-template&gt;<br>  &lt;/ul&gt;<br>  &lt;/ng-template&gt;<br>&lt;/div&gt;<br>&lt;/ng-template&gt;</pre><p>As you may be aware, Angular incorporates the concept of a ViewContainer, allowing you to add and remove child views dynamically. This structure enables Angular to exhibit the necessary dynamic behavior in the DOM, and the aforementioned content changes are facilitated through this container. Angular utilizes a special HTML comment to position the container for the dynamic point where the content will change in the DOM.</p><p>In essence, what has been described so far boils down to this. For example, *ngIf will create a ViewContainer in the background, and this container will be associated with a specific point in the DOM using a special HTML comment. Depending on the given condition, a child view will be added or removed at this point. In other words, that object will either be displayed or removed.</p><p>To put it concisely, we covert the template into an ng-template behind the scenes, and then dynamically manage it using ViewContainer, thanks to the built-in directives. Although this structure seems powerful, its lack of intuitiveness and inherent drawbacks, such as compiler costs, prompted the Angular team to develop a more efficient <em>Control Flow Syntax</em>. This alternative performs the same tasks and constructs the same view without the added compiler overhead associated with directives.</p><p>Below is the sample code blog rewritten using Control Flow Syntax:</p><pre>@if(condition)<br>{<br>  &lt;div&gt;<br>    &lt;ul&gt;<br>      @for(person of persons;track $index){<br>        &lt;li&gt;{{person}}&lt;/li&gt;<br>      }<br>    &lt;/ul&gt;<br>  &lt;/div&gt;<br>}</pre><h4>Control Flow Syntax Structures</h4><ol><li><strong>if statement : </strong>It can be used as follows:</li></ol><pre>@if(condition == 1)<br>{<br>  &lt;div&gt;<br>    Condition is 1<br>  &lt;/div&gt;<br>}@else if(condition == 2)<br>{<br>  &lt;div&gt;<br>    Condition is 2<br>  &lt;/div&gt;<br>}@else{<br>  &lt;div&gt;<br>    Condition is 3<br>  &lt;/div&gt;<br>}</pre><p>Moreover, there’s an additional detail: you have the option to assign the outcome of the controlled condition to a separate variable, as illustrated below:</p><pre>@if(condition == 1; as result)<br>{<br>  &lt;div&gt;<br>    Condition is {{result}}<br>  &lt;/div&gt;<br>}</pre><p>2. <strong>for statement: </strong>The use of the for statement is combined with the track keyword.</p><pre>&lt;ul&gt;<br>   @for(person of persons;track $index)<br>   {<br>     &lt;li&gt;{{person}}&lt;/li&gt;<br>   }<br>&lt;/ul&gt;</pre><p>In addition to the previous for structure, the ability to perform operations in the case of an empty collection is an important innovation.</p><pre>&lt;ul&gt;<br>   @for(person of persons;track $index)<br>   {<br>     &lt;li&gt;{{person}}&lt;/li&gt;<br>   }<br>   @empty<br>   {<br>    &lt;li&gt;<br>      &lt;strong&gt;No person&lt;/strong&gt;<br>    &lt;/li&gt;<br>   }<br>&lt;/ul&gt;</pre><p>In the previous versions, we needed *ngIf to perform the below check and display a message if the collection was empty. The new syntax makes the process much simpler and more elegant, doesn’t it?</p><p>By the way, you can still access variables like $index, $first, $last, $even, $odd, and $count, which were available in the previous version.</p><p>3.<strong> switch statement: </strong>The switch structure can also be used with the following syntax:</p><pre>@switch (accessLevel) {<br>  @case (&#39;admin&#39;) { &lt;admin&gt;&lt;/admin&gt;}<br>  @case (&#39;user&#39;) { &lt;user&gt;&lt;/user&gt;}<br>  @case (&#39;guest&#39;) { &lt;guest&gt;&lt;/guest&gt;}<br>}</pre><p>Now you may have the following question in your mind: Will we do this conversion manually, one by one, in a project with hundreds, maybe thousands of structural directives?</p><p>The answer is both Yes and No. If you have a lot of free time and patience, yes 😃, but if you are impatient (!) and short on time like me, the Angular team has taken us into consideration and allowed us to do this process automatically 🙏 To achieve this, the instructions you need to provide to the CLI will be as follow — &gt; ng g @angular/core:control-flow</p><p>As a result of this command, both the directive operations in the application’s components and the special characters such as @, {, and } in the templates will be converted into HTML entities, as mentioned in the previous lines.</p><blockquote>Note: With this syntax, the characters @, {, and } now have special meanings. Therefore, using these characters in the template will result in an error. To use them, the following equivalents should be used:</blockquote><blockquote>@ = &amp;#64;</blockquote><blockquote>{ = &amp;#123;</blockquote><blockquote>} = &amp;#125;</blockquote><p><strong>Conclusion</strong></p><p>I anticipate that the Angular team will prioritize and promote the use of the control flow syntax in projects as a recommended practice at points of need in the future. It’s important to note that the introduction of the control flow syntax does not necessarily mean the elimination of the usage of structural directives.</p><p>Frankly, as a developer who actively uses Asp.Net, I loved <em>Control Flow Syntax</em>. Because it is very similar to the Razor engine and I love using it.</p><p>If you found this blog post helpful, please give it a clap. Thanks for reading…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=008f51d0e4a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dockerize a .Net Project Without Dockerfile]]></title>
            <link>https://medium.com/@atakankorez/dockerize-a-net-project-without-dockerfile-4232a2b9246c?source=rss-5368f4ac89d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/4232a2b9246c</guid>
            <category><![CDATA[containerization]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[dockerfiles]]></category>
            <category><![CDATA[net-7]]></category>
            <category><![CDATA[tips-and-tricks]]></category>
            <dc:creator><![CDATA[Atakan Korez]]></dc:creator>
            <pubDate>Sat, 28 Oct 2023 20:46:58 GMT</pubDate>
            <atom:updated>2023-10-28T20:46:58.826Z</atom:updated>
            <content:encoded><![CDATA[<h3>Dockerize a .Net Project Without Dockerfile</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/893/1*T5Va52sBVV1Rpx5Yjs8V4A.jpeg" /></figure><p>In this blog post, we’re going to explore a fascinating feature introduced in .NET 7 and later versions that allows us to containerize applications without the need for a Dockerfile. Additionally, we’ll take a closer look at the built-in container support that’s shaking up the world of DevOps.</p><p>Imagine a world where you can wave goodbye to the hassle of maintaining Dockerfiles for your applications. Well, Microsoft has turned this into a reality. Starting with .NET 7 SDK, they’ve revolutionized the process of containerizing applications by eliminating the dependency on Dockerfiles, making your DevOps workflow smoother and more streamlined. With this approach, containerizing applications becomes a breeze, and the need for complex Dockerfiles is a thing of the past.</p><p>The crux of this approach revolves around simplifying the way we containerize software applications. In the past, developers often had to dive deep into Dockerfiles, investing significant time and energy into getting things just right. But with .NET 7 and beyond, you can create and deploy Docker images right from the .NET CLI tool. This makes the whole process much more efficient and manageable.</p><p>Now, let’s take a trip down memory lane and recall how we used to containerize a .NET application with a Dockerfile. Simultaneously, we’ll explore how to achieve the same without a Dockerfile. Let’s dive right in.</p><p>First, let’s create an ASP.NET Core WEB API application with a simple endpoint:</p><pre>var builder = WebApplication.CreateBuilder(args);<br><br>var app = builder.Build();<br><br>app.MapGet(&quot;/&quot;, () =&gt; &quot;Hello World!&quot;);<br><br>app.Run();</pre><p>Now, to containerize this application, let’s create a Dockerfile with the following content:</p><pre>FROM mcr.microsoft.com/dotnet/sdk:7.0 as build<br>WORKDIR /src<br>COPY *.csproj .<br>RUN dotnet restore<br>COPY . .<br>RUN dotnet publish -c Release -o /publish<br><br>FROM mcr.microsoft.com/dotnet/aspnet:7.0 as runtime<br>WORKDIR /publish<br>COPY --from=build /publish .<br>ENV ASPNETCORE_URLS=http://+:5000<br>EXPOSE 5000<br>ENTRYPOINT [&quot;dotnet&quot;, &quot;Docker.Example.dll&quot;]</pre><p>With the image at your disposal, you can now create a container from it using the below command:</p><pre>docker run -p 5000:5000 --name docker-example-container docker-example</pre><p>Finally, let’s make a request to <a href="http://localhost:5000/">http://localhost:5000/</a>. Voila! You’ve successfully containerized your .NET application without a Dockerfile.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/344/1*NofcloM_e5rySPWPaZKemA.png" /></figure><p>You might be thinking, “What’s the catch? It all sounds too easy.” Well, you’re absolutely right; there’s no catch. This approach is ideal for straightforward containerization of .NET applications. However, as your application’s requirements and project complexity grow, so does the content of your Dockerfile. This inevitably translates to increased maintenance costs. To address such situations, Microsoft has stepped in, offering container support in .NET that lets you skip Dockerfiles.</p><p>With this support, creating Docker images and launching containers is as simple as a single command:</p><pre>dotnet publish --os linux --arch x64 -p:PublishProfile=DefaultContainer -p:ContainerImageName=docker-example</pre><p>If that command seems complex, you can simplify it by adding properties like ContainerImageName, PublishProfile, and ContainerImageTags directly in your .csproj file, as shown below:</p><pre>&lt;Project Sdk=&quot;Microsoft.NET.Sdk.Web&quot;&gt;<br>  ...<br>  &lt;PropertyGroup&gt;<br>    ...<br>    &lt;ContainerImageName&gt;docker-example-container&lt;/ContainerImageName&gt;<br>    &lt;PublishProfile&gt;DefaultContainer&lt;/PublishProfile&gt;<br>    &lt;ContainerImageTags&gt;1.0.0;latest&lt;/ContainerImageTags&gt;<br>  &lt;/PropertyGroup&gt;<br>  &lt;ItemGroup&gt;<br>    ...<br>  &lt;/ItemGroup&gt;<br>&lt;/Project&gt;</pre><p>In this simplified scenario, you can use the command:</p><pre>dotnet publish --os linux --arch x64</pre><p>For even further simplification, you can add the RuntimeIdentifier property like this:</p><pre>&lt;ContainerImageName&gt;docker-example-container&lt;/ContainerImageName&gt;<br>&lt;PublishProfile&gt;DefaultContainer&lt;/PublishProfile&gt;<br>&lt;ContainerImageTags&gt;1.0.0;latest&lt;/ContainerImageTags&gt;<br>&lt;RuntimeIdentifier&gt;linux-x64&lt;/RuntimeIdentifier&gt;</pre><p>Now you can create your image just with the dotnet publish command! You can also define an environment variable using the ContainerEnvironmentVariable property as follows.</p><pre>&lt;Project Sdk=&quot;Microsoft.NET.Sdk.Web&quot;&gt;<br>  .<br>  .<br>  .<br>  &lt;ItemGroup&gt;<br>    &lt;ContainerEnvironmentVariable Include=&quot;Example_Environment_Variable&quot; Value=&quot;PortNumber&quot; /&gt;<br>  &lt;/ItemGroup&gt;<br>&lt;/Project&gt;</pre><h4>Conclusion</h4><p>.NET’s built-in container support for versions 7 and beyond is a game-changer, simplifying the containerization process. With no need for complex Dockerfiles, developers can efficiently create and deploy Docker images directly from the .NET CLI tool, making DevOps workflows smoother and more accessible.</p><p>Whether it’s a straightforward application or a complex project, this approach saves time and effort, offering a streamlined path to containerization. Embrace this change, enjoy the benefits, and simplify your DevOps journey in the .NET ecosystem.</p><p><em>If you found this blog post helpful, please give it a clap. Thanks for reading…</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4232a2b9246c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular Signals: A Deep Dive]]></title>
            <link>https://medium.com/@atakankorez/angular-signals-in-every-aspect-20875d9cac27?source=rss-5368f4ac89d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/20875d9cac27</guid>
            <category><![CDATA[angular-signals]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[angularjs]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[rxjs]]></category>
            <dc:creator><![CDATA[Atakan Korez]]></dc:creator>
            <pubDate>Sun, 08 Oct 2023 19:34:05 GMT</pubDate>
            <atom:updated>2023-10-08T19:36:16.179Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*q1XAzZg4xyw4qVUDGHO06A.png" /></figure><p>In this blog, we will thoroughly examine Signals, a new feature introduced with Angular 16, which makes life easier for developers and improves application performance while also reducing costs. Signals provide a new way to capture when a variable undergoes a data change, making the code more reactive. So, let’s get started.</p><h4>What are Signals?</h4><p>Signals are a new feature that tracks changes in a variable’s value and notifies us reactively when a change occurs. To better understand this, let’s proceed with the example below:</p><pre>let x = 50;<br>let y = 100;<br>let z = x + y;<br>console.log(z); // 150<br>x = 100;<br>console.log(z); // 150</pre><p>If you look at the code above, you can see that the variable z is calculated from the variables x and y, and the result is printed to the console on line 4. Everything seems normal so far, but do you think changing the value of the x variable on line 5 will make any difference in the value of z on line 6? Of course not, right? That&#39;s because the value of z will remain independent of x and y from line 3 onwards, and any changes to x or y during the process will not affect z!</p><p>However, if you want the code to react to changes in x or y, or in other words, if you want z to be recalculated when x or y values change, you need to be more reactive. You can use a getter property like the one below for that purpose:</p><pre>get total() {<br>  return this.x + this.y;<br>}</pre><p>Yes, this way you can achieve reactive behavior. However, if you want to apply this directly to a variable when a change occurs, you can use Signals like this:</p><pre>let x = signal(50);<br>let y = 100;<br>let z = computed(() =&gt; x() + y);<br>console.log(z()); // 150<br>x.set(100)<br>console.log(z()); // 200</pre><p>As you can see, the signal function is used to track changes in the x variable, and the computed function is used to recalculate the value of z when this variable changes. The set function is used to change the value, as shown in line 5. Of course, we will explore these functions and their purposes in detail in the following lines. For now, we have provided a simple example to show you how reactive behavior can be easily achieved with the Signals feature.</p><p>Long story short, Signals allow us to dynamically track the values of variables (at the variable level) in Angular applications and take actions with various qualities in case of possible changes. This enables us to easily perform our desired tasks along with these actions, improving application performance and providing an effective user experience in terms of change detection.</p><blockquote>Zone.JS is a runtime model that allows Angular to work effectively with asynchronous operations and handle events efficiently. It regulates the interactions of components and other parts of an Angular application, optimizing performance. In other words, Zone.JS ensures that components respond to changes in any part of the DOM where changes occur, regardless of their location. So, we can say that Signals work independently of Zone.JS in Angular!</blockquote><h4>How to Define and Use Signals?</h4><p>To define a signal, we use the signal function found in the @angular/core path.</p><pre>import { signal } from &#39;@angular/core&#39;;<br>// ...<br>let x = signal(50);</pre><p>As you can see in the code above, a signal with a value of 50 has been defined. When we inspect the type of this signal, we will see that it is of type WritableSignal. In other words, it can be both read and written. To make this more explicit, you can specify the type of the created signal as follows:</p><pre>let x: WritableSignal&lt;number&gt; = signal(5);</pre><p>During the definition process, you can also specify the type of the signal as a generic parameter:</p><pre>let x: WritableSignal&lt;string&gt; = signal&lt;string&gt;(&quot;hello&quot;);</pre><p>To use a defined signal or, in other words, to read the value of a signal, you can call it as a function when needed. Note that the parentheses should be empty as shown below:</p><pre>x(); // This is how you read the value of the signal x</pre><p>Now let’s take a look at important functions that allow us to perform actions on signals.</p><h4>set Function</h4><p>The set() function allows us to assign a different value to a signal besides its initial value or update the existing value.</p><pre>let x: WritableSignal&lt;number&gt; = signal&lt;number&gt;(20);<br>console.log(x()); // 20<br>x.set(45);<br>console.log(x()); // 45</pre><p>It’s crucial to know the following details about the set() function: If the set() function is called consecutively on a signal and assigns the same value, this will trigger a change in the signal value as if it has been changed. This is extremely important for scenarios where you need to react to changes in a value, as it ensures that your signal reacts even when the value assigned is the same as the previous one.</p><pre>let x: WritableSignal&lt;number&gt; = signal&lt;number&gt;(20);<br>console.log(x()); // 20<br>x.set(20); // Although the same value is assigned, it will trigger change detection<br>console.log(x()); // 20</pre><h4>update function</h4><p>The update() function is used to update a signal to a new value that is based on the current value. It takes a function as an argument that returns the new value.</p><pre>// Create a signal.<br>const count = signal(5);<br><br>// Update the signal using the update() method.<br>count.update(value =&gt; value + 1);<br><br>// Log the new value.<br>console.log(count.value); // 6</pre><h4>mutate function</h4><p>The mutate() function is used to directly modify the current value of a signal. It takes a function as an argument that performs the mutation.</p><pre>// Create a signal.<br>const users = signal([]);<br><br>// Add a new user to the signal using the mutate() method.<br>users.mutate(users =&gt; users.push({ name: &#39;Atakan&#39; }));<br><br>// Log the new value.<br>console.log(users.value); // [{ name: &#39;Atakan&#39; }]</pre><blockquote>When to use the update() or mutate() method depends on the specific situation. If you need to update a signal to a new value that is based on the current value, then use the update() method. If you need to directly modify the current value of a signal, then use the mutate() method.</blockquote><h4>subscribe Function</h4><p>The subscribe() function allows us to monitor changes in the value of a signal and perform specific actions when a change occurs.</p><pre>let x: WritableSignal&lt;number&gt; = signal&lt;number&gt;(20);<br>const subscription = x.subscribe((newValue, oldValue) =&gt; {<br>  console.log(`Value changed from ${oldValue} to ${newValue}`);<br>});<br><br>x.set(40); // This will trigger the subscription callback</pre><p>In this example, a subscription is created to the signal x, and whenever the value of x changes (as a result of using the set() function), the callback provided to subscribe() is executed. This way, you can react to changes in the value of a signal and perform actions accordingly.</p><blockquote>Remember to unsubscribe from the subscription when it’s no longer needed to prevent memory leaks!</blockquote><h4>map Function</h4><p>The map() function allows us to create a new signal that derives its value from an existing signal, transforming it in the process.</p><pre>let x: WritableSignal&lt;number&gt; = signal&lt;number&gt;(20);<br>let y = x.map((value) =&gt; value * 3);<br>console.log(y()); // 60<br><br>x.set(25); // This will trigger a change in y as well<br>console.log(y()); // 75</pre><p>In this example, the signal y is derived from the signal x using the map function. The transformation function multiplies the value of x by 2, resulting in a new signal y with the updated value when x changes.</p><h4>Computed Functions</h4><p>Computed functions are a powerful way to create signals that automatically recalculate their values based on other signals. These functions are created using the computed() function.</p><pre>import { computed } from &#39;@angular/core&#39;;</pre><pre>let x = signal(20);<br>let y = signal(30);</pre><pre>let z = computed(() =&gt; x() + y());<br>console.log(z()); // 50</pre><pre>x.set(25); // This will trigger a recalculation of z<br>console.log(z()); // 55</pre><p>In this example, we create a computed signal z that calculates its value based on the values of signals x and y. When either x or y changes, z is automatically recalculated, ensuring that it always reflects the correct value.</p><h4>effect function</h4><p>When the value of a signal changes, we may want to execute some code. To achieve this, we can use the effect function, which can only be used at the constructor level.</p><pre>@Component({<br>  selector: &#39;app-root&#39;,<br>  standalone: true,<br>  template:<br>    &#39;&lt;button (click)=&quot;onSet()&quot;&gt;set&lt;/button&gt; &lt;br&gt;{{x()}}&#39;,<br>})<br>export class AppComponent {<br>  constructor() {<br>    effect(() =&gt; console.log(&quot;Current value of x: ${this.x()}&quot;));<br>  }<br><br>  x: WritableSignal&lt;number&gt; = signal&lt;number&gt;(1);<br><br>  onSet() {<br>    this.x.update((data) =&gt; data + 10);<br>  }<br>}</pre><p>As seen in the example above, with the effect function defined in the constructor, we can perform additional actions in response to possible data changes in the “x” signal. The effect function always runs the change detection process asynchronously.</p><p>The effect function can be used for various purposes, such as logging data during changes, synchronizing data to local storage during changes, or adding custom DOM behaviors. Additionally, when an effect is created, it will automatically be destroyed when the component, directive, or pipe to which it belongs is destroyed. If you wish to manually destroy an effect, you can use the destroy function as follows:</p><pre>const _effect: EffectRef = effect(() =&gt; /* ... */);<br>_effect.destroy();</pre><p>Under normal circumstances, you cannot change the value of a signal within effectand computedfunctions. If you need to change it, you should do so through the allowSignalWrites property, although this approach is not generally recommended:</p><pre>effect(() =&gt; {<br>  console.log(&quot;Current value of x: ${this.x()}&quot;);<br>  this.x.update((data) =&gt; data + 10);<br>}, { allowSignalWrites: true });</pre><p>It’s important to note that allowing signal value changes within an effectusing the allowSignalWritesproperty is not recommended.</p><h4>cleanup function</h4><p>In cases where an effect is triggered serially due to frequent changes in the “x” signal, and you want to stop the previous effect’s process before starting a new one, you can use the cleanup function. The cleanup function is a callback function called before the next effect starts or when the relevant effect is destroyed:</p><pre>effect((onCleanup) =&gt; {<br>  console.log(&quot;Current value of x: ${this.x()}&quot;);<br>  const timer = setTimeout(() =&gt; {<br>    console.log(&quot;Processing...&quot;);<br>  }, 2000);<br>  onCleanup(() =&gt; {<br>    clearTimeout(timer);<br>  });<br>});</pre><p>The cleanup function ensures that previous effects are destroyed when a new one is fired. Finally, if you want to prevent any effects from being triggered when the value of a signal changes, you can use the untracked”function. Code within the untracked function will not be considered as a dependency by effects:</p><pre>effect(() =&gt; {<br>  console.log(&quot;Current value of x: ${this.x()}&quot;);<br>  untracked(() =&gt; {<br>    this.y.update((data) =&gt; data + 1);<br>    console.log(&quot;Current value of y: ${this.y()}&quot;);<br>  });<br>});</pre><p>In the code above, the untracked function ensures that the operations it contains will not create dependencies for effects. Therefore, the “y” signal’s value will only trigger the effect when the “x” signal’s value changes.</p><h4>Derived Signals</h4><p>Derived signals are signals that are derived from one or more source signals using various transformation operations. These operations can include arithmetic operations, filtering, mapping, and more.</p><p>Here’s an example of creating derived signals:</p><pre>import { signal, computed, filter } from &#39;@angular/core&#39;;<br><br>let x = signal(5);<br>let y = signal(10);<br><br>// Create a computed signal that multiplies x and y<br>let multiplied = computed(() =&gt; x() * y());<br><br>// Create a filtered signal that only emits even numbers<br>let even = filter((value) =&gt; value % 2 === 0, multiplied);<br><br>console.log(multiplied()); // 50<br>console.log(even()); // 10<br><br>x.set(3);<br>console.log(multiplied()); // 30<br>console.log(even()); // No change, still 10</pre><h4>Batching Changes</h4><p>Signals offer a built-in way to batch changes, which can be useful when you want to perform multiple updates to signals without triggering multiple change detection cycles.</p><p>You can use the batch() function to group multiple changes together:</p><pre>import { signal, batch } from &#39;@angular/core&#39;;<br><br>let x = signal(10);<br>let y = signal(0);<br><br>batch(() =&gt; {<br>  x.set(30);<br>  y.set(40);<br>});<br><br>// Change detection will only run once for both updates</pre><p>In this example, the x and y signals are updated within a batch function. This ensures that change detection runs only once for both updates, improving performance when making multiple changes in succession.</p><h4>RxJS Interop</h4><p>In Angular 16, there are functions in the @angular/core/rxjs-interop path, namely toSignal and toObservable for transforming observables into signals and vice versa. Both functions should be used at the constructor level. Using them elsewhere may result in errors.</p><p><strong>toSignal Function</strong></p><p>The toSignal function allows you to transform an observable object into a read-only signal (meaning it has a Signal reference).</p><pre>export class AppComponent {<br>  constructor() {<br>    effect(() =&gt; console.log(&quot;Value of the counter signal: ${this.counter()}&quot;));<br>  }<br>  counter$ = interval(1000);<br>  counter = toSignal(this.counter$);<br>}</pre><p>As seen in the example above, an observable with a 1-second interval is created, and the toSignal function is used to transform it into a signal. Consequently, the value of the counter signal will change every second, triggering the effect function accordingly.</p><p>It’s important to note that the toSignal function will immediately subscribe to the observable. This behavior can lead to unintended side effects in some cases.</p><p>Additionally, observables do not have an initial value by default. Therefore, when using the toSignal function, you may want to provide an initial value to the resulting signal using the initialValue property:</p><pre>export class AppComponent {<br>  constructor() {<br>    effect(() =&gt; console.log(&quot;Value of the counter signal: ${this.counter()}&quot;));<br>  }<br>  counter$ = interval(1000);<br>  counter = toSignal(this.counter$, { initialValue: 999 });<br>}</pre><p>Alternatively, you can provide an initial value to the resulting signal if the source observable immediately emits data by setting the requiresSync property to true:</p><pre>export class AppComponent {<br>  constructor() {<br>    effect(() =&gt; console.log(&quot;Value of the counter signal: ${this.counter()}&quot;));<br>  }<br>  counter$ = interval(1000);<br>  counter = toSignal(this.counter$, { requiresSync: true });<br>}</pre><p>Finally, if a transformed observable using the toSignal function does not immediately emit data, Angular will throw an error. To resolve this issue, you can provide an initial value to the source observable, as shown below:</p><pre>export class AppComponent {<br>  constructor() {<br>    effect(() =&gt; console.log(&quot;Value of the counter signal: ${this.counter()}&quot;));<br>  }<br>  counter$ = interval(1000).pipe(startWith(0));<br>  counter = toSignal(this.counter$, { requiresSync: true });<br>}</pre><p><strong>toObservable Function</strong></p><p>The toObservable function is used to transform a signal into an observable object. Here’s an example of how it can be used:</p><pre>count: WritableSignal&lt;number&gt; = signal(1);<br>count$ = toObservable(this.count);<br><br>increment() {<br>  setTimeout(() =&gt; {<br>    this.count.update((data) =&gt; data + 1);<br>    this.increment();<br>  }, 1500);<br>}<br><br>ngOnInit() {<br>  this.increment();<br>  this.count$.subscribe((data) =&gt; console.log(data));<br>}</pre><p>In this example, the count signal is transformed into an observable, and the increment function continuously updates the signal’s value. The ngOnInit function subscribes to the observable and logs its values.</p><h4>Benefits of Using Signals</h4><p>Now that you have an understanding of what signals are and how to use them, let’s explore some of the benefits of using signals in Angular applications:</p><ol><li><strong>Reactivity: </strong>Signals provide a more reactive way to work with data in Angular. You can easily track changes and react to them without relying solely on Angular’s change detection.</li><li><strong>Performance: </strong>Signals can lead to better performance in your Angular applications. By tracking changes at a granular level, you can minimize unnecessary re-renders and improve the overall efficiency of your app.</li><li><strong>Simplified Code:</strong> Signals can simplify your code by reducing the need for complex change detection strategies and event handling. This can make your codebase cleaner and easier to maintain.</li><li><strong>Independence from Zone.JS: </strong>Signals work independently of Zone.JS, which can be advantageous in scenarios where you want more control over change detection or when working with libraries that don’t play well with Zone.JS.</li><li><strong>Efficient State Management: </strong>Signals can be used for state management within your Angular components. You can create signals for different pieces of state and easily compose them to derive new state values.</li><li><strong>Batching Changes: </strong>Signals provide a built-in mechanism for batching changes, which can be useful when you need to make multiple updates to signals in a single operation, reducing unnecessary change detection cycles.</li></ol><h4>Conclusion</h4><p>Signals provide a powerful and efficient way to handle data reactivity and state management in Angular applications. By offering fine-grained control over change detection and updates, signals can help you create more responsive and performant Angular components.</p><p>While signals offer these advantages, it’s essential to consider your specific use case and project requirements when deciding whether to use signals in your Angular application. Signals can be a powerful tool, particularly in scenarios where fine-grained reactivity and performance optimizations are crucial.</p><p>Whether you choose to use signals for your entire application or for specific components, understanding how to work with signals and their associated functions can be a valuable addition to your Angular development toolkit. Experiment with signals in your projects to see how they can simplify your code, improve reactivity, and boost the overall performance of your Angular applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20875d9cac27" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What happened in Moq library: A Blog on Controversies]]></title>
            <link>https://medium.com/@atakankorez/what-happened-in-moq-library-a-blog-on-controversies-832629a125ef?source=rss-5368f4ac89d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/832629a125ef</guid>
            <category><![CDATA[dot-net-framework]]></category>
            <category><![CDATA[test-driven-development]]></category>
            <category><![CDATA[mocking]]></category>
            <category><![CDATA[moq]]></category>
            <category><![CDATA[unit-test-framework]]></category>
            <dc:creator><![CDATA[Atakan Korez]]></dc:creator>
            <pubDate>Sun, 24 Sep 2023 18:46:09 GMT</pubDate>
            <atom:updated>2023-09-24T18:46:09.533Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/280/1*lJGGXgxa43J5OOUtvH0I3A.png" /></figure><p>Mocking is one of the methods used by the popular software methodology Test Driven Development(TDD) and unit tests in particular to isolate the system they test. These methods can be broadly defined as test doubles.</p><p><a href="https://github.com/devlooped/moq"><strong>Moq</strong></a> is a most popular mocking library that we can use to write unit tests on the .Net side. It allows us to test cases in our normal project by producing fake objects for our tests.</p><h4>Problem</h4><p><a href="https://www.cazzulino.com/"><em>Daniel Cazzulino</em></a>, the author of the Moq library, introduced an application called<strong><em> </em></strong><a href="https://github.com/devlooped/SponsorLink"><strong>Sponsorlink</strong></a><strong> </strong>and he<em> </em>integrated it<em> </em>into the Moq 4.20 version. It turned out that Sponsorlink, which was added in version 4.20, stores mail on Azure without users’ consent is a critical security vulnerability. (for details: <a href="https://github.com/devlooped/moq/issues/1372#issuecomment-1670344399">https://github.com/devlooped/moq/issues/1372#issuecomment-1670344399</a>)</p><h4><strong>What is SponsorLink?</strong></h4><p>In essence, SponsorLink is an initiative to encourage developers to financially support their fellow developers who produce valuable open-source tools. By embedding SponsorLink in a library, developers can send gentle reminders to their users about the possibility of sponsorship, straight within the development environment, like Visual Studio or Rider (SponsorLink blog <a href="https://www.cazzulino.com/sponsorlink.html">post</a>)</p><h4><strong>How does Sponsorlink work?</strong></h4><p>The operation seems straightforward at first glance:</p><ol><li>If a developer is using an editor and there’s network connectivity, SponsorLink runs git config --get user.email during the build to retrieve the developer’s configured email.</li><li>This email (hashed and encoded, not in its raw form) is then used to check if the developer has installed the SponsorLink GitHub app (this happens using an HTTP call to Azure).</li><li>Further, it checks if the developer is sponsoring the particular open-source project.</li><li>If the developer isn’t sponsoring, they’re offered links to install the app and then sponsor the account.</li></ol><h4><strong>The impact of Sponsorlink</strong></h4><p>This is a huge privacy breach. If you use this library, your e-mail will be processed without your consent on Azure service.</p><p>If you are not a sponsor or the check fails, you will receive a warning, that will break your build if you have TreatWarningsAsErrors set to true.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*OFZigRD2hlBm1tx35Z-BCw.png" /></figure><p>Moreover, if you are stationed in the EU, this is a violation of GDPR, because e-mail is considered personally identifiable information, and you didn’t opt into having your e-mail read and sent, and there’s no opt-out option.</p><h4><strong>Is this security vulnerability still here?</strong></h4><p>The changes which are related to Sponsorlink were reverted in 4.20.2. However, the reason for reverting it is not the breach of GDPR, but rather the malware (that’s an accurate technical term for this change) not working on MacOS and Linux machines. That means the author may add these changes back once issues are resolved. For details: <a href="https://github.com/devlooped/moq/pull/1375">https://github.com/devlooped/moq/pull/1375</a></p><p>So, when it comes to the question: Sponsorlink is not currently on Moq, but it doesn’t mean it won’t be back. For details: <a href="https://github.com/devlooped/moq/issues/1374">https://github.com/devlooped/moq/issues/1374</a></p><h4><strong>Is it safe for us to continue using Moq (with a version higher than 4.20)?</strong></h4><p>In my opinion, if possible, we should remove the Moq library from all our projects. A great alternative is <a href="https://nsubstitute.github.io/"><strong>NSubstitute</strong></a><strong> </strong>or <a href="https://github.com/hassanhabib/CleanMoq"><strong>Clean </strong>Mock</a> which is forked from the Moq repo (if you don’t want to do a lot of code stuff).</p><h4>Final Thoughts</h4><p>Although it seems like an extreme measure, it may be necessary in the long run, because the author did not express any intent not to re-add the dependency in the future. Simply having such changes merged and released <strong>intentionally</strong> is well more than enough to lose all trust in that package and its author.</p><p>I am going to use a previous version of Moq and consider moving to <strong>NSubstitute</strong>, depending on how the situation develops. While I continue to value <strong>Moq </strong>as a library we’ve relied on for years, I remain hopeful that our community can work towards rebuilding trust.</p><blockquote>I would like to end the blog by stating that I am working on a blog that explains how to implement <strong>HttpClient</strong>(HttpMessageHandler) and <strong>Logging</strong>(<em>ILogger</em>), which are quite complex operations of <strong>Moq</strong>, with <strong>NSubstitute</strong>. It will be a nice blog, stay tuned.</blockquote><p>If you found this blog post helpful, please give it a clap. Thanks for reading…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=832629a125ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[S.O.L.I.D: A Superheroes Story]]></title>
            <link>https://medium.com/@atakankorez/s-o-l-i-d-a-superheroes-story-182d868a3aa5?source=rss-5368f4ac89d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/182d868a3aa5</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[oop-concepts]]></category>
            <category><![CDATA[efficient-programming]]></category>
            <category><![CDATA[solid]]></category>
            <category><![CDATA[best-practices]]></category>
            <dc:creator><![CDATA[Atakan Korez]]></dc:creator>
            <pubDate>Sun, 17 Sep 2023 20:01:16 GMT</pubDate>
            <atom:updated>2023-09-17T20:01:16.564Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i5hBxV1oNZePMFWaYd3vRQ.png" /></figure><p>This blog post is a story on how superheroes can save your code from becoming a supervillain’s lair of confusion and chaos. It is aimed at software engineers but should be understandable for non-software engineers as well. The goal is to give everyone a high-level understanding of <em>SOLID </em>principles.</p><h4><strong>What is Object Oriented Programming(OOP)?</strong></h4><p>It is an approach to designing modular reusable software systems which should lead to. Of course, there’s much more to OOP than I just told. Think about fundamental concepts like dynamic dispatching, encapsulation, polymorphism, inheritance, and open recursion, but this is not a session on OOP itself but about <em>SOLID</em>.</p><blockquote><em>Dynamic dispatching = Class animal -&gt; Classes Elephant, Lion, Tiger all inherit from Animal. Only at runtime, the implementation of an overridden method will be determined.</em></blockquote><blockquote>Open recursion = This/Self/Me keywords. Call a method on your own object, so the method could be overridden by any child. Goes hand-in-hand with dynamic dispatching.</blockquote><h4><strong>S.O.L.I.D Principles</strong></h4><p>The letters themselves stand for 5 principles which in turn are:</p><blockquote>S — Single Responsibility Principle (SRP)</blockquote><blockquote>O — Open/Close Principle (OCP)</blockquote><blockquote>L — Liskov Substitution Principle (LSP)</blockquote><blockquote>I — Interface Segregation Principle (ISP)</blockquote><blockquote>D — Dependency Inversion Principle (DIP)</blockquote><p>Let’s dive into these principles!</p><h4><strong>Single Responsibility Principle</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*le8d9Ym4KXO9su8dAxsczA.jpeg" /></figure><p>Just like the villains all want to get a piece of Spiderman the functionalities would like to be incorporated into a single class which will grow out of its jacket.</p><p>Therefore, the SRP states that a class should have only a single reason to change. This responsibility should be entirely encapsulated by the class. The services of the class should be narrowly aligned with that responsibility.</p><blockquote>Goals are; Short and concise objects, testability, readability, and maintainability.</blockquote><pre>public class BatMan<br>{<br>   public void FightVillain(Villain villain)<br>   {<br>      // Some fighting going on<br>      RequestHelp(villain);<br>   }<br><br>   private void RequestHelp(Villain villain)<br>   {<br>      // Which superhero has the power to fight this villain?<br>      // Which superhero isn&#39;t currently occupied?<br>      // Reach out to superhero<br>      new SuperheroHotline().RequestHelp(villain);<br>   }<br>}</pre><h4>Open/Closed Principle</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*iFlZ4yQs-QU3DH80agliFA.jpeg" /></figure><p>As we can see in the picture Clark Kent does not change (closed) until we put a phone booth in his way then he becomes Superman (open).</p><p>This is the whole idea of OCP. Classes we create should be closed for modification, but open for extension.</p><blockquote>Goal: Every time we modify an existing class, we are potentially breaking our application as it can introduce bugs and errors; even in other parts of our application.</blockquote><pre>//-----------BEFORE------------------<br>public class BatMan<br>{<br>   public void FightVillain(Villain villain)<br>   {<br>      var vehicle = GetVehicle(villain.terrain);<br>      // Some fighting going on<br>   }<br><br>   private BatVehicle GetVehicle(Terrain terrain)<br>   {<br>      if (terrain == Terrain.Air)<br>      {<br>         return BatVehicle.Batplane;<br>      } else if (terrain == Terrain.Water) <br>      {<br>         return BatVehicle.Batboat;<br>      }<br>      return BatVehicle.Batmobile;<br>   }<br>}<br><br>//------------AFTER------------------<br>public class BatMan<br>{<br>   public void FightVillain(Villain villain)<br>   {<br>      var vehicle = GetVehicle(villain.terrain);<br>      // Some fighting going on<br>   }<br><br>   private BatVehicle GetVehicle(Terrain terrain)<br>   {<br>      return BatVehicles.GetVehicle(terrain);<br>   }<br>}</pre><h4>Liskov Substitution Principle</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*B8262U08ISzlIFHcp1iI5Q.jpeg" /></figure><p>As we can see in the above picture, we should be able to trust either the black man on the left or the white girl on the right as they both have superpowers like Superman. In other words, do we care whether the superhero is black/white, male/female, adult/child or do we care that the superhero saves us?</p><p>For this reason, LSP states that any child class should only extend or modify behavior defined in the parent class, NOT introduce new behavior.</p><blockquote>Goal: The parent/child relationship should be in the form of ‘Is substitutable for’ instead of the ‘is a’ kind.</blockquote><pre>//-----------BEFORE------------------<br>public class SuperHero {<br>   public virtual void UsePower() { // We&#39;re using some super power }<br>}<br><br>public class Batman: SuperHero {<br>   public override void UsePower() { // We&#39;re using batarangs }<br>}<br><br>public class Superman : SuperHero {<br>   public override void UsePower() { // We&#39;re using laser eyes }<br>   public void Fly() { // I believe I can fly }<br>}<br><br>public class SuperHero {<br>   public virtual void UsePower() { // We&#39;re using some super power }<br>}<br><br>public class Batman : SuperHero {<br>   public override void UsePower() { // We&#39;re using batarangs }<br>}<br><br>public class Superman : SuperHero {<br>   public override void UsePower() { // We&#39;re using laser eyes while flying }<br>}<br><br>//------------AFTER------------------<br>public interface IPowerable<br>{<br>   void UsePower();<br>}<br>public interface IFlyable<br>{<br>   void Fly();<br>}<br><br>public class Batman : IPowerable {<br>   public void UsePower() { // We&#39;re using batarangs }<br>}<br><br>public class Superman : IPowerable, IFlyable {<br>   public void UsePower() { // We&#39;re using laser eyes while flying }<br>   public void Fly() { // I believe I can fly }<br>}</pre><p>Even combinations are possible, e.g.:</p><p>— In base class, we define virtual methods which are applicable to all superheroes.</p><p>— We have some interfaces applicable to only some of the superheroes.</p><p>— This way you can substitute superheroes on base and child levels for the functionality that is applicable to all and use specific powers for some of them.</p><h4>Interface Segregation Principle</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*mfIFc9VM5ne3CLnCNgkdLg.jpeg" /></figure><p>While Batman wears a cape and Superman wears a cape does this mean that we should force Spiderman to wear a cape too?</p><p>This is exactly what ISP is about. We should not force clients to implement methods that they do not use. Therefore, it is better to create more (or even many) small interfaces than to create a few big interfaces.</p><blockquote>Goal: Increase flexibility and maintainability, decrease dependencies</blockquote><pre>//----------- BEFORE----------------<br>public interface ISuperhero <br>{<br>   void UseSuperPowers();<br>   void DateCatwoman();<br>}<br><br>public class Batman : ISuperhero <br>{<br>   public void UseSuperPowers() { // I&#39;m using all my superpowers }<br>   public void DateCatwoman() { // Having the time of my life }<br>}<br><br>public class Superman : ISuperhero <br>{<br>   public void UseSuperPowers() { // I&#39;m using all my superpowers }<br>   public void Datecatwoman() { // My friend will not like this }<br>}<br><br>//------------AFTER--------------------<br>public interface ISuperhero <br>{<br>   void UseSuperPowers();<br>}<br>public interface IDateCatwoman<br>{<br>   void DateCatwoman();<br>}<br><br>public class Batman : ISuperhero, IDateCatwoman<br>{<br>   public void UseSuperPowers() { // I&#39;m using all my superpowers }<br>   public void DateCatwoman() { // Having the time of my life }<br>}<br><br>public class Superman : ISuperhero <br>{<br>   public void UseSuperPowers() { // I&#39;m using all my superpowers }<br>}</pre><p>Superman.DateCatwoman will likely be implemented using a NotImplementedException.</p><h4>Dependency Inversion Principle</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*0z21NOXr4DEe2l4jzLc5GA.jpeg" /></figure><p>If supervillains threaten our way of living would we really care if The Avengers, The X-Men, The Fantastic Four, or The Justice League would come to our rescue?</p><p>This is what DIP is about. Do not depend on concrete implementations, rather decouple code and depend on abstractions.</p><blockquote>Goal: Take away dependencies between objects. Easier to test. Easier to substitute one implementation with another.</blockquote><pre>//----------- BEFORE----------------<br>public class Batman {<br>   public void FightCrime() { // I&#39;m fighting all crime in Gotham City }<br>}<br><br>public class Joker {<br>   public void CauseMayhem() { // I&#39;m causing all kinds of mayhem in Gotham City }<br>}<br><br>public class CrimeFighter {<br>   public CrimeFighter() {<br>      Batman batman = new Batman();<br>      Joker joker = new Joker();<br><br>      joker.CauseMayhem();<br>      batman.FightCrime();<br>   }<br>}<br>//------------AFTER--------------------<br>public interface ISuperhero { void FightCrime(); }<br>public interface IVillain { void CauseMayhem(); }<br><br>public class Batman : ISuperhero {<br>   public void FightCrime() { // I&#39;m fighting all crime in Gotham City }<br>}<br><br>public class Joker : IVillain {<br>   public void CauseMayhem() { // I&#39;m causing all kinds of mayhem in Gotham City }<br>}<br><br>public class CrimeFighter {<br>   public CrimeFighter(ISuperhero hero, IVillain villain) {<br>      villain.CauseMayhem();<br>      hero.FightCrime();<br>   }<br>}</pre><p>With the DIP implementation, we can simply replace Batman &amp; Joker with Superman &amp; Lex Luthor without having to change these existing classes (so it also adheres to OCP).</p><h4>Conclusion</h4><p>Now you understand a little bit of what <em>SOLID</em> is all about. It gives you the tools to create software that is more maintainable, modular, extensible, testable, and reusable. Applied correctly it can lead to a reduction in long-term maintenance costs.</p><p>Remember, like most other things, <em>SOLID </em>is not a silver bullet to use for every situation. It is just another tool in your toolbox. Properly understanding these principles will empower you to make informed design decisions and create high-quality superhero-worthy software. May <em>SOLID </em>be your companion on your coding adventures…</p><p>If you found this blog post helpful, please give it a clap. Thanks for reading…</p><blockquote>This article has been prepared by taking advantage of my colleague Eddie Terlouw’s SOLID training. I owe him my thanks…</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=182d868a3aa5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Effective But Little-Known Way to Optimize SQL Server Queries]]></title>
            <link>https://medium.com/@atakankorez/an-effective-but-little-known-way-to-optimize-sql-server-queries-990c4155a2ef?source=rss-5368f4ac89d2------2</link>
            <guid isPermaLink="false">https://medium.com/p/990c4155a2ef</guid>
            <category><![CDATA[indexing]]></category>
            <category><![CDATA[database-development]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[performance-improvement]]></category>
            <category><![CDATA[sql-server]]></category>
            <dc:creator><![CDATA[Atakan Korez]]></dc:creator>
            <pubDate>Mon, 04 Sep 2023 20:16:16 GMT</pubDate>
            <atom:updated>2023-09-04T20:16:16.208Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bhZlm07BfZdXaxIxgVOeNg.png" /></figure><p>SQL Server queries are essential for accessing and manipulating data in a database. However, queries can sometimes be slow and inefficient. This can be due to a number of factors, such as the way the query is written, the size of the database, or the hardware configuration.</p><p>There are a number of ways to optimize this kind of SQL Server queries. One of the most effective ways is to use <strong>indexes.</strong> Indexes are data structures that improve the performance of queries by helping the database engine find the data it needs more quickly. However, it can be difficult to determine whether an index will actually improve performance before creating it. To be honest, this is time-consuming and error-prone.</p><p>Fortunately, in order to solve this problem, I will introduce you to a structure that has existed since the SQL Server 2005 version. Here are <strong>Hypothetical Indexes</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*GLFKjrs-l69OuP21XBEy2g.gif" /></figure><p><strong>What are Hypothetical Indexes?</strong></p><p>Hypothetical indexes are a way to test the performance of an index without actually creating it. They are created using the CREATE INDEX statement with the WITH STATISTICS clause.</p><p>To create a hypothetical index, follow these steps:</p><ol><li>Select the table.</li><li>Select the columns you want to create the index on.</li><li>Use the WITH STATISTICS_ONLYclause.</li></ol><p>For example, the following command creates a hypothetical index on the product_id and product_name columns in the products table:</p><pre>CREATE INDEX hypothetical_index<br>ON products (product_id, product_name)<br>WITH STATISTICS_ONLY</pre><p>To analyze the results of hypothetical indexes, you can use the SET STATISTICS IO ON and SET STATISTICS TIME ON commands. These commands will collect statistics about the execution of the query plan, including the number of rows read from the database and the amount of time it took to execute the query.</p><p>For example, the following command analyzes the performance of a query that uses a hypothetical index to retrieve a record from the products table:</p><pre>SET STATISTICS IO ON;<br>SET STATISTICS TIME ON;<br><br>SELECT *<br>FROM products<br>WHERE product_id = 1;</pre><p>The results of these commands will show you how many rows were read from the database and how long it took to execute the query. You can then compare these results to the results of the same query without the hypothetical index to see if the index improved performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*K9jz8ocBWIEZoQ2sBY4ouQ.gif" /></figure><p><strong>Pros and Cons of Hypothetical Indexes</strong></p><p>There are several advantages to using hypothetical indexes:</p><ul><li>They allow you to test performance before creating the index.</li><li>They allow you to compare the performance of different index designs.</li><li>They reduce the impact of index creation on performance.</li></ul><p>Given the inherent nature of life’s blessings entailing a cost, Hypothetical Indexes, too, bear its own set of drawbacks.</p><ul><li>They do not actually create the index, so they do not actually improve performance.</li><li>They can be somewhat complex to use.</li><li>They can be difficult to debug.</li></ul><p><strong>Conclusion</strong></p><p>Hypothetical indexes are a powerful tool for performance tuning, but they should not be used as a replacement for manual index creation. They should be used to test the performance of different index designs and to find the best index for a particular query. Here are some additional tips for using hypothetical indexes:</p><ul><li>Use hypothetical indexes to test the performance of queries that you are considering making changes to.</li><li>Use hypothetical indexes to compare the performance of different index designs.</li><li>Use hypothetical indexes to test the impact of index fragmentation on performance.</li></ul><p>By following these tips, you can use hypothetical indexes to improve the performance of your SQL Server queries.</p><p>If you found this blog post helpful, please give it a clap. Thanks for reading…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=990c4155a2ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>