<?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 Buse Nur Şahin on Medium]]></title>
        <description><![CDATA[Stories by Buse Nur Şahin on Medium]]></description>
        <link>https://medium.com/@busenursahin?source=rss-67c9aefc0c68------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Nr0vRcgU4jdI74la_H-Z6Q.png</url>
            <title>Stories by Buse Nur Şahin on Medium</title>
            <link>https://medium.com/@busenursahin?source=rss-67c9aefc0c68------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 06:24:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@busenursahin/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[Enabling Project Expansion by Generating Classes and DLLs at Runtime with .Net Core]]></title>
            <link>https://busenursahin.medium.com/enabling-project-expansion-by-generating-classes-and-dlls-at-runtime-with-net-core-2c9bc36c8cc9?source=rss-67c9aefc0c68------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c9bc36c8cc9</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Buse Nur Şahin]]></dc:creator>
            <pubDate>Thu, 26 Dec 2024 13:08:59 GMT</pubDate>
            <atom:updated>2024-12-26T13:10:09.859Z</atom:updated>
            <content:encoded><![CDATA[<h3>Enabling Project Expansion by Generating Classes and DLLs at Runtime with .Net Core</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*P3FUQ02Tbe99pXSG" /><figcaption>Photo by <a href="https://unsplash.com/@n_claudia?utm_source=medium&amp;utm_medium=referral">clau alexa</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Let’s assume that we have different payment methods, log types, in short, operation classes that implement the same interface in our project, and when we add a new operation type (for example, class type) from the data source (with a db-first-like approach), how can the project continue to work by expanding without the need for change?</p><p>I would like to share with you how I approached such a need, what problems I encountered and how I found a solution.</p><h4>Scenario</h4><p>We use different payment methods in our project and we want to have a code structure that can adapt to new payment method integration without resistance.</p><p>We want the relevant classes to be created automatically for the payment types we read from the data source without the need to change the project code, and after the classes are created, we want to add the relevant dll files at runtime without the need to recompile, and we want the classes created to meet the requirements of the relevant interface.</p><h3>Demo</h3><h4>Payment Types Table</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VIbYeb3M4yzeF4IM" /></figure><h4>Payment method selection screen</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EpfqYLKp_aqgXdu6" /></figure><p>Let’s run it again by adding a new payment type to the data source without making any changes in the project code.</p><h4>Payment Types Table</h4><p>After adding new payment system</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*T9weYBUE9i_PpLzF" /></figure><h4>Payment method selection screen</h4><p>After adding new payment system</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gBP2RfXXQPklgBMR" /></figure><h4>Test</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mBRSWjo_0otdSBjD" /></figure><h4>The test passed, so what happened?</h4><p>Since the Select Box already reads the data from the data source, the newly added payment method is immediately selectable, so how was the class of the new payment system created and a method of that class can be executed?</p><h4>Classes Generated at Runtime</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/0*-s2WPnn16sjx3335" /></figure><h4>DLL files generated in Runtime</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/0*AxjnpsSohPmiLFYw" /></figure><h4>Code Structure</h4><p>The code structure was created in accordance with the open-closed principle.</p><pre>public interface IPayment<br>{<br>    string Pay(int amount);<br>}</pre><p>Since we want to build an extensible code structure, we have a payment methods interface and payment methods use this interface.</p><pre>public class CreditCardManager : IPayment<br>{<br>    public string Pay(int amount)<br>    {<br>        return $&quot;paid by Credit Card amount: {amount}&quot;;<br>    }<br>}</pre><p>We can think of the above code fragment as an example of a payment method class that we foresee that we will use in the project.</p><pre>public class PaymentService<br>{<br>    private readonly IPayment _payment;<br>    public PaymentService(IPayment _payment)<br>    {<br>        _payment = payment;<br>    }<br><br>    public string Pay(int amount)<br>    {<br>        return _payment.Pay(amount);<br>    }<br>}</pre><p>In the code above, we created the class where we can access the payment method classes with dependency-injection.</p><h4>Data Source</h4><pre>public class PaymentType<br>{<br>    public int Id { get; set; }<br>    public string Title { get; set; }<br>    public string ClassName { get; set; }<br>}</pre><p>The code above is the payment type model. Using this model you can provide data with any ORM or ADO.NET or with your own static elements. The ClassName attribute in this model will be the name of the manager class we will create and the Title field will provide a user-friendly text on the Payment Type selection screen so that we do not need to change the part we present to the user.</p><h4>Class Generation</h4><pre>public class ClassGenerator<br>{<br>    public void GenerateClass(string className)<br>    {<br>        using (StreamWriter writer = new StreamWriter($&quot;{Constants.GeneratedFolder}/{className}.cs&quot;))<br>        {<br>            writer.WriteLine(&quot;using System;&quot;);<br>            writer.WriteLine(&quot;using System.Collections.Generic;&quot;);<br>            writer.WriteLine(&quot;using ProjectName.Abstract;&quot;);<br>            writer.WriteLine(&quot;using System.ComponentModel.DataAnnotations;&quot;);<br>            writer.WriteLine(&quot;using System.Linq;&quot;);<br>            writer.WriteLine(&quot;using System.Text;&quot;);<br>            writer.WriteLine(&quot;using System.Threading.Tasks;&quot;);<br>            writer.WriteLine(&quot;namespace ProjectName.Concrete;&quot;);  //namespace adını düzenlememiz gerekiyor.<br>            writer.WriteLine($&quot;public class {className} : IPayment&quot;);<br>            writer.WriteLine(&quot;{&quot;);<br>            writer.WriteLine(&quot;public string Pay(int amount)&quot;);<br>            writer.WriteLine(&quot;{&quot;);<br>            writer.WriteLine($&quot;return $\&quot;paid by {className} &quot; + &quot;amount:{amount}\&quot;;&quot;);<br>            writer.WriteLine(&quot;}&quot;);<br>            writer.WriteLine(&quot;}&quot;);<br>        }<br>    }<br>}</pre><p>We will create a Helper Class called ClassGenerator and manage file creation and writing to the file through this method.</p><p>Note: Here it is obvious that the method content can vary significantly according to a payment method, but it can still be thought that after the code is created, the code in the method will be integrated into the payment method without taking the code in the method via input and deploying it.</p><pre>public void CreatePaymentManagerClassFromDb()<br>    {<br>        ClassGenerator classGenerator = new ClassGenerator();<br><br>        foreach (PaymentType paymentType in GetPaymentTypes())<br>        {<br>            classGenerator.GenerateClass(paymentType.ClassName);<br>        }<br>    }</pre><p>For each row (each data in the list) that we read using this method, we can use the namespace defined with the namespace we edited in the ClassGenerator class.</p><pre>&quot;namespace ProjectName.Concrete;&quot;</pre><pre>$&quot;{your_folder}/{className}.cs&quot;</pre><p>We will create the relevant class file in the location specified by the folder information.</p><h4>Creating an Object from a Class with Reflection</h4><pre>public class PaymentFactory<br>{<br>  <br>    public IPayment GetInstance(string className)<br>    {<br>        string assembly = $&quot;ProjectName.Concrete.{className}&quot;;<br>        return (IPayment) System.Reflection.Assembly.GetAssembly(typeof(IPayment)).CreateInstance(assembly);<br>    }<br>}</pre><p>In this code fragment we used factory-design-pattern.</p><p>Our goal is to get an instance of the given class type by calling the GetInstance method of the factory class, not with the new() keyword when creating an object from the payment method classes. This way we can create a dynamic structure.</p><p>We use the Reflection structure to get the object created by giving the class name.</p><p>Now we can run the project without getting an error at compile time, but we will get an error at runtime.</p><p>When PaymentFactory/GetInstance method runs, while the project is being built under the relevant namespace, since there is no such class (for example MailOrder.cs) yet, there is no assembly information of this class, so it will return null and the related object will not be created in Reflection. How can we solve this?</p><h4>Runtime DLL creation (Roslyn)</h4><p>At this stage, we can use AssemblyBuilder or CsharpCodeProvider with .NET Framework to generate DLLs from code fragments at runtime, but since these methods are not yet fully compatible with .NET Core, we will use Roslyn compiler. See: <a href="https://github.com/dotnet/roslyn">https://github.com/dotnet/roslyn</a></p><p>Although the project codes remain the same in general, we will need to create a DLL and include it in the project before creating an instance. For this, we will make a few edits in the PaymentFactory class.</p><pre>using Microsoft.CodeAnalysis;<br>using Microsoft.CodeAnalysis.CSharp;<br>using Microsoft.CodeAnalysis.Emit;</pre><p>The packages we will use for this operation are in the code fragment above.</p><h4>We rewrite the GetInstance method</h4><pre>string classFilePath = $&quot;{your_folder}/{className}.cs&quot;;<br>string code = File.ReadAllText(classFilePath);<br>SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(code);</pre><p>We read the relevant code file, get the code fragment and parse this code fragment into a SyntaxTree object.</p><pre>var references = AppDomain.CurrentDomain.GetAssemblies(<br>.Where(a =&gt; !a.IsDynamic &amp;&amp; !string.IsNullOrEmpty(a.Location))<br>.Select(a =&gt; MetadataReference.CreateFromFile(a.Location));)</pre><p>Since the newly generated class uses the IPayment interface, it will give an error if it does not have the relevant references when we compile it, we get the project references in the above code fragment.</p><pre>CSharpCompilation compilation = CSharpCompilation.Create(<br>     $&quot;DynamicAssembly-{className}.dll&quot;,<br>     new[] { syntaxTree },<br>     references,<br>     new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)<br>);</pre><p>With this code, it compiles the related class by giving references.</p><pre>DynamicAssembly-{className}.dll</pre><p>so that we create a separate DLL for each class and avoid getting errors or file squashing by creating a dynamic name.</p><pre>EmitResult result = compilation.Emit($&quot;DynamicAssembly-{className}.dll&quot;);</pre><p>We use this code fragment to include the DLL in the project and get an instance of the related class.</p><pre>if (result.Success)<br>{<br>    Console.WriteLine($&quot;DLL generated: DynamicAssembly-{className}.dll&quot;);<br>}<br>else<br>{<br>    Console.WriteLine(&quot;Derleme hatası:&quot;);<br>    foreach (var diagnostic in result.Diagnostics)<br>    {<br>        Console.WriteLine(diagnostic);<br>    }<br>}</pre><p>In this way we do error management and we get the output “DLL generated” when the dll is generated.</p><h4>Generating Instance with Reflection after DLL creation</h4><pre>Assembly dynamicAssembly = Assembly.LoadFrom($&quot;DynamicAssembly-{className}.dll&quot;)<br><br>string namespaceName = &quot;ProjectName.Concrete&quot;;<br>string fullClassName = namespaceName != null ? $&quot;{namespaceName}.{className}&quot; : className;<br><br>Type myClassType = dynamicAssembly.GetType(fullClassName);<br><br>IPayment instance = (IPayment)Activator.CreateInstance(myClassType);<br>return instance;With the above code fragment, we create an object of type IPayment by loading the DLL and taking the class type in the DLL.</pre><p>With the above code fragment, we create an object of type IPayment by loading the DLL and taking the class type in the DLL.</p><p>Now, when there is a change in the data source, we can extend the project without the need to change the project code (except for specific implementation) and without the need to recompile the project after the relevant classes are generated.</p><p>You can access the code I wrote for the Log Types scenario with a similar approach <a href="https://github.com/busenursahin/autolog2">here</a>.</p><p>Thank you for reading</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c9bc36c8cc9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automating a .Net MVC That Uses an API]]></title>
            <link>https://busenursahin.medium.com/automating-a-net-mvc-that-uses-an-api-26611a758451?source=rss-67c9aefc0c68------2</link>
            <guid isPermaLink="false">https://medium.com/p/26611a758451</guid>
            <category><![CDATA[mvc]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Buse Nur Şahin]]></dc:creator>
            <pubDate>Thu, 09 May 2024 07:04:28 GMT</pubDate>
            <atom:updated>2024-05-09T07:38:49.525Z</atom:updated>
            <content:encoded><![CDATA[<h3>Automating the use of APIs with .NET</h3><p>How can we automate converting a JSON object from an existing API source into a C# model? How can we automatically create the HttpClient class that this model will use to connect to the API?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*21UFVcHxpqjMLNRm" /><figcaption>Photo by <a href="https://unsplash.com/@krstne?utm_source=medium&amp;utm_medium=referral">Kristine Tumanyan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Hello! As .Net developers well know, scaffolding is a lifesaver in tasks like CRUD operations, Identity management, and using Entity Framework with a Database First approach. A look at the aspnet-codegenerator documentation shows that there’s almost nothing we can’t generate in the world of .Net Web Applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZxfAhLMx2LlWDogm" /><figcaption><a href="https://learn.microsoft.com/en-us/aspnet/core/fundamentals/tools/dotnet-aspnet-codegenerator?view=aspnetcore-7.0#arguments">https://learn.microsoft.com/en-us/aspnet/core/fundamentals/tools/dotnet-aspnet-codegenerator?view=aspnetcore-7.0#arguments</a></figcaption></figure><p>In scenarios where we have database tables, we know how quickly a project can start up when we include identity in our setup, generate our models with db first, and auto-generate controller and view classes for CRUD operations based on the entities.</p><h3>What happens if our data source is an API instead of a database?</h3><p>Since our data source has changed, we need to switch from DB-First to API-First management. Instead of connecting to a database and reading tables and fields, we’ll need to create classes and attributes by understanding JSON result content. (There are tools developed for this, but I want to discuss the method I use here. In this article, we’ll work with a simple API response.)</p><h3>API RESPONSE</h3><p>Let’s say we provide the endpoint as an argument to our program. With the following code structure, we can get the API response and access the JSON object within the content.</p><pre>HttpClientHelper clientHelper = new HttpClientHelper()<br>string jsonString = await clientHelper.GetJson(endPoint);</pre><h3>Deserializing the JSON object into a JObject.</h3><p>Using Newtonsoft.Json, we parse the JSON text to make it more meaningful. Since we don’t know which type to parse it into — because our goal is to create this type — we parse it into a JObject so we can access class attributes and their types.</p><pre>JArray jArray = JArray.Parse(jsonString);<br>JObject jsonObject = jArray.Children&lt;JObject&gt;().First();</pre><h3>Generating a class from the JObject attributes.</h3><p>Essentially, creating a class means writing code to a file, which we can automate with I/O operations and a few settings.</p><p>For example, instead of manually typing each property, we can use a method that automatically creates a line for every attribute by reading the name and type from the JObject.</p><pre>public class PropertyBuilder<br>{<br>   public string GetProperty(Newtonsoft.Json.Linq.JProperty jToken)<br>   {<br>      string propertyName = char.ToUpper(jToken.Name[0]) + jToken.Name.Substring(1);<br>      if (jToken.Value.Type == Newtonsoft.Json.Linq.JTokenType.Integer)<br>      {<br>         return $&quot;   public int {propertyName};&quot;;<br>      }<br>    <br>      return $&quot;   public {jToken.Value.Type} {propertyName};&quot;;<br>   }<br>}</pre><p>If you have experience with controller scaffolding in MVC, you’ll remember that the data comes from a database and progresses through a template using Entity Framework. Here, we’ve created our model classes, but we don’t yet have a layer to connect data to these models.</p><h3><strong>Extensible Client Structure</strong></h3><p>Here, our data source has changed and we’re not using an ORM. So, can’t we generate an intermediary layer to fetch data from this source? We need to set up an extensible structure so that it can handle basic CRUD operations whenever a new entity is added. (In this example, we’ll only implement the GetList operation.)</p><pre>public interface IClientService&lt;T&gt; where T : class, new(<br>{<br>    Task&lt;IEnumerable&lt;T&gt;&gt; GetAll(string endPoint);<br>})</pre><p>Let’s implement this interface using the Generic Design Pattern.</p><pre>public class ClientService&lt;T&gt; : IClientService&lt;T&gt; where T : class, new(<br>{<br>   public async Task&lt;IEnumerable&lt;T&gt;&gt; GetAll(string endPoint)<br>   {<br>      HttpClient client = new HttpClient();<br>      string responseBody = &quot;&quot;;<br>      using HttpResponseMessage response = await client.GetAsync(endPoint);<br>      response.EnsureSuccessStatusCode();<br>      responseBody = await response.Content.ReadAsStringAsync();<br>      return JsonConvert.DeserializeObject&lt;IEnumerable&lt;T&gt;&gt;(responseBody);<br>   }<br>}</pre><h3>Generating a Client Service</h3><p>When the model is created, we can generate a Client Service for that model, derived from the main Client Service and responsive to the GetAll method. This allows us to pull the API response and map it to our object in one move.</p><pre>string endPoint = &quot;https://api.thecatapi.com/v1/images/search&quot;;<br>string ns = &quot;Cat.Web.Models&quot;;<br>string typeName = &quot;Cat&quot;;<br><br>HttpClientHelper clientHelper = new HttpClientHelper();<br>string jsonString = await clientHelper.GetJson(endPoint);<br>JArray jArray = JArray.Parse(jsonString);<br>JObject jsonObject = jArray.Children&lt;JObject&gt;().First();<br><br>//JObject.Parse<br>string savePath = Path.Combine(Constants.TargetFolder, &quot;RazorPageGenerator&quot;);<br>using (StreamWriter streamWriter = new StreamWriter(Path.Combine(savePath, $&quot;{typeName}.cs&quot;)))<br>{<br>   streamWriter.WriteLine($&quot;using System;&quot;);<br>   streamWriter.WriteLine($&quot;using System.Linq;&quot;);<br>   streamWriter.WriteLine();<br>   streamWriter.WriteLine($&quot;namespace {ns};&quot;);<br>   streamWriter.WriteLine();<br>   streamWriter.WriteLine($&quot;public class {typeName}&quot;);<br>   streamWriter.WriteLine(&quot;{&quot;);<br>   var propertyBuilder = new PropertyBuilder();<br>   foreach (var property in jsonObject.Properties())<br>   {<br>      var prop = propertyBuilder.GetProperty(property);<br>      streamWriter.WriteLine(prop);<br>   }<br>  <br>   streamWriter.WriteLine(&quot;}&quot;);<br>}<br><br>using (StreamWriter streamWriter = new StreamWriter(Path.Combine(savePath, $&quot;{typeName}ClientService.cs&quot;)))<br>{<br>   streamWriter.WriteLine($&quot;using System;&quot;);<br>   streamWriter.WriteLine($&quot;using System.Linq;&quot;);<br>   streamWriter.WriteLine($&quot;using {ns}.Services;&quot;);<br>   streamWriter.WriteLine();<br>   streamWriter.WriteLine($&quot;namespace {ns};&quot;);<br>   streamWriter.WriteLine();<br>   streamWriter.WriteLine($&quot;public class {typeName}ClientService : ClientService&lt;{typeName}&gt;&quot;);<br>   streamWriter.WriteLine(&quot;{&quot;);<br>   streamWriter.WriteLine(&quot;}&quot;);<br>}</pre><p>The only thing left to do is to create Razor pages, which the aspnet-codegenerator handles.</p><p>After scaffolding the models and Client Services, using the code-generator to create Razor pages seems to move the project from ‘manually creating models’ to ‘launching with a few commands.’ What do you think?</p><p>Thanks for reading. Best regards</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26611a758451" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Javascript Promise Yapıları Nedir ve Nasıl Çalışır?]]></title>
            <link>https://busenursahin.medium.com/javascript-promise-yap%C4%B1lar%C4%B1-nedir-ve-nas%C4%B1l-%C3%A7al%C4%B1%C5%9F%C4%B1r-33bb71d593fd?source=rss-67c9aefc0c68------2</link>
            <guid isPermaLink="false">https://medium.com/p/33bb71d593fd</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[promises]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Buse Nur Şahin]]></dc:creator>
            <pubDate>Thu, 04 Jan 2024 06:22:31 GMT</pubDate>
            <atom:updated>2024-07-09T06:09:30.050Z</atom:updated>
            <content:encoded><![CDATA[<p>Daha performanslı, bloklanmayan yazılım ürünleri geliştirmek ve kullanıcı memnuniyetini artırmak için asenkron işlemlere ihtiyaç duyarız. Yazılım dillerinin farklı konseptleri ve ihtiyaçlarına uygun farklı anahtar kelimeleri ve yapıları bulunur. JavaScript dilinde asenkron işlemleri gerçekleştirebilmek için <strong>Promise </strong>yapısını öğrenmek gereklidir.</p><p>Promise yapılarını anlamakta zorlanıyorsanız, şu soruları kendinize sorabilirsiniz:</p><ol><li>Fonksiyonel programlama yapısını biliyor muyum?</li><li>JavaScript temellerine hakim miyim?</li><li>Asenkron programlama kavramını biliyor muyum ve neden ihtiyaç duyulduğunun farkında mıyım?</li><li>Callback fonksiyonlarını biliyor muyum ve rahatlıkla kullanabiliyor muyum?</li></ol><p>Bu sorulara cevabınız evet ise, Promise yapılarını incelemeye başlayabilirsiniz. Hayır ise, bu akış diyagramının takıldığınız noktasına geri dönüp halletmeye çalışmanızı öneririm.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fQBXIrMSk5bV0DET" /><figcaption>Photo by <a href="https://unsplash.com/@tavgaksalih?utm_source=medium&amp;utm_medium=referral">Tavga K.S</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Callback Fonksiyon Nedir?</h3><p>Callback fonksiyonlar bir fonksiyonu diğer bir fonksiyona argüman olarak verebilmek için kullanılan yapılarıdır. Bir işlem tamamlandığında başka bir şey de yapılmasını istiyorum dediğimiz zaman callback kullanmamız gerekiyor.</p><p>Javascript senkron çalışır ve single thread’dir ama kullanım alanları ve doğası gereği asenkron işlemlerle sık sık karşılaşırız. Uzun süren işlemlerimizin tamamlanmasını beklemeden diğer işlere devam etmek isteriz ve bloklanma yaşamamak isteriz. Bunun için bir iş çalışırken yani bir kod satırı okunduğunda uzun süren işlemin tamamlanmasını beklemeden diğer satıra geçmeliyiz ancak alt satırlarda uzun süren işlemin çıktısına bağlı bir işlem varsa kodumuz istediğimiz gibi çalışmayacaktır.</p><p>Peki uzun süren işler tamamlandığında, bu uzun süren işlemlere bağımlı olan diğer işler bu uzun süren işin sonucunu, tamamlandığını, hata alıp almadığını nasıl bilecek? İşte burada callback devreye girer ve javascript bize callback tabanlı asenkron programlamayı sunar.</p><blockquote><strong>Dikkat ederseniz setTimeout, setInterval, fetch gibi asenkron javascript fonksiyonları hep callback fonksiyon alırlar, sebebinden az önce bahsetmiş olduk.</strong></blockquote><h3>Senaryo</h3><p>Web uygulamamıza dosya yüklemi işlemi var ancak bu işlem uzun sürdüğü için kullanıcıyı donmuş bir ekranla karşılamak yerine yükleme anında geri bildirim vermek istiyoruz. Bunun için yüklenen boyuta göre işlemin yüzde kaçının bittiğini ekrana basmak istiyoruz.</p><h3>Adım 1:</h3><p>Callback alan bir upload fonksiyonu yazalım. Bu upload fonksiyonunun bir anlık değeri bir de işin alacağı bütün zamanı gösteren total değeri olsun. Bunu bir dosyanın upload edilen boyutu ile dosya boyutu gibi düşünebiliriz.</p><p>Upload fonksiyonunun upload edilen boyutu değiştikçe bir callback çağırsın ve bu callback’e anlık aktarılan boyut değerini ve total değeri versin böylece upload fonksiyonuna bir callback verdiğimizde bu callback fonksiyon iki parametre ile gelecek ve bu parametreler üzerinde işlemin yüzde kaçının tamamlandığını bulabileceğim.</p><pre>function upload(callback) {<br>  var current = 0;<br>  var total = 5;<br>  var interval = setInterval(() =&gt; {<br>    current += 1;<br>    callback(current, total);<br>    if (current == total) clearInterval(interval);<br>  }, 1000);<br>}</pre><p>Burada anlık değeri 0 ve tamamlanma değeri 5 olan bir işlem var.</p><p>Bu işlem saniye başı 1 birim artıyor ve her artışta callback’i iki argüman ile tetikliyor.</p><h3>Adım 2:</h3><p>Upload fonksiyonunu bir callback argümanı geçerek çağıralım.</p><pre>upload((current, total) =&gt; {<br>  progress.innerHTML = current / total * 100 + &quot;%&quot;;<br>});</pre><h3>Sonuç olarak</h3><p>Tek iş parçacığı üzerinde çalışan javascript ile asenkron işlemleri gerçekleştirebilmemiz için ihtiyacımız olan callback fonksiyonlarını başka bir fonksiyonu argüman olarak alan <strong>higher order</strong> -yüksek seviyeli- fonksiyonlara nasıl geçeceğimizi ve ana fonksiyonun nasıl çalıştığını görmüş olduk. Uygulama kodlarına <a href="https://jsfiddle.net/86dsa9bk/18/">şuradan</a> da erişebilirsiniz.</p><h3>Promise Nedir?</h3><p>Temel anlamda bir işlem var ve bu işlem belirli bir zamanda gerçekleşecek ise ve biz bu işlem gerçekleştiğinde gibi anları yaklamak istiyorsak bu noktada Promise’lere başvurabiliriz.</p><p>Oluşturduğumuz promise’leri kullanırken ise Chaining yapısına başvururuz ve .then() ve .catch() kullanarak ardışıl işlemleri birbirine bağlayabiliriz.</p><h3>Senaryo</h3><p><strong>Bir Promise nesnesi oluşturmak, nesneyi kullanmak ve Promise’i nasıl yöneteceğinizi öğrenmek için bir örnek uygulama yapalım.</strong></p><p>Örneğin, biraz zaman alan bir veri çekme işlemimiz olsun. Bu veri çekme işlemini bir fonksiyonda yaptığımızı düşünelim. Normalde fonksiyondan gelen veriyi bir alt satırda kullanırız ama bu veriyi asenkron olarak çekmek istiyorsak bir alt satırda veri henüz gelmemiş olabilir çünkü asenkron programlama o satırın bitmesini beklemeden işlem yapmaya devam edecektir. Öyleyse bu fonksiyon içindeki işlemin tamamlanıp tamamlanmaması önem arz etmektedir ve yine bu fonksiyonun “tamamlandığında” anını ve başarılı sonuç veya hatalı sonuç durumlarını yakalayabilmem gerekmektedir.</p><p>İşte Promise bu ihtiyaçlar için biçilmiş kaftandır.</p><h3>Promise Yapısı</h3><p>Örneğimizi nasıl kodlayabilirdik düşünelim ve promise yapısı senaryomuzdan hareketle biraz anlamlandırmaya çalışalım.</p><p>Bu işlem başarılı döndüğünde kısmını nasıl yakayalayabilirim?</p><p>Promise chaining mekanizması ile, yani yazdığınız promise’den sonra “.then()” diyerek içerisinde bir callback function ile dönen değeri alabilirsiniz.</p><p>Bu işlemin başarısız sonuçlandığı durumu nasıl yakalayabilirim?</p><p>Yine promise chaining mekanizması ile, yani yazdığınız promise’den sonra “.catch()” diyerek yine içerisinde bir callback function ile dönen değeri alabilirsiniz.</p><p>Peki, promise yazarken başarılı-başarısız durumu nasıl geri döndürebilirim?</p><p>resolve ve reject bir JavaScript Promise’i oluşturduğunuzda kullanabileceğiniz özel fonksiyonlardır ve bu fonksiyonlar Promise’in içerdiği çalıştırılabilir işlev (executor function) içinde bulunurlar. Bu executer function’lar ile işlem sonucunu dönebilirsiniz.</p><h3>Uygulama</h3><p>Promise oluştralım.</p><pre>new Promise((resolve, reject) =&gt; {})</pre><p>Bekleme işlemini simüle etmek için setTimeout kullanalım ve 2 saniye bekleyelim. Sonrasında başarılı veya başarısız durumu simüle etmek için rasgele bir değer üretelim ve bu değeri bir koşulla resolve veya reject ile döndürelim. Böylece bu Promise‘i bir işlevin içinde döndürebiliriz ki, bu işlev üzerinden zincirleme (chaining) mekanizmasını kullanabilelim.</p><pre>function myFetch(url) {<br>  return new Promise((resolve, reject) =&gt; {<br>    setTimeout(() =&gt; {<br>      const random = Math.random();<br>      if (random &lt; 0.7) {<br>        // Başarılı sonuç<br>        resolve({ data: `Veri alındı: ${url}` });<br>      } else {<br>        // Hata durumu<br>        reject(new Error(`Veri alınamadı: ${url}`));<br>      }<br>    }, 2000);<br>  });<br>}</pre><p>Bu Promise’i şöyle kullanabiliriz:</p><pre>// Örnek kullanım:<br>const url = &#39;&#39;;<br>myFetch(url)<br>  .then(response =&gt; {<br>    console.log(response.data);<br>  })<br>  .catch(error =&gt; {<br>    console.error(error.message);<br>  });</pre><p>Bu kullanımdan sonra, eğer daha önce fetch gibi bir fonksiyon kullandıysanız veya axios ile veri çekme kodu gördüyseniz, bu size yabancı gelmeyecektir.</p><p>Örnek bir axios ile veri çekme kodu:</p><pre>axios<br>.get(&quot;https://reqres.in/api/users?page=1&quot;)<br>.then((resp) =&gt; {<br>  let id = resp.data.data[4].id;<br>  console.log(id);<br>})<br>.catch((err) =&gt; {<br>  console.log(err);<br>});</pre><p>Bu aşamadan sonra modern JavaScript ile gelen async ve await anahtar kelimelerini öğrenebilir ve Promise tabanlı asenkron kodları daha okunabilir hale getirebilirsiniz.</p><p>Özetle promise yapıları javascript ile veri çekme gibi vakit alan işlemlerde uygulamanın bloklanmasını engellemek veya kullanıcıya geri bildirimde bulunmak gibi ihtiyaçları karşılayan asenkron işlemleri yapabilmek ve bu işlemler üzerinde kontrolü sağlamak için kullanılan yapılardır.</p><p>Konu hakkında daha fazla bilgi edinmek için <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">mozillanın</a> ve <a href="https://www.w3schools.com/js/js_promise.asp">w3schools</a>‘un kaynaklarına başvurabilirsiniz.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33bb71d593fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Extension Method (Genişletme Metodları) Nedir? (C#)]]></title>
            <link>https://busenursahin.medium.com/extension-method-nedir-e603c4f16b02?source=rss-67c9aefc0c68------2</link>
            <guid isPermaLink="false">https://medium.com/p/e603c4f16b02</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[extension]]></category>
            <category><![CDATA[extension-method]]></category>
            <category><![CDATA[csharp]]></category>
            <dc:creator><![CDATA[Buse Nur Şahin]]></dc:creator>
            <pubDate>Wed, 27 Dec 2023 09:52:50 GMT</pubDate>
            <atom:updated>2023-12-27T10:02:04.841Z</atom:updated>
            <content:encoded><![CDATA[<p>Proje geliştirirken hazır kütüphanelerden sıklıkla faydalanıyoruz. Kullandığımız hazır kütüphaneleri proje ihtiyaçlarına göre genişlettiğimiz durumlar olmalı çünkü bir kütüphanenin yalnızca kendi haliyle tüm projelerdeki tüm ihtiyaçlara cevap üretebilmesi pek olası değil.</p><p>Kullanılan kütüphaneleri proje ihtiyaçlarına göre genişletirken kalıtım almak gibi, method ezme gibi farklı yöntemler kullanabiliyoruz. Yazının konusu olan <strong>Extension Method </strong>bu yöntemlerden biri aslında.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Pj2r2asQ5l4Jg0NA" /><figcaption>Photo by <a href="https://unsplash.com/@kevin_butz?utm_source=medium&amp;utm_medium=referral">Kevin Butz</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Bir örnek üzerinden gitmenin daha doğru olduğunu düşünüyorum. Mesela biz bir proje oluşturduğumuzda hazır gelen <strong>String </strong>veri tipi var. Bu veri tipi aslında bir sınıf ve içerisinde methodları var, metindeki harfleri büyüten method olan <strong>ToUpper</strong> veya verilen karaktere göre metni parçalayarak diziye çeviren <strong>Split </strong>methodu gibi.</p><h4>Peki bizim farklı bir ihtiyacımız olduğunda?</h4><p>Ve bu farklı ihtiyacımızı String değerler üzerinden direkt çağırmak istediğimizde?</p><p>Hadi <strong>Split </strong>methodundan bir örnek verelim.</p><p>Split methodu String ifadeleri verilen ifadeye göre bölerek dizi haline çeviren bir methoddur. Normalde ilgili bölücü karakteri (separator) vererek diziye çevirme işlemini sağlayabiliriz ama biz direkt boşluklara göre bölen ve ekstra bir karakter vermemizi istemeyen bir method olsun isteyelim.</p><h3>Bunu nasıl yaparız?</h3><p>İstediğimiz şey bir metin yazdıktan sonra Split methodunu çağırabildiğimiz gibi <strong>MySplit </strong>methodunu çağırmak. Dolayısıyla bir String üzerinde bu methodu çalıştırmam lazım.</p><h4>Nasıl yaparım?</h4><p>Hazır olan String sınıfını bulup gidip o sınıfa bir ekleme mi yapmalıyım? <strong>Tabii ki hayır</strong>. Hazır sınıfları ve kütüphaneleri değiştirmemeliyiz.</p><h4>Peki nasıl String’e bağlı yeni bir method yazarım?</h4><p>Öncelikle static bir sınıfımız olması gerekiyor, genelde isimlendirme <strong>ilgili sınıf + Extensions</strong> olarak yapılır.</p><pre>public static class StringExtensions<br>{<br>}</pre><p>Bu sınıfa <strong>static bir method</strong> ekleyeceğiz. Peki bu methodun hangi sınıfın extension methodu olduğunu nasıl belirteceğiz?</p><p>Özel bir parametre ile.</p><pre>public static string[] MySplit(this String metin)<br>{<br>    var result = metin.Split(&#39; &#39;);<br>    return result;<br>}</pre><p>Yukarıdaki kodda</p><ul><li>static bir method var, bu extension methodun bir şartı</li><li>bu method <strong>this String </strong>tipinde bir parametre alıyor, bu da hangi sınıfa extension yazdığımızı belirtmek için kullandığımız bir alan</li><li>string dizisi dönüyor çünkü bölme işlemi yapacağım</li><li>method içerisinde String sınıfından hazır gelen Split methodunu kendime göre özelleştirmek istediğim boşluk karakterini kullanıyorum</li><li>dönüş değeri olarak aldığım ise sonucu veriyorum</li></ul><h3>Extension Methodu çağıralım</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*8M8Pzxh7HH6lAGSUpgwOhg.png" /></figure><blockquote>Artık String ifadelerde <strong>MySplit </strong>methodu da çağırılabilir oldu, bunu sağlayan <strong>Extension Method yazmış olmamız</strong>.</blockquote><h4>Program çıktısı ise şöyle</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*mVthEAEuwQUDoMtIn9axqw.png" /></figure><p>Bu basit örnekten sonra C# ile kurumsal proje geliştirme tecrübesi olanların aşina olduğu <strong>DevExpress </strong>ürününün demo kodlarından birine bakacağız.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*bQ3Wzi-dH4hLlLhzgVqFFQ.png" /><figcaption><a href="https://github.com/DevExpress/DevExtreme.AspNet.Mvc-Demos-NETCore/blob/master/WidgetGallery/Extensions.cs#L12">https://github.com/DevExpress/DevExtreme.AspNet.Mvc-Demos-NETCore/blob/master/WidgetGallery/Extensions.cs#L12</a></figcaption></figure><p>DevExpress Widget Gallery altındaki bu kodda .Net <strong>ModelStateDictionary </strong>sınıfına bir <strong>extension method</strong> yazıyor ve kompleks bir obje içerisinde gelen hata mesajlarını birleştirerek tek bir metin halinde String veri tipinde döndürüyor.</p><p>En basit haliyle Extension Methodu anlatmaya çalıştım ve sonrasında gerçek hayatta nasıl bir kullanımı olduğuna dair kod örneği paylaştım. Umarım öğrenme sürecinize faydası olmuştur.</p><p>Konu hakkında <a href="https://medium.com/u/5a2e1195a4a9">Burak Selim Şenyurt</a> hocamızın yıllar önce kaleme aldığı şu muhteşem <a href="https://www.buraksenyurt.com/post/C-3-0-Derinlemesine-Extension-Method-Kavramc4b1-bsenyurt-com-dan">yazısına </a>da bakabilirsiniz.</p><p>Okuduğunuz için teşekkür ederim, iyi çalışmalar</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e603c4f16b02" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Komuta Tasarım Deseni — (Command Design Pattern)]]></title>
            <link>https://busenursahin.medium.com/komuta-tasar%C4%B1m-deseni-command-design-pattern-a7b21b0ac198?source=rss-67c9aefc0c68------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7b21b0ac198</guid>
            <dc:creator><![CDATA[Buse Nur Şahin]]></dc:creator>
            <pubDate>Fri, 08 Dec 2023 08:50:33 GMT</pubDate>
            <atom:updated>2024-01-20T15:39:31.403Z</atom:updated>
            <content:encoded><![CDATA[<h3>Komuta Tasarım Deseni — (Command Design Pattern)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6mZI77r_O7j1K7Op" /><figcaption>Photo by <a href="https://unsplash.com/@studiokiek?utm_source=medium&amp;utm_medium=referral">Kiki Siepel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Senaryo</h3><p>Bir arayüz uygulamasında kullanıcının arayüz üzerinden yapabileceği işlemlerin yer aldığı bir palet oluşturulacak. Palet üzerinden yapılabilen her işlemin geri alma ve geri alınan işlemi tekrar ileri alma özelliklerinin olması isteniyor. Bu paleti genişletilebilir, esnek ve kullanıcıdan alınan komutların rahatça saklanıp yönetilebildiği bir yapı ile geliştirilmesi isteniyor. Nasıl yapardınız?</p><h3>Komuta Tasarım Deseni</h3><p>Bu senaryoyu gerçekleştirmek için uygulayacağımız Komuta Tasarım Desenini kısaca tanıyarak başlayabiliriz. Komuta tasarım deseni işlemleri(fonksiyonları) soyutlayarak ve sarmalayarak bir noktadan yönetilebilir olmasını sağlar.</p><p>Mesela televizyonun uzaktan kumandasını elimize aldığımızda ve bir tuşa bastığımızda bir komut veriyoruz. Kumandada verebileceğimiz tüm komutlar kayıtlı. Bu soyutlanmış yapıyı uyguladığımızda komuta tasarım desenini uyguluyoruz gibi düşünebiliriz.</p><p>Bu tasarım deseni için genelde verilen bir örnek vardır, bir ışığı açıp kapatmak için önümüzde bir anahtar var. Anahtara bastığımızda ışık açılıyor ve tekrar bastığımızda kapanıyor.</p><p>Bu yapıyı komuta tasarım deseni ile nasıl uygulayabilirdik?</p><p><strong>Komuta</strong>: komut, anahtar üzerinden yapılabilecek işlemlerin soyut kavramı</p><pre>public interface ICommand<br>{<br>    void Execute();<br>}</pre><p><strong>Komuta alıcı</strong>: lamba, komutları uygulayacak olan lamba</p><pre>public class Light<br>{<br>    public void TurnOn()<br>    {<br>        Console.WriteLine(&quot;Işık açıldı&quot;);<br>    }<br><br>    public void TurnOff()<br>    {<br>        Console.WriteLine(&quot;Işık kapatıldı&quot;);<br>    }<br>}</pre><p><strong>Somut komutlar</strong>: uygulanabilir komut, kullanıcının kumandasında yer alabilecek işlemler (anahtar açma ve kapama)</p><pre>public class TurnOnCommand : ICommand<br>{<br>    private Light _light { get; set; }<br>    public TurnOnCommand(Light light)<br>    {<br>        _light = light;<br>    }<br><br>    public void Execute()<br>    {<br>        _light.TurnOn();<br>    }<br>}<br><br>public class TurnOffCommand : ICommand<br>{<br>    private Light _light { get; set; }<br>    public TurnOffCommand(Light light)<br>    {<br>        _light = light;<br>    }<br>    public void Execute()<br>    {<br>        _light.TurnOff();<br>    }<br>}</pre><p><strong>Çağırıcı</strong>: anahtar, işlemleri çağırdığımız arayüz</p><pre>public class RemoteControl<br>{<br>    private Dictionary&lt;string, ICommand&gt; _commands = new Dictionary&lt;string, ICommand&gt;();<br><br>    public void Register(string key, ICommand command)<br>    {<br>        _commands.Add(key, command);<br>        //_commands[key] = command;<br>    }<br><br>    public void ExecuteCommand(string key)<br>    {<br>        if(_commands.TryGetValue(key, out ICommand command))<br>        {<br>            command.Execute();<br>        }<br>        else<br>        {<br>            Console.WriteLine(&quot;geçersiz komut&quot;);<br>        }<br>    }<br><br>}</pre><p>Lambayı kapatıp açmayı test edelim</p><pre><br>Light light = new Light();<br><br>ICommand turnOnCommand = new TurnOnCommand(light);<br>ICommand turnOffCommand = new TurnOffCommand(light);<br><br>RemoteControl remoteControl = new RemoteControl();<br>remoteControl.Register(&quot;on&quot;, turnOnCommand);<br>remoteControl.Register(&quot;off&quot;, turnOffCommand);<br><br>// Lambayı açma işlemi<br>remoteControl.ExecuteCommand(&quot;on&quot;);<br>// Lambayı kapatma işlemi<br>remoteControl.ExecuteCommand(&quot;off&quot;);</pre><p>Kod çıktısı:</p><pre>Işık açıldı<br>Işık kapatıldı</pre><h3>Soru: Tamam da neden?</h3><pre>Light light = new Light();<br>light.TurnOn();<br>light.TurnOff();</pre><p>Bu şekilde 3 satırda ve birçok yeni sınıf oluşturmadan yapabileceğimiz bir işi neden uzatarak yaptık? Aslında cevap olarak, “kompleks uygulamalarda daha temiz, yönetilebilir, takip edilebilir, kod yazmak için” diyebiliriz. Bu yüzden evet, ışık açıp kapama kodunda uygulamak hiç mantıklı değil ama belki yukarıdaki senaryoda kullanmak biraz daha anlamlı gelebilir, hadi senaryoyu uygulamaya başlayalım.</p><h3>Kullanıcı İşlemlerinin Saklanması</h3><p>Palet üzerinde metin ekleme, şekil çizme, arka plan silme, arka plan rengi değiştirme işlemlerinin olduğunu düşünelim. Komutların alıcısı olan üç veri türü var, metin ve çizim ve arka plan.</p><pre>public class Text<br>{<br>    public void AppendText()<br>    {<br>        Console.WriteLine(&quot;yeni metin eklendi&quot;);<br>    }<br>}<br><br>public class Draw<br>{<br>    public void DrawLine()<br>    {<br>        Console.WriteLine(&quot;çizgi çizildi&quot;);<br>    }<br><br>    public void DrawCircle()<br>    {<br>        Console.WriteLine(&quot;daire çizildi&quot;);<br>    }<br>}<br><br>public class Background<br>{<br>    public void ClearBackground()<br>    {<br>        Console.WriteLine(&quot;arka plan kaldırıldı&quot;);<br>    }<br><br>    public void ChangeBackgroundColor()<br>    {<br>        Console.WriteLine(&quot;arka plan rengi değiştirildi&quot;);<br>    }<br>}</pre><p>Bu sınıflar komuta tasarım deseninde hangi kavrama denk gelir? <strong>Komuta alıcı</strong> sınıflara (reciever).</p><p>Birbirinden farklı türdeki işlemleri bir yığında tutabilmem için bu işlemleri <strong>sarmalamam </strong>gerektiğini düşünüyorum ve tüm sarmalanan farklı türdeki işlemler eğer <strong>aynı arayüzden türetilmişse</strong>, nesne yönelimli programlamanın <strong>poliformizm prensibine uygun şekilde</strong>, <strong><em>tüm işlemleri aynı veri yapısında tutabilirim.</em></strong></p><pre>public interface ICommand<br>{<br>    void Execute();<br>    void Undo();<br>}</pre><h3>Her alıcıdaki her işlem için gerekli somut sınıfların yazılması gerekiyor.</h3><p>İşlemlerin türediği ortak yapıda, ortak olan özellikleri saklayabilirim. Bu işlemler çalıştırma ve geri alma işlemleridir.</p><ul><li>Bir işlem uygulanması için butona basıldığında “çalıştır” komutu gitmiş olur ki bu “komut” sınıfında yer alıyor (ICommand/Execute).</li><li>İşlem geri alındığında “geri al” komutunu çalıştırırım ki bu da “komut” sınıfında yer alıyor (ICommand/Undo).</li><li>Geri alınan işlemi tekrar ileri almam için de tekrar “çalıştır” komutunu çağırmam yeterli.</li></ul><pre>public class AppendText : ICommand<br>{<br>    private Text _text { get; set; }<br>    public AppendText(Text text) =&gt; _text = text;<br><br>    public void Execute() =&gt; _text.AppendText();<br><br>    public void Undo() =&gt; _text.UndoText();<br>}<br><br>public class DrawLine : ICommand<br>{<br>    private Draw _draw { get; set; }<br><br>    public DrawLine(Draw draw) =&gt; _draw = draw;<br><br>    public void Execute() =&gt; _draw.DrawLine();<br><br>    public void Undo() =&gt; _draw.UndoDraw();<br>}<br><br>public class DrawCircle : ICommand<br>{<br>    private Draw _draw { get; set; }<br><br>    public DrawCircle(Draw draw) =&gt; _draw = draw;<br>    public void Execute() =&gt; _draw.DrawCircle();<br><br>    public void Undo() =&gt; _draw.UndoDraw();<br>}<br><br>public class ChangeBackgroundColor : ICommand<br>{<br>    private Background _background { get; set; }<br><br>    public ChangeBackgroundColor(Background background) =&gt; _background = background;<br><br>    public void Execute() =&gt; _background.ChangeBackgroundColor();<br><br>    public void Undo() =&gt; _background.UndoBackground();<br>}<br><br>public class CleareBackground : ICommand<br>{<br>    private Background _background { get; set; }<br><br>    public CleareBackground(Background background) =&gt; _background = background;<br><br>    public void Execute() =&gt; _background.ClearBackground();<br><br>    public void Undo() =&gt; _background.UndoBackground();<br>}</pre><p>Artık alıcılarımız ve işlemlerimiz hazır. Paletin bu işlemlerden tamamen soyutlanmış olması için bir kontrol yapısı <strong>adeta bir kumanda</strong> oluşturacağız.</p><pre>public class RemoteControl<br>{<br><br>}</pre><p>Kullanıcı palet üzerindeki işlemlere tıkladığında <strong><em>yapılan son işlemleri ileri-geri alabilmek için bir yerde saklamamız gerekiyor.</em></strong> Son yapılan işlemin geri alınabilmesi için işlemlerin saklanabileceği <strong><em>en uygun yapı son giren-ilk çıkar (lifo) prensibine uygun veri yapısı olan stack (yığın-yığıt) gibi duruyor</em></strong>.</p><p>Uygulanan komutlar ve ileri alma işlemi için geri alınan komutlar olmak üzere iki adet yığın oluşturmalıyız.</p><pre>public class RemoteControl<br>{<br>    Stack&lt;ICommand&gt; commands = new Stack&lt;ICommand&gt;();<br>    Stack&lt;ICommand&gt; undoCommands = new Stack&lt;ICommand&gt;();<br>}</pre><p>Bir işlemi uyguladığımızda bu komutayı çağırmalı ve komutlar yığınına eklemeliyiz.</p><pre>public class RemoteControl<br>{<br>    Stack&lt;ICommand&gt; commands = new Stack&lt;ICommand&gt;();<br>    Stack&lt;ICommand&gt; undoCommands = new Stack&lt;ICommand&gt;();<br><br>    public void Execute(ICommand command)<br>    {<br>        command.Execute();<br>        commands.Push(command);<br>    }<br>}</pre><p>Uygulanan son komut geri alındığında komutlar yığınındaki son elemanı alıp işletmeli ve geri alınan komutlar yığınına eklemeliyiz.</p><pre>public class RemoteControl<br>{<br>    Stack&lt;ICommand&gt; commands = new Stack&lt;ICommand&gt;();<br>    Stack&lt;ICommand&gt; undoCommands = new Stack&lt;ICommand&gt;();<br><br>    public void Execute(ICommand command)<br>    {<br>        command.Execute();<br>        commands.Push(command);<br>    }<br><br>    public void UndoLastCommand()<br>    {<br>        if (commands.Count &gt; 0)<br>        {<br>            ICommand command = commands.Pop();<br>            command.Undo();<br>            undoCommands.Push(command);<br>        }<br>        else<br>        {<br>            Console.WriteLine(&quot;Geri alınacak bir işlem yok.&quot;);<br>        }<br>    }<br>}</pre><p>Geri alınan son komut için ise geri alınan komutlar yığınındaki son elemanı çıkarmalı, çalıştırmalı ve çalıştırılan komutlara eklemeliyiz.</p><pre>public class RemoteControl<br>{<br>    Stack&lt;ICommand&gt; commands = new Stack&lt;ICommand&gt;();<br>    Stack&lt;ICommand&gt; undoCommands = new Stack&lt;ICommand&gt;();<br><br>    public void Execute(ICommand command)<br>    {<br>        command.Execute();<br>        commands.Push(command);<br>    }<br><br>    public void UndoLastCommand()<br>    {<br>        if (commands.Count &gt; 0)<br>        {<br>            ICommand command = commands.Pop();<br>            command.Undo();<br>            undoCommands.Push(command);<br>        }<br>        else<br>        {<br>            Console.WriteLine(&quot;Geri alınacak bir işlem yok.&quot;);<br>        }<br>    }<br><br>    public void RedoLastCommand()<br>    {<br>        if (undoCommands.Count &gt; 0)<br>        {<br>            ICommand command = undoCommands.Pop();<br>            command.Execute();<br>            commands.Push(command);<br>        }<br>        else<br>        {<br>            Console.WriteLine(&quot;İleri alınacak bir işlem yok.&quot;);<br>        }<br>    }<br>}</pre><h3>Test</h3><p>Command Design Pattern ile uyguladığımız senaryonun testini yapalım.</p><p>Uygulamayı açtık ve paleti kullanarak</p><ul><li>Arka planı kaldırdık</li><li>Bir metin ekledik</li><li>Arka planı değiştirdik</li><li>Arka planı beğenmeyerek geri aldık</li><li>Metinden de vazgeçerek geri aldık</li><li>Yalnızca bir daire ekleyerek uygulamamızı sonlandırdık.</li></ul><p>Bu kullanıcı deneyimini uygulayalım</p><pre><br>var text = new Text();<br>var draw = new Draw();<br>var background = new Background();<br><br>var remoteControl = new RemoteControl();<br>remoteControl.Execute(new CleareBackground(background));<br>remoteControl.Execute(new AppendText(text));<br>remoteControl.Execute(new ChangeBackgroundColor(background));<br>remoteControl.UndoLastCommand();<br>remoteControl.UndoLastCommand();<br>remoteControl.Execute(new DrawCircle(draw));</pre><p>Kod çıktısı:</p><pre>arka plan kaldırıldı<br>yeni metin eklendi<br>arka plan rengi değiştirildi<br>arka planda yapılan son değişiklik geri alındı<br>son eklenen yazı geri alındı<br>daire çizildi</pre><p>Uygulama tamamlandığında kumanda hafızasında kalan son komutlara baktığımızda yalnızca arka plan temizleme ve daire çizme kaldığını görmekteyiz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*rf-TxYhOzNgoXdQVcGcaAw.png" /></figure><p>Command Design Pattern, metotları sınıf halinde yazarak yönetimi, takibi, loglamayı, listelemeyi kolaylaştırmakta ve soyutlayarak metodu uygulayacak kişinin metot hakkında bilgi sahibi olması gerekliliğini ortadan kaldırmaktadır. Böylece kolaylıkla tek bir ICommand üzerinden farklı nesnelerin farklı metotlarını tek noktadan yönetebildik ve bir yığın içerisinde saklayarak geri alma-ileri alma işlemlerini gerçekleştirebildik.</p><p>Okuduğunuz için teşekkür ederim</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7b21b0ac198" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dependency Injection ve Basit Bir IoC Container Nasıl Yapabiliriz? (.net)]]></title>
            <link>https://busenursahin.medium.com/dependency-injection-ve-ioc-nedir-ve-nas%C4%B1l-kullanabiliriz-net-98e64450251b?source=rss-67c9aefc0c68------2</link>
            <guid isPermaLink="false">https://medium.com/p/98e64450251b</guid>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[solid]]></category>
            <category><![CDATA[ioc]]></category>
            <category><![CDATA[c]]></category>
            <dc:creator><![CDATA[Buse Nur Şahin]]></dc:creator>
            <pubDate>Thu, 07 Dec 2023 05:51:24 GMT</pubDate>
            <atom:updated>2024-08-08T01:31:29.456Z</atom:updated>
            <content:encoded><![CDATA[<h3>Senaryo</h3><p>Bir sipariş sistemimiz olduğunu düşünelim, bu sistemde yeni sipariş oluşturulduğunda ve var olan bir sipariş güncellendiğinde siparişi oluşturan kullanıcıya mail gitmeli. Mail gönderme işlemi sistem kurulduğunda gmail altyapısını kullanıyorken ilerleyen zamanlarda outlook altyapısına veya başka bir mail servisine geçiş yapabileceği öngörülüyor. Bu değişime direnmeyen ve kolay güncellenebilen bir kod yapısı oluşturmak istiyoruz. Bunu nasıl yapabiliriz?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sJ2X7EmJQpcBEEhU" /><figcaption>Photo by <a href="https://unsplash.com/@monstercritic?utm_source=medium&amp;utm_medium=referral">Sergey Shmidt</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Konsol Uygulaması ile Basit Bir Yapı Oluşturuyoruz</h3><p>Oluşturduğumuz yapıda sipariş işlemleri OrderController sınıfı üzerinden gerçekleştiriliyor.</p><ul><li>Bir sipariş oluşturmak için OrderController sınıfının Post metodunu tetiklememiz gerekiyor.</li><li>Bir sipariş güncellemek için ise Put metodunu tetiklememiz gerekiyor.</li></ul><pre>public class OrderController<br>    {<br>        public void Post()<br>        {<br>            Console.WriteLine(&quot;handled order post action&quot;);<br>        }<br>        public void Put()<br>        {<br>            Console.WriteLine(&quot;handled order put action&quot;);<br>        }<br>    }</pre><p>Bir sipariş oluşturmak için Program.cs üzerinden şöyle bir kod çağrısı yapıyoruz.</p><pre>var orderController = new OrderController();<br>orderController.Post();</pre><p>Sipariş oluşturulduğunda ve eklendiğinde mail atabilmek için bir servis sınıfımız var.</p><pre>public class GmailService<br>    {<br>        public void SendEmail(string sender, string reciever, string content)<br>        {<br>            Console.WriteLine($&quot;Gmail Service sent an email.\nsender:{sender}\nreciever:{reciever}\ncontent:{content}&quot;);<br>        }<br>    }</pre><p>OrderController bu sınıfı kullanarak sipariş oluştuğunda ve güncellendiğinde SendEmail metodunu çağırıyor.</p><pre>public class OrderController<br>    {<br>        public void Post()<br>        {<br>            Console.WriteLine(&quot;handled order post action&quot;);<br>            var mailService = new GmailService();<br>            mailService.SendEmail(sender: &quot;sender@gmail.com&quot;, reciever: &quot;reciever@gmail.com&quot;, content: &quot;an email content&quot;);<br>        }<br><br>        public void Put()<br>        {<br>            Console.WriteLine(&quot;handled order put action&quot;);<br>            var mailservice = new GmailService();<br>            mailservice.SendEmail(sender: &quot;sender@gmail.com&quot;, reciever: &quot;reciever@gmail.com&quot;, content: &quot;an email content&quot;);<br>        }<br>    }</pre><p>Programı çalıştırdığımızda şu çıktıyı alıyoruz:</p><pre>handled order post action<br>Gmail Service sent an email.<br>sender:sender@gmail.com<br>reciever:reciever@gmail.com<br>content:an email content</pre><h3>Bağımlılıkların Çözümlenmesi</h3><p>Uygulama şuan çalışıyor ve ihtiyaca yanıt üretiyor ancak OrderController içerisinde yeni GmailService nesnesi oluşturarak sıkı bağlı bir yapı kuruldu. OrderController GmailService sınıfına bağımlı ve bu bağımlılığın soyutlamaya çevrilmesi gerekiyor. Neden? Çünkü Outlook servisi kullanılmaya başlandığında mail gönderimiyle alakalı neredeyse tüm kod satırlarının düzenlenmesi gerekecek ve tekrar bu tip bir değişim ihtiyacında aynı işlemler tekrarlanacak. Bu da kodun değişime direçli bir hale gelmesine neden olduğu için bunu istemiyoruz. Ne istiyoruz? Esnek bağlı bir yapı. Bunu nasıl yapacağız? OrderController GmailService sınıfına değil bu sınıfın soyutlamasına bağımlı olacak ve GmailService de soyutlamadan türetilecek. Böylece iki sınıf bir protokol imzalamış gibi olacak ve bu kurallar bütünü üzerinden anlaşmaları sayesinde yeni oluşturulacak bir mail servisi için kod hızlıca uyarlanabilecek.</p><h3>Kötü Durum</h3><p>Projeye yeni bir mail servisi eklendi.</p><pre>public class OutlookMailService<br>    {<br>        public void EmailSend(Mail mail)<br>        {<br>            Console.WriteLine($&quot;Outlook service is sent an email!\nreciever:{mail.Reciever}\ncontent:{mail.Content}&quot;);<br>        }<br>    }<br><br>public class Mail<br>    {<br>        public string Reciever { get; set; }<br>        public string Content { get; set; }<br>    }</pre><p>Sipariş Yönetim sınıfı bu değişim ile çalışamaz duruma geldi ve düzenleme gerekti.</p><pre>public class OrderController<br>    {<br>        public void Post()<br>        {<br>            var mailService = new OutlookMailService();<br>            mailService.EmailSend(mail: new Mail { Content = &quot;an email content&quot;, Reciever = &quot;reciever@gmail.com&quot; });<br>        }<br><br>        public void Put()<br>        {<br>            var mailService = new OutlookMailService();<br>            mailService.EmailSend(mail: new Mail { Content = &quot;your order updated&quot;, Reciever = &quot;reciever@gmail.com&quot; });<br>        }<br>    }</pre><h3>Olması Gereken Durum</h3><p>İki mail servisi ve daha sonra eklenebilecek herhangi bir mail servisi soyut bir servisten türemeli idi.</p><pre>public interface IMailService<br>    {<br>        void SendMail(Mail mail);<br>    }</pre><p>Mail servislerinin tümü bu soyutlamadan türetilerek Sipariş Yönetim sınıfının bağımlılığı esnek hale getirilseydi değişim gerekmeyecekti.</p><pre>public class OutlookMailService : IMailService<br>    {<br>        public void SendMail(Mail mail)<br>        {<br>            Console.WriteLine($&quot;Outlook service is sent an email!\nreciever:{mail.Reciever}\ncontent:{mail.Content}&quot;);<br>        }<br>    }<br><br>public class GmailService : IMailService<br>    {<br>        public void SendMail(Mail mail)<br>        {<br>            Console.WriteLine($&quot;Gmail Service sent an email.\nsender:sender\nreciever:{mail.Reciever}\ncontent:{mail.Content}&quot;);<br>        }<br>    }</pre><p>İki servis de aynı soyutlamadan türediği için metod isimleri ve parametreleri ortaklaştırıldı böylece yeni eklenen servisler de bu ortak imzaya uyacak ve Sipariş Yönetim sınıfı mail servis değişiminden etkilenmeyecek.</p><pre>public class OrderController<br>    {<br>        public void Post()<br>        {<br>            var mailService = new OutlookMailService();<br>            mailService.SendMail(mail: new Mail { Content = &quot;an email content&quot;, Reciever = &quot;reciever@gmail.com&quot; });<br>        }<br><br>public void Put()<br>        {<br>            var mailService = new OutlookMailService();<br>            mailService.SendMail(mail: new Mail { Content = &quot;your order updated&quot;, Reciever = &quot;reciever@gmail.com&quot; });<br>        }<br>    }</pre><p>Bu durumda yeni bir mail servisi eklenirse yalnızca yeni oluşturulan nesne tipleri değişerek sistem çalışmaya devam edecek ama hala birden fazla yerde değişiklik yapmamız gerekiyor. Bunu engellemenin yolu ise bağımlılığı enjekte etmek ve new anahtar kelimesini kullanmaktan kaçınmak.</p><p>OrderController bu mail servis nesnesini dışarıdan alıyor olsaydı nasıl olurdu?</p><pre>public class OrderController<br>    {<br>        IMailService _mailService;<br>        public OrderController(IMailService mailService)<br>        { _mailService = mailService;<br>        }<br>        public void Post()<br>        {<br>            _mailService.SendMail(mail: new Mail { Content = &quot;an email content&quot;, Reciever = &quot;reciever@gmail.com&quot; });<br>        }<br>        public void Put()<br>        {<br>            _mailService.SendMail(mail: new Mail { Content = &quot;your order updated&quot;, Reciever = &quot;reciever@gmail.com&quot; });<br>        }<br>    }</pre><p>Bu durumda Program.cs üzerinden OrderController nesnesi oluşturulurken artık hangi mail servisini kullanacağı bilgisi için bir parametre istiyor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/515/1*4a8wPnCxolp1NeTjXoiNKw.png" /></figure><p>Gmail servisini kullanmak istiyorsak:</p><pre>var orderController = new OrderController(new GmailService());<br>orderController.Post();</pre><p>Outlook servisini kullanmak istiyorsak:</p><pre>var orderController = new OrderController(new OutlookMailService());<br>orderController.Post();</pre><p>Proje kaynak kodunda başka herhangi bir noktada değişim yapmadan iki servis arasında geçiş sağlayabiliyoruz. Başka bir mail servis için sistemi uyarlamak da oldukça kolay.</p><p>Örneğin Yandex email servis için gerekli servis yazılır.</p><pre>public class YandexMailService : IMailService<br>    {<br>        public void SendMail(Mail mail)<br>        {<br>            Console.WriteLine($&quot;yandex mail service/send mail\n{mail.Reciever}\n{mail.Content}&quot;);<br>        }<br>    }</pre><p>Ve tek değişiklik ile sistem yandex mail servisi kullanmaya başlar.</p><pre>var orderController = new OrderController(new YandexMailService());<br>orderController.Post();</pre><p>Kodun çıktısı:</p><pre>yandex mail service/send mail<br>reciever@gmail.com<br>an email content</pre><h3>IoC Container</h3><p>Mail servis yönetimini esnek hale getirdik, şimdi ise bağımlılık yönetimini kolaylaştırmak adına inversion of control yapısını nasıl kullanabileceğimize bakacağız.</p><p>Bir konteynır yapısı kurmalıyız. Tüm soyutlamalar ve bu soyutlamaları uygulayacak sınıfları bu konteynır içerisinde eşleştirmeliyiz. Herhangi bir zamanda bir soyutlamayı kullanacağımız zaman konteynırdan eşlendiği sınıfı çağırmalı ve o nesne üzerinden işlemlerimize devam etmeliyiz, şöyle ki:</p><h3>Konteynır</h3><p>Bağımlılık tablosunu bir konteynır içerisinde tutacağız.</p><pre>public class SimpleContainer<br>{<br>}</pre><p>Hangi soyutlamaya hangi sınıftan nesne üretilmesini istediğimizi burada saklamamız gerekiyor. Bunun için HashMap veri yapısını kullanacağız. C# içerisinde Dictionary bu veri yapısını uygulamamızı sağlıyor. Burada tutacağımız değerler hangi soyut tipe hangi somut sınıfın denk geldiğini tutmak.</p><pre>public class SimpleContainer<br>{<br>    private readonly Dictionary&lt;Type, Type&gt; _map = new Dictionary&lt;Type, Type&gt;();<br>}</pre><p>Bağımlılık tablosuna yeni bir değer eklemek için Register metodu oluşturuyoruz.</p><pre>public class SimpleContainer<br>{<br>    private readonly Dictionary&lt;Type, Type&gt; _map = new Dictionary&lt;Type, Type&gt;();<br>    public void Register&lt;TAbstraction, TImplementation&gt;()<br>    {<br>        _map[typeof(TAbstraction)] = typeof(TImplementation);<br>    }<br>}</pre><p>Bağımlılık tablosundan bir soyutlamaya karşılık gelen sınıftan bir nesne elde etmek için Resolve metodunu oluşturuyoruz.</p><pre>public TAbstraction Resolve&lt;TAbstraction&gt;()<br>{<br>    Type type = _map[typeof(TAbstraction)];<br>    return (TAbstraction)Activator.CreateInstance(type);<br>}</pre><p>Artık bağımlılıkları tek noktadan yönetmek için new anahtar kelimesini kullanmayacağız ve tüm bağımlılıkları SimpleContainer’a ekleyip SimpleContainer’dan isteyerek çözüyoruz.</p><pre>SimpleContainer container = new SimpleContainer();<br>container.Register&lt;IMailService, YandexMailService&gt;();<br><br>IMailService service = container.Resolve&lt;IMailService&gt;();<br>var orderController = new OrderController(service);<br>orderController.Post();</pre><p>Artık konteynırda eşleşmiş olan servislerden ihtiyacımız olan servisi alıp Sipariş Yönetim sınıfına enjekte ediyor. (kurucu metoduna parametre olarak veriyor)</p><p>Başka bir mail servisini kullanmak istediğimizde ise sadece konteynırdaki map tablosuna yeni eşleşmeyi kaydetmemiz gerekiyor.</p><pre>container.Register&lt;IMailService, GmailService&gt;();</pre><p>Kod çıktısı:</p><pre>Gmail Service sent an email.<br>sender:sender<br>reciever:reciever@gmail.com<br>content:an email content</pre><p>Okuduğunuz için teşekkür ederim.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98e64450251b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Are JavaScript Callback Functions?]]></title>
            <link>https://busenursahin.medium.com/what-are-javascript-callback-functions-637415647308?source=rss-67c9aefc0c68------2</link>
            <guid isPermaLink="false">https://medium.com/p/637415647308</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software]]></category>
            <dc:creator><![CDATA[Buse Nur Şahin]]></dc:creator>
            <pubDate>Sat, 30 Sep 2023 08:10:42 GMT</pubDate>
            <atom:updated>2023-09-30T08:12:23.174Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we will explore callback functions in JavaScript, which allow us to perform asynchronous operations, and understand where they are used. We will simulate a real-life scenario to grasp their concept.</p><h3>What is a Callback Function?</h3><p>Callback functions are structures used to pass one function as an argument to another function. They are employed when we want something else to happen after an operation is completed.</p><p>JavaScript operates synchronously and is single-threaded, but due to its nature and applications, it frequently encounters asynchronous tasks. We often want to continue with other tasks without waiting for lengthy operations to finish, avoiding getting blocked. However, if there is a dependent operation on the output of a time-consuming task in the subsequent lines, the code won’t work as intended.</p><p>So, how will other tasks dependent on these time-consuming operations know when they are completed, whether they succeeded, or encountered errors? This is where callbacks come into play.</p><blockquote>As you can see, asynchronous JavaScript functions like setTimeout, setInterval, fetch, etc., always require callback functions. We have just discussed the reasons behind this.</blockquote><p>In essence, callback functions are functions passed as parameters to another function, called within that function, and they assist in the consistent operation of interdependent asynchronous tasks. As mentioned earlier, asynchronous JavaScript functions like setTimeout, setInterval, fetch, etc., always require callback functions.</p><h3>Scenario</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*mBbzR0qc_sreydav" /></figure><p>In our web application, we have a file upload process. Since this operation takes a considerable amount of time, instead of presenting the user with a frozen screen, we want to provide feedback during the upload, showing what percentage of the task is completed based on the uploaded file size.</p><h3>Step 1:</h3><p>Let’s create an upload function that accepts a callback. This upload function will have a current value representing the instantaneous progress and a total value indicating the entire duration of the task, similar to the uploaded file size.</p><p>Think of the upload function as having an instantaneous value that changes as the upload progresses, and a total value representing the file size.</p><pre>function upload(callback) {<br>  var current = 0;<br>  var total = 5;<br>  var interval = setInterval(() =&gt; {<br>    current += 1;<br>    callback(current, total);<br>  if (current == total) clearInterval(interval);<br>    }, 1000);<br>}</pre><p>Here, we have a task with an initial value of 0 and a target value of 5. This task increases by 1 unit every second, triggering the callback with two arguments: current progress and total value.</p><h3><strong>Step 2:</strong></h3><p>Let’s invoke the upload function with a callback argument.</p><pre>upload((current, total) =&gt; {<br>  progress.innerHTML = current / total * 100 + &quot;%&quot;;<br>});</pre><h3>Step 3:</h3><p>Display on the screen.</p><pre>Loading..<br>&lt;div id=&quot;progress&quot;&gt;&lt;/div&gt;</pre><h3>Conclusion</h3><p>We have learned how to pass callback functions to higher-order functions, which are functions that take other functions as arguments, and how the main function operates. This knowledge enables us to perform asynchronous tasks in JavaScript, allowing us to execute multiple operations simultaneously and providing a seamless user experience, despite JavaScript being single-threaded. You can access the application code <a href="https://jsfiddle.net/86dsa9bk/18/">here</a>.</p><p>For further reading on callback functions, you can check out <a href="https://developer.mozilla.org/en-US/docs/Glossary/Callback_function">this article</a>.</p><p>For a real file upload process, you can use Ajax upload with a progress event and pass a callback that takes an event argument. You can control the upload moment using event.loaded and event.total. For detailed information, refer to the <a href="https://www.educative.io/answers/how-to-add-a-progress-bar-to-your-file-upload-code-using-ajax">article</a> mentioned above.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=637415647308" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design Patterns — Chain of Responsibility]]></title>
            <link>https://busenursahin.medium.com/sorumluluk-zinciri-tasar%C4%B1m-deseni-nedir-chain-of-responsibility-26c7a6a7fdcc?source=rss-67c9aefc0c68------2</link>
            <guid isPermaLink="false">https://medium.com/p/26c7a6a7fdcc</guid>
            <category><![CDATA[tasarım-desenleri]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[chain-of-responsibility]]></category>
            <category><![CDATA[sorumluluk-zinciri]]></category>
            <category><![CDATA[desing-pattern]]></category>
            <dc:creator><![CDATA[Buse Nur Şahin]]></dc:creator>
            <pubDate>Mon, 18 Sep 2023 08:48:56 GMT</pubDate>
            <atom:updated>2023-12-05T10:57:46.745Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nShat_zqNBby0fS4" /><figcaption>Photo by Judson Moore on Unsplash</figcaption></figure><h3>Nedir?</h3><p><strong><em>Sorumluluk Zinciri -Chain of Responsibility (CoR)-</em></strong> tasarım deseni (behavioral design patterns) davranışsal tasarım desenlerinden biridir.</p><p><strong><em>Davranışlar tasarım desenleri</em></strong>; yazılım bileşenlerinin nasıl etkileşimde bulunacağını ve nasıl işbirliği yapacaklarını yöneten şablonlardır. Tasarım deseni olmaları hasebiyle tekrar kullanılabilirlik sağlamış olur ve kodu isterlerin değişimine direnç göstermeyen esnek yapılı bir hale getirir.</p><h3>UML Diyagram</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/433/0*1NPNMgP1WHQYM5JR" /><figcaption><a href="https://www.dofactory.com/net/chain-of-responsibility-design-pattern">https://www.dofactory.com/net/chain-of-responsibility-design-pattern</a></figcaption></figure><blockquote>Sorumluluk zincirini prensibinde <strong><em>bağlı listelerdeki düğüm yapısına benzeyen</em></strong> bir yapı kullandığımızı düşünebiliriz.</blockquote><blockquote><strong>Zincir</strong>ini birden çok <strong>halka</strong>sı olur, bu halkalara(chain) <strong>işleyici(handler) </strong>denir.<strong> </strong>İşleyicilerin ortak noktası <strong>işleyeceği nesnedir</strong>. İşleyicilerin hepsi <strong><em>ortak bir sınıftan</em></strong> türer (bağlı listelerdeki <strong><em>düğüm</em></strong> gibi).</blockquote><blockquote>İşleyiciler bir sonraki işleyici sınıfın bilgisini (referansını) tutar (bağlı listelerdeki node.next yapısı gibi) ve bu bilgiyi esnek biçimde güncelemek için bir set methodu kullanır.</blockquote><p>Gelen istek oluşturulan sıraya göre işleyicilere (handler) verilir ve eğer süreç bir işleyici tarafından sonlandırılmadıysa bir sonraki düğüm olmayana dek devam eder.</p><ul><li>UML diyagramındaki <strong>Handler</strong> sınıfı halkalarınızın ortak işlevi olan HandleRequest veya <strong>ProgressRequest</strong> olarak isimlendirilebilen <strong><em>isteği işleme</em></strong> methoduna sahiptir.</li><li>İşleme methodu soyuttur, sınıfların <strong>polimorfik</strong> özellik göstermesi için soyut olmalıdır ki her işleyici kendi üstlendiği göreve göre methodu ezebilsin (override)</li><li>Her Handler (işleyici) bir sonraki handler(<strong>Successor)</strong> bilgisini taşır ve bu değer <strong>setSuccessor</strong> methodu ile düzenlenebilir.</li></ul><blockquote>Yapının esnekliği buradan gelir, isterlere göre zincir değişik şekilde oluşturulabilir ve değişikliğe direnç göstermez.</blockquote><p><strong>Esnek bağlı olan bu yapıda zinciri oluşturan halkaların ortak özelliği ise aldıkları yani işleyecekleri istek, uygulamada buna <em>Request</em> diyeceğiz.</strong></p><p>Şimdi gerçek hayattan bir örnek verip bir senaryo üzerinde kullandığımız yapıları simule ederek açıklayalım.</p><h3>Gerçek Hayattan Bir Örnek</h3><p>Gerçek hayatta bu prensibin karşımıza çıktığı yerler var mı?</p><p>Müşteri hizmetlerini aradığınızda sizi işlemleri sıralayarak ve sesli yanıt veya tuşlama ile ilgili kişiye ulaştırdığı senaryoda sorumluluk prensibi benzeri bir yapı işliyor. Çünkü sırayla kontroller sağlanarak eğer zincirin şuanki halkası isteğinizi karşılayabiliyorsa ona yönlendiriliyor eğer karşılayamıyorsa bir sonraki halkaya aktarılıyorsunuz ta ki isteğinizi karşılayabilecek yetkiliye ulaşana kadar.</p><h3>Gerçek Hayat Senaryosu</h3><p>.Net teknolojileriyle MVC web uygulaması veya WebApi geliştirdiyseniz <strong>Middleware</strong> yapısını duymuşsunuzdur. Middleware yapısının arkasında yatan kavram da Sorumluluk Zinciri Prensibidir.</p><p><strong>Bir web uygulamasında yetkilendirme olsun, doğrulama olsun, swagger api desteklesin, gelen istekler şu desene göre controller’a yönlendirilsin, view olsun-olmasın gibi tüm kararları ara yazılım denilen “middleware” ler ile düzenleyebiliriz.</strong></p><h3>Uygulama</h3><p>Bir console uygulaması oluşturup web uygulamalarındaki middleware işleyişini simüle ederek konuyu daha iyi açıklamaya çalışacağım.</p><p>Senaryomuz şöyle: Kullanıcı sisteme istek atarak (request) sipariş oluşturabilir ancak siparişin oluşması için atılan istek bazı şartları sağlamalıdır.</p><ol><li>İstek içerisinde henüz geçerliliğini yitirmemiş ve bir değere sahip <strong>token</strong> olmalıdır. Bu token bize <strong>kullanıcının geçerli olup olmadığı</strong> bilgisini verecek. Eğer token’ın bir değeri var ve henüz expired olmamış ise yani hala <strong>geçerli ise istek işlenmeye devam edebilir, aksi takdirde kullanıcı doğrulanamadı cevabını dönerek isteği sonlandırmalıdır</strong>. Keza diğer işlemlerin uygulanmasının bir anlamı yoktur.</li><li>İstek içerisindeki token’da <strong>rollerin</strong> bulunduğu bir liste olmalıdır, eğer bu rol listesinde <strong>“Customer” kullanıcı tipi varsa istek işlenmeye devam etmelidir aksi takdirde istek işlenişi sonlanmalıdır.</strong></li><li>İstek içerisindeki sipariş verilen üründen <strong>yeterli adette olmalıdır</strong>. Kodu dallandırıp budaklandırmamak adına burada <strong>Order</strong> diye bir nesnenin içerisindeki <strong>InStock</strong> alanına bakacağız eğer true ise stok vardır, <strong>false ise stok yoktur ve</strong> <strong>sipariş doğrulanmadan istek cevabı dönülmelidir</strong>.</li><li>Eğer kullanıcı doğrulandı ise ve kullanıcı yetkisi varsa ve sipariş verilen ürün de stokta varsa sipariş işlemi gerçekleştirilmelidir ve cevap dönmelidir. İlgili işlemleri yapmak için <strong>Controller</strong> sınıfına yönlendirilmesi gerekir.</li></ol><p>İstek için oluşturduğumuz class şöyle olabilir:</p><pre>namespace ChainOfResponsibility.Data<br>{<br>    public class Request<br>    {<br>        public Token Token { get; set; }<br>        public Order Order { get; set; }<br>    }<br>    public class Order<br>    {<br>        public int Id { get; set; }<br>        public double Price { get; set; }<br>        public bool InStock { get; set; }<br>    }<br>    public class Token<br>    {<br>        public string Value { get; set; }<br>        public string[] Roles { get; set; }<br>        public bool IsExpired { get; set; }<br>    }<br>}</pre><p>Token ve Order alanlarının nasıl doldurulacağını uygulama yaparken göreceğiz, nasıl kullanılacağını ise az önceki adımlarda açıklandı.</p><p>Bu isteğe bir cevap dönmemiz gerekli. <strong>İşlem tamamlandı ise başarılı, yarıda kesildi ise başarısız sonuç dönerek kullanıcıya bir mesaj döndürmeliyiz.</strong></p><p>Cevap için oluşturduğumuz sınıf ise Response:</p><pre>namespace ChainOfResponsibility.Data<br>{<br>    public class Response<br>    {<br>        public bool Success { get; set; }<br>        public string Message { get; set; }<br>    }<br>}</pre><p>Şimdi sorumluluk zinciri yapısı ile isteği işlememiz gerekiyor. Bunun için UML’de de belirtildiği gibi bir <strong>Handler</strong> sınıfı oluşturuyoruz. Bu <strong>abstract bir sınıf olacak</strong> çünkü içerisinde kalıtım alan sınıfların ortak kullanacağı ve gövdesi olan bir method barındıracak(setSuccessor) ve bu method sayesinde her işleyicinin (handler) bir sonraki işleyicisinden haberi olmuş olur ve böylece <strong><em>BAĞIMLILIK olmadan bu yapı gerçekleşir.</em></strong></p><pre>namespace ChainOfResponsibility.Handlers<br>{<br>    public abstract class Handler<br>    {<br>        public Handler Successor { get; set; }<br>        public void SetSuccessor(Handler successor)<br>        {<br>            this.Successor = successor;<br>        }<br>        public abstract Response ProcessRequest(Request request);<br>    }<br>}</pre><p>Yukarıda verdiğimiz 4 adım için ilgili <strong>ConcreteHandler</strong> yani Handler soyut sınıfından türetilen somut sınıfları üreteceğiz. Sırasıyla authentication, authorization, validation ve controller olarak ilerleyeceğiz.</p><p>Çünkü</p><ol><li>Adımdaki token geçerliliği <strong>authentication</strong> (kullanıcı doğrulaması) işlemidir.</li><li>Adımdaki rol tabanlı kullanıcı doğrulaması bir <strong>authorization</strong> (kullanıcı yetkilendirme) işlemidir.</li><li>Adımdaki stok bilgisi kontrolü bir doğrulama (<strong>validation</strong>) işlemidir. (Fluent validation kullananlar oradaki yapıdan anımsayacaktır)</li><li>Adımda ise tüm şartları sağlayan bir sipariş nesnesi elimizde olacağı için bu nesneyi web simülasyonundaki <strong>controller’a</strong> vermemiz gerekecek ki ilgili işlemi yapıp başarılı sonuç dönsün.</li></ol><h3><strong>Authentication Handler</strong></h3><pre>namespace ChainOfResponsibility.Handlers<br>{<br>    public class AuthenticationHandler : Handler<br>    {<br>        public override Response ProcessRequest(Request request)<br>        {<br>            if (request.Token.IsExpired || string.IsNullOrEmpty(request.Token.Value))<br>            {<br>                return new Response<br>                {<br>                    Success = false,<br>                    Message = &quot;Kullanıcı doğrulanamadı.&quot;<br>                };<br>            }<br>            else<br>            {<br>                return this.Successor.ProcessRequest(request);<br>            }<br>        }<br>    }<br>}</pre><h3><strong>Authorizaiton Handler</strong></h3><pre>namespace ChainOfResponsibility.Handlers<br>{<br>    public class AuthorizationHandler : Handler<br>    {<br>        public override Response ProcessRequest(Request request)<br>        {<br>            if (!request.Token.Roles.Contains(&quot;Customer&quot;))<br>            {<br>                return new Response<br>                {<br>                    Success = false,<br>                    Message = &quot;Kullanıcı yetkisi doğrulanamadı&quot;<br>                };<br>            }<br>            else<br>            {<br>                return this.Successor.ProcessRequest(request);<br>            }<br>        }<br>    }<br>}</pre><h3><strong>Validation Handler</strong></h3><pre>namespace ChainOfResponsibility.Handlers<br>{<br>    public class ValidationHandler : Handler<br>    {<br>        public override Response ProcessRequest(Request request)<br>        {<br>            if (!request.Order.InStock)<br>            {<br>                return new Response<br>                {<br>                    Success = false,<br>                    Message = &quot;Sipariş oluşturulamadı, stok yetersiz&quot;<br>                };<br>            }<br>            else<br>            {<br>                return this.Successor.ProcessRequest(request);<br>            }<br>        }<br>    }<br>}</pre><h3><strong>Controller Handler</strong></h3><pre>namespace ChainOfResponsibility.Handlers<br>{<br>    public class ControllerHandler : Handler<br>    {<br>        public override Response ProcessRequest(Request request)<br>        {<br>            return new Response<br>            {<br>                Success = true,<br>                Message = &quot;Sipariş başarıyla oluşturuldu&quot;<br>            };<br>        }<br>    }<br>}</pre><p>Oluşturduğumuz bu yapıyı <strong>Program.cs</strong> içerisinde kullanacağız.</p><h4>Sorumluluk zincirini oluşturalım</h4><pre>using ChainOfResponsibility.Data;<br>using ChainOfResponsibility.Handlers;<br>Handler authentication = new AuthenticationHandler();<br>Handler authorization = new AuthorizationHandler();<br>Handler validation = new ValidationHandler();<br>Handler controller = new ControllerHandler();<br>authentication.SetSuccessor(authorization);<br>authorization.SetSuccessor(validation);<br>validation.SetSuccessor(controller);</pre><h4>Kullanıcıdan alınacak isteği oluşturalım</h4><pre>Request request = new Request<br>{<br>    Token = new Token<br>    {<br>        IsExpired = true,<br>        Roles = new string[] {},<br>        Value = &quot;token&quot;<br>    },<br>    Order = new Order<br>    {<br>        Id = 1,<br>        InStock = false,<br>        Price = 10<br>    }<br>};</pre><p>İlgili isteği sorumluluk zincirine vererek cevabını yazdıralım.</p><pre>Response response = authentication.ProcessRequest(request);<br>if (response.Success)<br>    Console.ForegroundColor = ConsoleColor.Green;<br>else<br>    Console.ForegroundColor = ConsoleColor.Red;<br>System.Console.WriteLine(response.Message);<br>Console.ResetColor();<br>Console.ReadLine();</pre><p>Yukarıda verilen ve kullanıcı isteğini temsil eden request nesnesinde token <strong>isExpired alanı true olduğu</strong> için token geçerlilik süresini yitirdiğini anlıyoruz. Bu durumda sorumluluk zincirinin ilk halkası olan authentication kısmında başarısız sonuç dönecek ve success false durumunda console color red verildiği için hata mesajı kırmızı yazacak.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/0*b7cJCqVH5NW4Ci1C" /></figure><p>Token IsExpired=false yapıp tekrar deneyelim, bu durumda token expire olmadığı için yani geçerli olduğu için ve token value da geçerli bir string olduğu için (bu değerin kontrolü authentication handler’da null veya empty değil olarak yapılıyor)</p><pre>IsExpired = false,</pre><p>Bu durumda kullanıcı doğrulanır ancak roles dizisi boş olduğu için yetki hatası verir ve çıktı şöyle olur.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/0*e7YQ1qByYbDeiQEo" /></figure><p>Şimdi roles içerisinde customer rolü ekleyelim ve tekrar deneyelim. Yukarıdaki kullanıcı doğrulaması geçerli olduğu durumda progress handler methodu bir sonraki halkanın progress handler methodunu işletip sonucunu döndürür.</p><pre>Roles = new string[] {&quot;Customer&quot;},</pre><p>Bu durumda authorization handler’a gidecek ve roles dizisinde Customer olup olmadığına bakacak. Customer tanımlaması roller içerisinde var olduğu için ise bir sonraki halkaya atlayacak ve stok kontrolüne bakacak.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/0*_locz3QQ-vFesggG" /></figure><p>Şimdi isteğin başarılı sonuç verebilmesi için order içerisindeki InStock alanını true yaparak stok olan bir ürünü sipariş vermek isteyelim.</p><pre>InStock = true,</pre><p>Böylece validation handler’dan geçip controller handler’a gelebilsin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/0*ud3rEq7Ic9TPQFdp" /></figure><p>İsteğin son hali controller handler’ kadar ilerleyebildiği için ve son halkada response başarılı döndüğü için Program.cs’deki success == true ise kontrolü sebebiyle konsol rengi yeşil olarak bastı.</p><h3>Sonuç</h3><p>Nedir? kısmında söylemiştik: Davranışsal tasarım desenleri durum değişikliğine karşı nasıl ilerleyeceğimizi tasarlamak için kullanılır. Uygulama üzerinde de gelen Request’in değişimiyle kodun nasıl davrandığını görmüş olduk.</p><p>Sorumluluk zinciri tasarım desenini kullanarak esnek bağlı yapılar oluşturabiliriz. Böylece proje içindeki kontrollerimizi temiz bir şekilde kodlayabilir, karar değişimlerine esnek cevap veren, if-else satırlarında boğulmayan kodlar yazabiliriz.</p><p>Bu konu hakkında daha fazla okuma yapmak için aşağıdaki makalelerden faydalanabilirsiniz.</p><p><a href="https://www.dofactory.com/net/chain-of-responsibility-design-pattern">https://www.dofactory.com/net/chain-of-responsibility-design-pattern</a></p><p><a href="https://refactoring.guru/design-patterns/chain-of-responsibility">https://refactoring.guru/design-patterns/chain-of-responsibility</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26c7a6a7fdcc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Instagram Clone with .Net MAUI (Part 1)]]></title>
            <link>https://busenursahin.medium.com/instagram-clone-with-net-maui-part-1-f32cc28220bf?source=rss-67c9aefc0c68------2</link>
            <guid isPermaLink="false">https://medium.com/p/f32cc28220bf</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[maui]]></category>
            <category><![CDATA[mvvm]]></category>
            <dc:creator><![CDATA[Buse Nur Şahin]]></dc:creator>
            <pubDate>Tue, 20 Jun 2023 21:11:57 GMT</pubDate>
            <atom:updated>2023-09-13T13:18:06.324Z</atom:updated>
            <content:encoded><![CDATA[<h3>Instagram Clone with .Net MAUI</h3><h4>In this Medium post, we will start building an Instagram Clone project using .Net MAUI, a relatively new technology compared to other cross-platform application development frameworks.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cQpAF1AXDEj8nuWw" /><figcaption>Photo by <a href="https://unsplash.com/@neonbrand?utm_source=medium&amp;utm_medium=referral">Kenny Eliason</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>As you know, Instagram is a complex application with multiple pages, modules, and various features. Therefore, it’s not possible to build the entire app at once :) Since I want to work with Maui layouts and lists, I decided to start with the Profile page, which contains different layouts and lists. In this article, we will focus on coding the part where posts are listed in a grid.</p><blockquote>At this stage, we won’t be using a REST API, so we will proceed with dummy data. Since the majority of our data consists of photographs, we will use <a href="https://picsum.photos/">Lorem Pictures</a>.</blockquote><p>Even though we will be using dummy data, we will still strive to achieve clean code by using MVVM and data binding. It will be an enjoyable coding adventure. Let’s get started!</p><h3>Let’s break down the page we want to code.</h3><ol><li>Profile Information:</li><li>Featured Stories</li><li>TabBar for transitioning between Posts, Reels, etc.</li><li>Grid Posts</li><li>Navigation Bar</li></ol><h3>Let’s code the Posts section.</h3><p>When we see this part, we might think of a Grid Layout at first, but let’s not jump into it right away! Because the grid layout is used for grid arrangements, but here we will create a list since the underlying data source will be a list, and we will make it visible.</p><h3>We will choose the List structure.</h3><p>When looking at the Maui view options, you will come across two types of lists: ListView and CollectionView. Since ListView only allows us to create vertical lists, it is clear that we should choose CollectionView without even discussing its other advantages.</p><h3>What will be listed in the CollectionView?</h3><p>We need to bind the post data to the list so that we can display it. Here, .NET MAUI suggests implementing the MVVM design pattern. So, let’s create a model view for the MainPage section and generate the necessary dummy data.</p><p>But before that, we need to create our basic models so that we can use them within the ModelView.</p><pre>namespace InstagramClone.Models<br>{<br>    public class Post<br>    {<br>        public int Id { get; set; }<br>        public string ImagePath { get; set; }<br>        public string Text { get; set; }<br>    }<br>}</pre><p>Now, let’s create the ViewModel and assign the Dummy Data.</p><pre>using System;<br>using System.Collections.ObjectModel;<br>using System.Windows.Input;<br>using InstagramClone.Models;<br><br>namespace InstagramClone.ViewModels<br>{<br>    public class MainPageViewModel<br>    {<br>        private IList&lt;Post&gt; _list;<br>        public IList&lt;Post&gt; List<br>        {<br>            get<br>            {<br>                if (_list == null)<br>                    _list = new ObservableCollection&lt;Post&gt;();<br>                return _list;<br>            }<br>            set<br>            {<br>                _list = value;<br>            }<br>        }<br>        void Bind()<br>        {<br>            List.Clear();<br>            for (int i = 0; i &lt; 10; i++)<br>            {<br>                List.Add(new Post<br>                {<br>                    Id = i,<br>                    ImagePath = $&quot;https://picsum.photos/id/{10 + i}/2500/1667&quot;,<br>                    Text = $&quot;{i}st nature post&quot;<br>                });<br>            }<br>        }<br>        public MainPageViewModel()<br>        {<br>            Bind();<br>        }<br>    }<br>}</pre><h3>Data Binding</h3><p>To display the data we have created on the page, we need to define the ViewModel we created as the BindingContext for the page.</p><pre>using InstagramClone.ViewModels;<br>namespace InstagramClone;<br><br>public partial class MainPage : ContentPage<br>{<br> public MainPage()<br> {<br>  InitializeComponent();<br>        this.BindingContext = new MainPageViewModel();<br>    }<br>}</pre><h3>Now, Let’s Create the CollectionView to Display The Posts</h3><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot; ?&gt;<br>&lt;ContentPage xmlns=&quot;http://schemas.microsoft.com/dotnet/2021/maui&quot;<br>             xmlns:x=&quot;http://schemas.microsoft.com/winfx/2009/xaml&quot;<br>             x:Class=&quot;InstagramClone.MainPage&quot;           <br>&gt;<br>  &lt;ScrollView&gt;<br>        &lt;!-- Content --&gt;<br>        &lt;StackLayout &gt;                <br>                &lt;CollectionView ItemsSource=&quot;{Binding List}&quot;&gt;<br>                    &lt;CollectionView.ItemsLayout&gt;<br>                        &lt;GridItemsLayout<br>                         Orientation=&quot;Vertical&quot;<br>                         Span=&quot;3&quot;<br>                         HorizontalItemSpacing=&quot;4&quot;<br>                         VerticalItemSpacing=&quot;4&quot;<br>                        /&gt;<br>                    &lt;/CollectionView.ItemsLayout&gt;<br>                    &lt;CollectionView.ItemTemplate&gt;<br>                        &lt;DataTemplate&gt;<br>                            &lt;Image Aspect=&quot;AspectFill&quot; HeightRequest=&quot;130&quot; WidthRequest=&quot;130&quot; Source=&quot;{Binding ImagePath}&quot;/&gt;<br>                        &lt;/DataTemplate&gt;<br>                    &lt;/CollectionView.ItemTemplate&gt;<br>                &lt;/CollectionView&gt;<br>        &lt;/StackLayout&gt;<br>    &lt;/ScrollView&gt;<br>&lt;/ContentPage&gt;</pre><p>After creating the <strong>ContentPage</strong>, as there will be other sections arranged vertically on this page in the future, we defined a <strong>StackLayout</strong>. To enable scrolling when the number of posts increases, we wrapped this StackLayout with a <strong>ScrollView</strong>.</p><p>To list the posts, as mentioned earlier, we defined a <strong>CollectionView</strong>. We bound it to a property of the ViewModel as the data source.</p><p>The layout is a <strong>Grid Layout</strong> with 3<strong> columns</strong>. We defined Vertical and Horizontal GridSpacing to have small gaps between the posts.</p><p>For the item template, we used an <strong>Image</strong> control with a width and height of 130px. We bound the ImagePath property of each item from the ViewModel and set <strong>AspectFill</strong> to ensure that each image fills the width and height without distortion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*eAgTfsyVuy_wQ8uUD7jkJw.png" /></figure><p>In this article, we have seen how to create the Instagram grid posts section by developing a Maui multi-platform app. You can follow the series for more content.</p><p>Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f32cc28220bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an Onion Architecture Solution with Dotnet CLI]]></title>
            <link>https://busenursahin.medium.com/building-an-onion-architecture-solution-with-dotnet-cli-5859fd0e534f?source=rss-67c9aefc0c68------2</link>
            <guid isPermaLink="false">https://medium.com/p/5859fd0e534f</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[onionarchitecture]]></category>
            <category><![CDATA[dotnet-cli]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <dc:creator><![CDATA[Buse Nur Şahin]]></dc:creator>
            <pubDate>Thu, 26 Jan 2023 08:55:31 GMT</pubDate>
            <atom:updated>2023-01-26T09:00:16.101Z</atom:updated>
            <content:encoded><![CDATA[<h4>In this article, we will briefly answer the question of “How we can create a project using onion architecture via dotnet cli?”</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/0*vECZGjtmm9gWDn1i.jpg" /><figcaption><a href="https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html">https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html</a></figcaption></figure><p>We use architectures like the Onion architecture to clean code and build extensible code structure because we want to have a clean code and a clean architecture, that is, a structure that is loosely coupled and does not resist change. <br>So, we divide the application into layers and minimize the dependency between these layers and obtain a loosely coupled structure.</p><h3>Structure of Onion Architecture</h3><p>The onion architecture can be realized in different ways, basically it is based on having a domain in the core and the outer layers referencing the layers close to the core. In this article, we will build a structure like this;</p><h4>1. Core<br>- Application</h4><p>It is the layer where the abstraction operations of the project are performed, it is located in the core of the project.</p><h4>- Domain</h4><p>It covers the basic domain related (e.g. Entities) areas of the project, located in the project core.</p><h4>2. Infrastructer<br>- Persistence</h4><p>Database related processes are located here. Thus, unlike the traditional tiered architecture, the domain, not the database processes, is in the core.</p><h4>- Infrastructer</h4><p>Where service implementations of external resource access are done.</p><h4>3. Presentation</h4><p>The presentation layer is the layer where the project is presented to the user, in this article we will present using an api.</p><p>In short, there are many projects that we will create as a library (classlib) to create the onion architecture structure we mentioned with dotnet cli, and there are also projects that will refer each other, whether it is close to the center of the onion or outside, it is all about this referencing, that is, being dependent.</p><p>For Dotnet CLI usage</p><p><a href="https://learn.microsoft.com/tr-tr/dotnet/core/tools/">.NET CLI</a></p><h3>Let’s name the project Cleany.</h3><pre>mkdir Cleany &amp;&amp; cd Cleany</pre><pre>dotnet new sln</pre><pre>dotnet sln Cleany.sln list</pre><p>The project folder and the sln file is created, list command to read the projects included in the sln file.</p><h4>Core/Domain Layer</h4><pre>dotnet new classlib -o Core/Domain</pre><pre>dotnet sln Cleany.sln add Core/Domain</pre><pre>dotnet sln Cleany.sln list</pre><h4>Core/Application Layer</h4><pre>dotnet new classlib -o Core/Application <br>&amp;&amp; dotnet sln Cleany.sln add Core/Application</pre><blockquote>Unlike the traditional layered architecture, the Application layer is the layer that refers to the Domain Layer, not the Data Access Layer. Thus there is less dependency on Data Access Operations and hence loose coupling. The loose coupling in the Onion architecture is due to the fact that interfaces are created in the application layer, i.e. <strong>the abstraction is done here</strong>.</blockquote><h4>Infrastructure Layer</h4><pre>dotnet new classlib -o Infrastructure/Infrastructure <br>&amp;&amp; dotnet sln Cleany.sln add Infrastructure/Infrastructure <br>&amp;&amp; rm Infrastructure/Infrastructure/Class1.cs</pre><blockquote>The last of the commands, delete file, is to delete the file named Class1.cs that comes by default when classlib is created via dotnet cli.</blockquote><h4>Persistence Layer</h4><pre>dotnet new classlib -o Infrastructure/Persistence<br>&amp;&amp; dotnet sln Cleany.sln add Infrastructure/Persistence<br>&amp;&amp; rm Infrastructure/Persistence/Class1.cs</pre><h4>Presentation Layer / Web API</h4><pre>dotnet new webapi -o Presentation/API <br>&amp;&amp; dotnet sln Cleany.sln add Presentation/API</pre><blockquote>When all these operations are done and sln projects are listed, the following image is created.</blockquote><pre>dotnet sln Cleany.sln list</pre><pre>Project(s)<br>----------<br>Core/Domain/Domain.csproj<br>Core/Application/Application.csproj<br>Infrastructure/Infrastructure/Infrastructure.csproj<br>Presentation/API/API.csproj</pre><h3>Reference addition operations</h3><pre>dotnet add Core/Application/Application.csproj<br>reference Core/Domain/Domain.csproj</pre><pre>&lt;ItemGroup&gt;<br>    &lt;ProjectReference Include=&quot;..\Domain\Domain.csproj&quot; /&gt;<br>&lt;/ItemGroup&gt;</pre><blockquote>Now when we come to the project file of the Application Layer, that is, when we come to Application.csproj, when we read inside, when we open it, we see that the domain has been added here, so that our <strong>enterprice assets will be available in the application layer</strong>.</blockquote><pre>dotnet add Infrastructure/Infrastructure/Infrastructure.csproj<br>reference Core/Application/Application.csproj</pre><pre>dotnet add Infrastructure/Persistence/Persistence.csproj<br>reference Core/Application/Application.csproj</pre><blockquote>Since the Application layer also references the domain layer, we also access the domain, at this point, let’s reference the infrastructure layers for the Presentation Layer.</blockquote><pre>dotnet add Presentation/API/API.csproj <br>reference Infrastructure/Infrastructure/Infrastructure.csproj <br><br>dotnet add Presentation/API/API.csproj <br>reference Infrastructure/Persistence/Persistence.csproj</pre><p>We talked about how we can easily set up the solution structure without using Visual Studio and how we can do this using the terminal, and as an example, we realized the onion architecture.</p><p><strong><em>Thanks for reading</em></strong></p><h4>Resources</h4><ul><li><a href="https://learn.microsoft.com/en-us/dotnet/core/tools/dotnet-sln">dotnet sln command - .NET CLI</a></li><li><a href="https://learn.microsoft.com/en-us/dotnet/core/tools/dotnet-add-reference">dotnet add reference command - .NET CLI</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5859fd0e534f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>