<?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 Enis Necipoğlu on Medium]]></title>
        <description><![CDATA[Stories by Enis Necipoğlu on Medium]]></description>
        <link>https://medium.com/@enisn?source=rss-4c08bf8ed488------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*gGbaRBbRLMAfW7Y-pa41hg.png</url>
            <title>Stories by Enis Necipoğlu on Medium</title>
            <link>https://medium.com/@enisn?source=rss-4c08bf8ed488------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 21:19:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@enisn/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[Context Engineering: AI İle Çalışmanın Yeni Paradigması]]></title>
            <link>https://enisn.medium.com/context-engineering-ai-i%CC%87le-%C3%A7al%C4%B1%C5%9Fman%C4%B1n-yeni-paradigmas%C4%B1-a60e99353c56?source=rss-4c08bf8ed488------2</link>
            <guid isPermaLink="false">https://medium.com/p/a60e99353c56</guid>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[claude-code]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Enis Necipoğlu]]></dc:creator>
            <pubDate>Tue, 12 May 2026 10:38:37 GMT</pubDate>
            <atom:updated>2026-05-12T10:48:03.411Z</atom:updated>
            <content:encoded><![CDATA[<p>Yapay zeka ile yazılım geliştirme pratikleri baş döndürücü bir hızla değişiyor. Çok değil, birkaç yıl öncesine kadar “Yapay zekayı hacklemek”, “doğru büyülü kelimeleri bulmak” yani <em>Prompt Engineering</em> en değerli yetenek olarak görülüyordu. “Adım adım düşün”, “Bana bir uzman gibi davran” gibi kalıplar her komutun vazgeçilmeziydi.</p><p>Ancak bugün geldiğimiz noktada, modern Büyük Dil Modelleri (LLM) bu basit numaralara ihtiyaç duymayacak kadar gelişti. Devasa boyutlara ulaşan bağlam pencereleri (context windows) sayesinde artık sorun AI’ın <em>nasıl</em> düşüneceği değil, düşünmek için <em>hangi veriye</em> sahip olduğu.</p><p>Tam da bu yüzden, yazılım mühendisliğinde yeni ve çok daha güçlü bir paradigma yükseliyor: <strong>Context Engineering (Bağlam Mühendisliği)</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uJ_gxyqD_KHTTR_T9x3y3g.png" /></figure><h3>Hikaye Anlatıcılığı: Kodu Değil, Vizyonu Paylaşmak</h3><p>Günlük pratiğimde AI Agent’larla (özellikle kod yazarken) iletişim kurarken fark ettiğim en önemli detay şu: Onlara izole, küçük tasklar vermek en büyük hata. “Şu butonu ekle” veya “Bu endpoint’i yaz” dediğinizde, AI en kısa ve en izole yolu seçer. Bu da kod tabanında teknik borç ve kırılganlık yaratır.</p><p>Bunun yerine, genelde her şeye bir <strong>hikaye anlatarak</strong> başlıyorum.</p><p>Önce bağlamı (context) dolduracak bildiğim her şeyi döküyorum. Ardından asıl ulaşmak istediğim <em>nihai amacı</em> (Kuzey Yıldızı’nı) anlatıyorum. Ancak ondan bu nihai amacı hemen gerçekleştirmesini istemiyorum. Aksine, yapmasını istediğim o küçük geliştirmeyi, bu büyük vizyonun bir parçası olarak sunuyorum.</p><p><strong>Bu neden çalışıyor?</strong> Çünkü bu yaklaşım, AI’a <em>Mimari Öngörü</em> (Architectural Foresight) kazandırıyor. Model, istediğim küçük geliştirmenin nihai amaca henüz ulaşmadığını biliyor, ancak gelecekte oraya evrileceğini bildiği için kodu ona göre kurguluyor. Interface’leri, abstract sınıfları ve genişletilebilir (extensible) noktaları bu vizyona uygun olarak bırakıyor. Aslında, tıpkı iyi bir Senior Developer gibi davranmasını sağlıyoruz.</p><h3>Statik ve Dinamik Bağlamın Gücü</h3><p>Peki, modelin her seferinde temiz kod kurallarını, mimari kararları veya isimlendirme standartlarını hatırlamasını nasıl sağlıyoruz? Her komutta bunları tekrar etmek hem yorucu hem de token israfı.</p><p>İşte burada “Context Engineering”in ikinci adımı devreye giriyor: <strong>Bağlamı Yönetmek</strong>.</p><p>Mimariyi ve desenleri (Architectural Grounding) her seferinde anlatmak yerine, bunları projede evrensel olarak erişilebilen yapılandırma dosyalarında veya AI’ın sabit yetenek (skill) tanımlarında tutuyorum. Önceden araca özgü kurallar (örneğin .cursorrules) kullanırken, artık ekosistem daha standart formatlara, örneğin depo kökündeki AGENTS.md veya .ai/ klasörü altındaki yapılandırmalara doğru evriliyor.</p><ul><li><strong>Statik Bağlam:</strong> Mimari kurallar, kullanılan kütüphaneler, proje standartları (AGENTS.md, Rules/Skills).</li><li><strong>Dinamik Bağlam:</strong> İş mantığı, anlık domain gereksinimleri, hikaye ve nihai amaç (Prompt).</li></ul><p>Bu kesin ayrım, modern AI destekli geliştirmenin kalbini oluşturuyor. Statik kuralları arka planda bir güvenlik bariyeri (guardrail) olarak kullanarak, AI’ın enerjisini ve dikkatini tamamen “ne çözüyoruz?” sorusuna odaklayabiliyoruz.</p><h3>Ölçeklenebilir Bağlam: Hiyerarşik ve Kapsamlı Yönetim</h3><p>Büyük projelerde, özellikle birden fazla modül barındıran monorepo yapılarında, tek bir devasa AGENTS.md dosyası kullanmak modelin dikkatini gereksiz yere dağıtabilir ve token maliyetlerini artırabilir. Endüstri şu an <strong>&quot;Scoped Context Management&quot; (Kapsamlı/Hiyerarşik Bağlam Yönetimi)</strong> diyebileceğimiz bir yaklaşıma evriliyor.</p><p>Devasa tek bir dosya yerine, repository’nin kökünde genel kuralları içeren bir AGENTS.md tutarken, her büyük modülün (veya alt klasörün) kendi AGENTS.md veya .ai/ yapılandırmasına sahip olması en ideal yapıdır.</p><p>AI Agent, çalıştığı dizine göre en spesifik kuralları yükler. Örneğin, Frontend klasöründe çalışırken React standartlarını, Backend modülünde çalışırken ABP Framework kurallarını devreye alır. Bu hiyerarşik yapı, modelin bağlam penceresini kirletmeden, sadece o an odaklanması gereken “mikro-evreni” ona sunar.</p><h3>Fikir Alışverişi: Latent Space’i Harekete Geçirmek ve Düşünme İlüzyonu</h3><p>Kodlamaya doğrudan geçmeden önce uyguladığım bir diğer kritik adım ise <strong>planlama ve onay aşaması</strong>.</p><p>Nihai amacı verdikten sonra, AI’dan doğrudan kod üretmesini beklemiyorum. Çoğunlukla plan modunu kullanarak veya “Sence bu yaklaşım uygun mu?”, “Bunu yapmak istiyorum, senin fikrin ne?” gibi sorularla tartışmayı başlatıyorum.</p><p><strong>Peki modeli konuşturmak neden bu kadar önemli?</strong> En temelinde, bir modelin ürettiği her kelime, sohbet geçmişine (conversation history) eklenerek bağlamın (context) ayrılmaz bir parçası haline gelir. Aslında AI’daki “düşünme” ilüzyonu, modelin kendi kendine konuşması (Chain of Thought) sürecinin ta kendisidir.</p><p>AI’a konsepti anlatıp soru sorduğunuzda sadece Latent Space’i (Gizil Alan) aktive etmekle kalmazsınız. Model size cevap verirken ürettiği mantıksal argümanları kendi bağlamına dahil eder. Kendi ürettiği bu yüksek kaliteli ve odaklı bağlam sayesinde, bir sonraki adımda yazacağı kodun mimarisi çok daha sağlam olur.</p><h3>Sonuç: Prompt Büyücüsü Değil, Takım Lideri Olun</h3><p>Açık konuşalım: Sihirli promptlar arama devri kapanmadı, o devir çoktan bitti. Bugün bir yerde “Prompt Engineering” başlığı altında sihirli taktikler veya kurslar pazarlayan birilerini görüyorsanız, oradan arkanıza bakmadan kaçın. Bir AI Agent’tan maksimum verimi almak, teknik bir dehadan ziyade iyi bir yöneticilik becerisi gerektiriyor.</p><p>Nasıl ki ekibinize yeni katılan bir geliştiriciye task verirken projenin vizyonunu, iş dinamiklerini ve kod standartlarını anlatıyor, sonra bir mimari taslak üzerinde anlaşıp uygulamaya geçmesini bekliyorsanız; AI ile çalışırken de tam olarak bunu yapmalısınız.</p><p>Bilgiyi doğru yapılandırın (Information Architecture), statik ve dinamik bağlamı ayırın ve ona kod yazılacak bir terminal gibi değil, vizyonu paylaşabileceğiniz bir çalışma arkadaşı gibi davranın. Göreceksiniz ki, en basit komutlar bile bu zengin bağlam içinde harika mühendislik çözümlerine dönüşecek.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a60e99353c56" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[13. Yüzyılda Kafka Kullanmak: Moğol “Yam” Sistemi Bize Sistem Mimarisini Nasıl Öğretiyor?]]></title>
            <link>https://enisn.medium.com/13-y%C3%BCzy%C4%B1lda-kafka-kullanmak-mo%C4%9Fol-yam-sistemi-bize-sistem-mimarisini-nas%C4%B1l-%C3%B6%C4%9Fretiyor-3721837fc5c8?source=rss-4c08bf8ed488------2</link>
            <guid isPermaLink="false">https://medium.com/p/3721837fc5c8</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Enis Necipoğlu]]></dc:creator>
            <pubDate>Mon, 11 May 2026 10:06:24 GMT</pubDate>
            <atom:updated>2026-05-11T10:06:24.842Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*beQ2nX3LsUu8mVWGU6qGPA.png" /></figure><p>Bir yazılım geliştirici olarak bugünlerde en büyük dertlerimizden biri nedir? Mikroservisler arası iletişimi sağlamak, veriyi en düşük gecikmeyle hedefe ulaştırmak ve sunuculardan biri çöktüğünde sistemin ayakta kalmasını <em>(fault tolerance)</em> garanti altına almak. Bunun için Kafka, RabbitMQ, gRPC gibi devasa teknolojiler kullanıyoruz.</p><p>Peki ya size, veri akışını yönetme ve dağıtık sistemler <em>(distributed systems)</em> kurma probleminin bundan tam 800 yıl önce, hem de Asya bozkırlarında çözüldüğünü söylesem?</p><p>Tarihin en büyük bitişik imparatorluğunu kuran Moğollar, Çin’den Doğu Avrupa’ya kadar uzanan devasa bir coğrafyayı yönetmek zorundaydı. Bu “devasa network” üzerinde iletişim kurmak, devasa bir veri iletim problemiydi. Cengiz Han ve ardılları bu problemi <strong>Yam (Örtöö)</strong> adını verdikleri kusursuz bir “<em>Message Broker</em>” sistemiyle çözdüler.</p><p>Gelin, modern yazılım mimarisi terimleriyle bozkırın bu 800 yıllık teknolojisini deşifre edelim.</p><h3>1. Node’lar ve Asenkron Veri İletimi (The Architecture)</h3><p>Yam sistemi, imparatorluğun hayati rotaları üzerine her 30–40 kilometrede bir kurulan istasyonlardan oluşuyordu. Modern mimarideki <strong>Node</strong>’larımıza denk gelen bu istasyonlarda her zaman dinlenmiş atlar, erzak ve kalacak yer bulunurdu.</p><p>Sistemin temel amacı <strong>Throughput’u (işlem hacmi)</strong> maksimize etmek, <strong>Latency’i (gecikme)</strong> ise minimize etmekti. Bir mesaj (veri paketi) yola çıktığında, onu taşıyan atlı (Ulak) bir istasyona varır varmaz yorgun atını bırakır, taze bir ata atlayıp hız kesmeden yola devam ederdi. Yani veri paketi, ağ üzerindeki düğümlerde asla bekleme yapmaz, sadece kaynak (resource) değiştirerek asenkron bir şekilde hedefine doğru akardı. Bu sayede günde 300 kilometre gibi, o dönemin şartlarında “fiber optik” sayılabilecek bir iletim hızına ulaşılıyordu.</p><h3>2. Paiza: 13. Yüzyılın JWT’si</h3><p>Beni bu sistemde en çok büyüleyen detay kimlik doğrulama mekanizmasıdır. Devasa bir ağda, her istasyondaki görevlinin gelen ulağı tanıması imkansızdır. Merkezi bir veritabanı (Central DB) olmadığı için görevli, “Bu adam gerçekten Kağan’ın elçisi mi?” diye sorgulayamaz.</p><p>İşte burada devreye <strong>Paiza</strong> giriyor. Paiza, ulakların boynunda taşıdıkları altın, gümüş, bronz veya ahşap tabletlerdi. Modern mimarideki <strong>Stateless Authentication</strong> ve <strong>JWT (JSON Web Token)</strong> mantığı tam olarak budur!</p><p>İstasyon görevlisi merkeze gidip doğrulama yapmak yerine, sadece Paiza’ya (Token) bakar. Token’ın materyali (altın veya ahşap olması), tıpkı JWT içindeki role veya claims verisi gibidir. Görevli, elinde altın Paiza olan birini gördüğünde (Admin Token), ona anında en iyi atları, en iyi erzakları tahsis eder ve geçişine (Authorization) izin verirdi. Kriptografik imza yerine, o dönem <strong>Kağan&#39;ın mührü (Tamga)</strong> kullanılıyordu.</p><h3>3. Failover ve Multi-Region Routing</h3><p>Bir dağıtık sistemin en önemli kuralı: “Her şey ters gidebilir.” Bozkırda hava şartları bozabilir, at sakatlanabilir veya ulağa haydutlar saldırabilirdi. Yani “Server Down” veya “Timeout” durumları kaçınılmazdı.</p><p>Moğol mühendisleri (stratejistleri) bunun için <strong>Redundancy (Yedeklilik)</strong> mekanizmasını kurdular. Çok kritik bir savaş emri veya istihbarat asla tek bir ulakla (Single Point of Failure) gönderilmezdi. Aynı mesaj, farklı rotalardan giden birkaç farklı ulağa verilirdi (<strong>Multi-region Active-Active replication</strong>). Eğer yolda bir ulak “düşerse”, diğer rotadaki ulak mutlaka hedefe ulaşırdı.</p><p>Ayrıca bir istasyon yıkılmışsa veya at kalmamışsa, ulak sistemin durmasına izin vermez, elindeki mevcut atı sınırlarına kadar zorlayarak bir sonraki Node’a ulaşmaya çalışırdı (<strong>Fallback mekanizması</strong>).</p><h3>Sonuç: Teknoloji Değişir, Mühendislik Prensipleri Kalır</h3><p>Bugün bulut sunucularımızda saniyede milyonlarca mesajı Kafka topic’leri üzerinden aktarırken, aslında binlerce yıl önce at sırtında rüzgara karşı dörtnala koşan o ulakların mirasını devam ettiriyoruz.</p><p>Mühendislik, eldeki araçlarla en optimum sistemi kurma sanatıdır. Dün bu araçlar atlar, istasyonlar ve altın tabletlerdi; bugün ise fiber optik kablolar, konteynerler ve dijital anahtarlar. Medyum değişse de, problemi çözme mantığımızın (gecikmeyi azalt, yetkiyi doğrula, hatayı tolere et) aynı kalması sizce de büyüleyici değil mi?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3721837fc5c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering at Source Generators]]></title>
            <link>https://medium.com/c-sharp-programming/mastering-at-source-generators-18125a5f3fca?source=rss-4c08bf8ed488------2</link>
            <guid isPermaLink="false">https://medium.com/p/18125a5f3fca</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Enis Necipoğlu]]></dc:creator>
            <pubDate>Sat, 15 Jan 2022 13:51:29 GMT</pubDate>
            <atom:updated>2022-02-08T13:27:28.287Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve been working on <a href="https://devblogs.microsoft.com/dotnet/introducing-c-source-generators/">Source Generators</a> for a while and some of my libraries have a feature that is based on source generators. But I want to make a demonstrate about dynamic usage of source generators and show you how useful it is. In this article, I’ll guide you to create csharp files from an entity using different templates such as Controller, Domain Service, Repository. All of them will be generated with source generators from a txt template. So, all the CRUD operations will be ready at the beginning of a project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6VB2ykXALH-3zgU2GWcsRg.png" /></figure><p><strong>Creating a new solution</strong></p><p>As you know, source generators work like an analyzer and provide an analyzing source code option in development-time even code can’t be compiled. So, we need a separate project. Let’s start with creating a new webapi which is named <strong>Awesome.Api</strong> and create a .netstandard2.0 class library named <strong>Awesome.Generators</strong>.</p><p>Make sure the solution structure is like below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/443/1*l6tcgdPwoJUwCbMGw9fiDg.png" /></figure><p>I personally prefer not to use <strong>Nullable Reference Types, </strong>so I just removed &lt;Nullable&gt;enable&lt;/Nullable&gt;section from <strong>.csproj</strong> files.</p><h3><strong>Development of the Syntax Receiver</strong></h3><p>Following references must be added to <strong>Awesome.Generators</strong> project:</p><pre>&lt;ItemGroup&gt;<br>    &lt;PackageReference Include=&quot;Microsoft.CodeAnalysis.CSharp.Workspaces&quot; Version=&quot;4.0.1&quot; PrivateAssets=&quot;all&quot; /&gt;<br>    &lt;PackageReference Include=&quot;Microsoft.CodeAnalysis.Analyzers&quot; Version=&quot;3.3.3&quot; PrivateAssets=&quot;all&quot; /&gt;<br>  &lt;/ItemGroup&gt;</pre><p>Now, we’re able to analyze code. You need to decorate your class with [Generator] attribute and implement ISourceGenerator interface to create a source generator.</p><pre>using Microsoft.CodeAnalysis;</pre><pre>namespace Awesome.Generators;</pre><pre>[Generator]<br>public class ServiceGenerator : ISourceGenerator<br>{<br>    public void Execute(GeneratorExecutionContext context)<br>    {<br>        throw new NotImplementedException();<br>    }</pre><pre>    public void Initialize(GeneratorInitializationContext context)<br>    {<br>        throw new NotImplementedException();<br>    }<br>}</pre><p>You’ll see there are 2 methods to implement.</p><p><strong>Initialize </strong>method will work at the beginning while initializing analyzer. You can register for some events or one-time configurations can be performed here.</p><p><strong>Execute </strong>method will be triggered when syntax changed. So it means while code is being written :)</p><p>We can not generate an entire class when all syntax changed events. We need to declare something like attribute usage. Defining an attribute is much more meaningful because that can prevent running code-generation while the developer adds each symbol into the code.</p><p>Let’s create an attribute with name <strong>GenerateServiceAttribute</strong> and decorate that class is like below:</p><pre>namespace Awesome.Generators;</pre><pre>[AttributeUsage(AttributeTargets.Class)]<br>public class GenerateServiceAttribute : Attribute<br>{<br>    public GenerateServiceAttribute(string template = null)<br>    {<br>    }<br>}</pre><p>Just added a template parameter to the constructor and didn’t set to any field or property because I don’t need it at runtime. I’ll need only syntax that is written on the source code. It’s for only decoration. I’ll use the constructor parameter while generating code.</p><p>Now we can create a SyntaxReceiver to track adding a new attribute and to check if that attribute is GenerateServiceAttribute. We need to create a syntax receiver for this.</p><p>I’ll need a small extension method, add the following class to your project before creating SyntaxReceiver:</p><pre>namespace Awesome.Generators;</pre><pre>public static class StringExtensions<br>{<br>    public static string EnsureEndsWith(<br>        this string source,<br>        string suffix)<br>    {<br>        if (source.EndsWith(suffix))<br>        {<br>            return source;<br>        }</pre><pre>        return source + suffix;<br>    }<br>}</pre><p>You’re ready to create AttributeSyntaxReceiver:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/608c7bd29e515c76d2ced8c9052411b4/href">https://medium.com/media/608c7bd29e515c76d2ced8c9052411b4/href</a></iframe><p>Now we can go back to <strong>ServiceGenerator </strong>class and register our the newly created AttributeSyntaxReceiver. Add registration code into Initialize method like below.</p><pre>public void Initialize(GeneratorInitializationContext context)<br>{<br>    context.RegisterForSyntaxNotifications(() =&gt; <br>        new AttributeSyntaxReceiver&lt;GenerateServiceAttribute&gt;());<br>}</pre><h3><strong>Working with Templates</strong></h3><p>Before starting working on <strong>Execute </strong>method, let’s create a default template to use for code-generation. A simple txt file is enough. I want to use a Controller template by default to generate CRUD operations for an entity. Using a templating engine like Scriban might be very useful but you can’t use the project references at runtime because analyzers work in Roslyn process and you can only access modules that are loaded by Roslyn. Of course, there is always a way to load your dependencies on Roslyn but it’s not the topic of today :)</p><ul><li>Create a Templates folder under <strong>Awesome.Generators </strong>project.</li><li>And mark all txt files are embedded resource in .csproj file via adding following group inside &lt;Project&gt; tags.</li></ul><pre>&lt;ItemGroup&gt;<br>    &lt;None Remove=&quot;Templates\**\*.txt&quot; /&gt;<br>    &lt;EmbeddedResource Include=&quot;Templates\**\*.txt&quot; /&gt;<br>&lt;/ItemGroup&gt;</pre><ul><li>Create <strong>Default.txt</strong> under Templates folder.</li></ul><pre>using Microsoft.AspNetCore.Mvc;<br>using {{Namespace}};</pre><pre>namespace {{PrefferredNamespace}}.Controllers;</pre><pre>[ApiController]<br>[Route(&quot;api/[controller]&quot;)]<br>public partial class {{ClassName}}Controller : ControllerBase<br>{<br>    private static readonly List&lt;{{ClassName}}&gt; _collection = new();</pre><pre>    [HttpGet]<br>    public virtual List&lt;{{ClassName}}&gt; Get()<br>    {<br>        return _collection;<br>    }</pre><pre>    [HttpGet(&quot;{id}&quot;)]<br>    public virtual {{ClassName}} GetSingle(Guid id)<br>    {<br>        return _collection.SingleOrDefault(x =&gt; x.Id == id);<br>    }</pre><pre>    [HttpPost]<br>    public virtual void Create({{ClassName}} item)<br>    {<br>        item.Id = Guid.NewGuid();<br>        _collection.Add(item);<br>    }</pre><pre>    [HttpPut(&quot;{id}&quot;)]<br>    public virtual void Update(Guid id, {{ClassName}} item)<br>    {<br>        var existing = _collection.Single(x =&gt; x.Id == id);</pre><pre>item.Id = id;<br>        _collection.Remove(existing);<br>        _collection.Add(item);<br>    }</pre><pre>    [HttpDelete(&quot;{id}&quot;)]<br>    public virtual void Delete(Guid id)<br>    {<br>        var existing = _collection.Single(x =&gt; x.Id == id);</pre><pre>        _collection.Remove(existing);<br>    }<br>}</pre><p>We can’t use the scriban at the moment but I like that convention.</p><p>Let’s create a class to keep parameters strong-typed. Create a class with name <strong>DefaultTemplateParameters</strong>.</p><pre>namespace Awesome.Generators.Templates;</pre><pre>public class DefaultTemplateParameters<br>{<br>    public DefaultTemplateParameters(<br>        string typeName, <br>        string typeNamespace,<br>        string rootNamespace)<br>    {<br>        ClassName = typeName <br>          ?? throw new ArgumentNullException(nameof(typeName));</pre><pre>        Namespace = typeNamespace<br>          ?? throw new ArgumentNullException(nameof(typeNamespace));</pre><pre>        PrefferredNamespace = rootNamespace <br>          ?? throw new ArgumentNullException(nameof(rootNamespace));<br>    }</pre><pre>    public string ClassName { get; set; }</pre><pre>    public string Namespace { get; set; }</pre><pre>    public string PrefferredNamespace { get; set; }<br>}</pre><h3><strong>Development of Source Generators</strong></h3><p>Now we can go back to our <strong>Execute</strong> method in ServiceGenerator.</p><p>The entire content of Generator:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b0ac6ed781a1916f1ae4107173f4b57/href">https://medium.com/media/6b0ac6ed781a1916f1ae4107173f4b57/href</a></iframe><p>I’ve written some comments inside the code. It should explain itself. If not you can contact me and we can discuss later. I’ll be delighted if you do :)</p><h3><strong>Executing the Source Generator</strong></h3><p>We’ve done with <strong>Awesome.Generators</strong> project. Let’s make it running.</p><p>Add <strong>Awesome.Generators</strong> reference to the <strong>Awesome.Api</strong> project. But be careful. It’s not a standard project reference. We must mark that reference as Analyzer via using OutputItemType parameter.</p><pre>&lt;ItemGroup&gt;<br>  &lt;ProjectReference<br>    Include=&quot;..\Awesome.Generators\Awesome.Generators.csproj&quot;<br>    OutputItemType=&quot;Analyzer&quot; /&gt;<br>&lt;/ItemGroup&gt;</pre><p>Now you can see our project as an analyzer in Visual Studio.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/1*kJNHeFQV5VlNGU-sY_lDqA.png" /></figure><p>There is no content yet because we haven’t used GenerateServiceAttribute and generated any of code. Let’s start with creating a new entity with our attribute which is named <strong>Todo.</strong></p><pre>using Awesome.Generators;</pre><pre>namespace Awesome.Api;</pre><pre>[GenerateService]<br>public class Todo<br>{<br>    public Guid Id { get; set; }<br>    public string Content { get; set; }<br>    public bool IsCompleted { get; set; }<br>}</pre><p>The project should be built once after referencing a new analyzer. After the build was completed, you’ll see the generated code under analyzer in solution explorer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*IEdbm0Go1xvXtxysvSxyqQ.png" /></figure><p><em>If the generated codes weren’t showed up, your IDE requires to be restarted. But it’s not necessary, you can still run the application.</em></p><p>Now hit the ▶️Run button. You’ll see the CRUD endpoints which come from the controller generated by source generators.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X3VIpqX2nwrnZi-C1h3Dxw.png" /></figure><p>Now you can create new entities as much as you desire with CRUD endpoints.</p><h3>Accessing to Database with a Custom Template</h3><p>You can inject a repository to controllers via editing code template and make your controller use database to perform CRUD operations.</p><blockquote>I assume the ID is Guid by default.</blockquote><p>I’ll use an interface to define Ids on entities which is named as <strong>IIdentifiable</strong>, because I’ll make operations over Id.</p><pre>public interface IIdentifiable<br>{<br>    Guid Id { get; set; }<br>}</pre><p>Don’t forget to implement it to our first entity named <strong>Todo</strong>.</p><pre>[GenerateService]<br>public class Todo : IIdentifiable<br>{<br>    public Guid Id { get; set; }</pre><pre>    public string Content { get; set; }</pre><pre>    public bool IsCompleted { get; set; }<br>}</pre><p>Before creating a custom template we need an abstract repository. Let’s call that as <strong>IRepository.</strong> Create a simple repository interface. We can add it to the main app (<strong>Awesome.Api</strong>).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3e5cd43ebf2e025bf23f5b963922437/href">https://medium.com/media/f3e5cd43ebf2e025bf23f5b963922437/href</a></iframe><p>I’ll use MongoDB implementation to get rid of DbContext implementation &amp; migrations. Add <strong>Mongo.Driver</strong> and <strong>Humanizer.Core</strong> reference to your project. I used Humanizer for just pluralizing collection names. You can pass it if you don’t need it.</p><pre>&lt;PackageReference Include=&quot;MongoDB.Driver&quot; Version=&quot;2.14.1&quot; /&gt;<br>&lt;PackageReference Include=&quot;Humanizer.Core&quot; Version=&quot;2.13.14&quot; /&gt;</pre><p>Add a MongoDbOptions class.</p><pre>using System.Reflection;</pre><pre>namespace Awesome.Api.Data;</pre><pre>public class MongoDbOptions<br>{<br>    public string ConnectionString { get; set; } = &quot;mongodb://localhost:27017/&quot; + Assembly.GetEntryAssembly().GetName().Name.Replace(&quot;.&quot;, &quot;_&quot;);<br>}</pre><p>And the implementation of <strong>MongoDbRepository.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eca6aa1e1a77816e9a250c99ebb1417f/href">https://medium.com/media/eca6aa1e1a77816e9a250c99ebb1417f/href</a></iframe><p>Don’t forget to register it into ServiceCollection in <strong>Program.cs</strong></p><pre>builder.Services.Add(<br>    new ServiceDescriptor(<br>        typeof(IRepository&lt;&gt;), <br>        typeof(MongoDbRepository&lt;&gt;), <br>        ServiceLifetime.Transient));</pre><p>Now, the repository pattern implementation is ready to use. We need to create another controller template that uses IRepository. Create a new file with the name <strong>RepositoryController.txt</strong> under Templates folder in <strong>Awesome.Api</strong> project and mark it as C# analyzer additional file. After making this, this file won’t be included in your assembly or won’t be copied to the output directory. This file only is accessed by analyzers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/1*nv2GMB0Ei5OWmTxzrjl5uw.png" /></figure><p>And the content of file is below.</p><pre>using Microsoft.AspNetCore.Mvc;<br>using System.Collections.Generic;<br>using Awesome.Api.Data;<br>using {{Namespace}};</pre><pre>namespace {{PrefferredNamespace}}.Controllers;</pre><pre>[ApiController]<br>[Route(&quot;api/[controller]&quot;)]<br>public partial class {{ClassName}}Controller : ControllerBase<br>{<br>    private readonly IRepository&lt;{{ClassName}}&gt; _repository;</pre><pre>    public {{ClassName}}Controller(<br>        IRepository&lt;{{ClassName}}&gt; repository)<br>    {<br>        _repository = repository;<br>    }<br>        <br>    [HttpGet]<br>    public virtual Task&lt;List&lt;{{ClassName}}&gt;&gt; GetListAsync()<br>    {<br>        return _repository.GetListAsync();<br>    }<br>        <br>    [HttpGet(&quot;{id}&quot;)]<br>    public virtual Task&lt;{{ClassName}}&gt; GetSingleAsync(Guid id)<br>    {<br>        return _repository.GetSingleAsync(id);<br>    }</pre><pre>    [HttpPost]<br>    public virtual async Task CreateAsync({{ClassName}} item)<br>    {<br>        await _repository.InsertAsync(item);<br>    }</pre><pre>    [HttpPut(&quot;{id}&quot;)]<br>    public virtual async Task UpdateAsync(Guid id, {{ClassName}} item)<br>    {<br>        await _repository.UpdateAsync(id, item);<br>    }</pre><pre>    [HttpDelete(&quot;{id}&quot;)]<br>    public virtual async Task DeleteAsync(Guid id)<br>    {<br>        await _repository.DeleteAsync(id);<br>    }<br>}</pre><p>Only placing template parameter to attribute is left. Go to our first entity named <strong>Todo</strong> and add the RepositoryController.txt parameter to GenerateServiceAttribute.</p><pre>[GenerateService(&quot;RepositoryController.txt&quot;)]<br>public class Todo : IIdentifiable<br>{<br>    public Guid Id { get; set; }<br>    public string Content { get; set; }<br>    public bool IsCompleted { get; set; }<br>}</pre><p>Now, re-build your project and see the generated file under the analyzers section in solution explorer is changed. If you have a running MongoDB instance, you’ll be able to perform all CRUD operations on MongoDB.</p><blockquote>If you don’t have MongoDB instance but have already installed docker, you can execute <a href="https://github.com/enisn/docker-development-environments#mongodb">this command</a> to run a mongodb instance without pain.</blockquote><p>Just create, update and delete a couple of todo items and see it’s working.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/499/1*pbyYAItlkS-TOwx9xrV2Sw.png" /></figure><h3><strong>Extending the Generated Class</strong></h3><p>You can use [GenerateService] attribute for your all entities and all entities will have the same pre-generated controllers, services, repositories, etc.</p><p>But sometimes, you need to customize generated classes. You have 2 ways to do that: Using a Partial Class and Overriding via Inheriting.</p><h4>Using a Partial Class</h4><p>Generated codes are included in your project, assembly. So, they don’t come from yet another assembly. That means you can create partial classes to make some additions to them.</p><p>Let’s talk about adding a new endpoint that marks all as completed.</p><p>Create a physical C# class named as <strong>TodoController.cs </strong>in the same namespace as generated one. In that case, we’re creating under the Controller folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*CJw_L_AEw8XeFUtv0lzhrA.png" /></figure><p>The compiler says you can’t have TodoController class in this namespace, because you already have it. If you see that message, you’ve created it in the correct namespace. Just make that class <strong>partial</strong>, the error will be disappeared.</p><p>Now we’re ready to add a new endpoint for TodoController.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3982a5562e404687928e81db305b8037/href">https://medium.com/media/3982a5562e404687928e81db305b8037/href</a></iframe><p>Run the application and see the newly created endpoint by you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OndnCgU_aU5fVf5W9yhpQw.png" /></figure><h4>Overriding via Inheriting</h4><p>When you create a new Controller and it inherits from TodoController, you’ll have 2 real controllers. You should make the base TodoController abstract via writing a tiny partial class to prevent pretending the base class as a controller.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a449e87708080879735f36e6f2da3a74/href">https://medium.com/media/a449e87708080879735f36e6f2da3a74/href</a></iframe><h3>Conclusion</h3><p>You can generate infinite Controllers, Services, Repositories, etc. that includes CRUD operations for your all entities. As a next step, you can add generate business services, and use that generated business services in generated controllers. Even you can add mapping and caching to your generated files to make them more suitable for enterprise solutions. The sky is the limit!</p><p>I would be glad if this example sheds light on the use of Source Generators.</p><h4>Source Code</h4><p>Also source code of this example is available on GitHub:</p><ul><li><a href="https://github.com/enisn/Mastering-at-Source-Generators">enisn/Mastering-at-Source-Generators: Mastering at Source Generators example (github.com)</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18125a5f3fca" width="1" height="1" alt=""><hr><p><a href="https://medium.com/c-sharp-programming/mastering-at-source-generators-18125a5f3fca">Mastering at Source Generators</a> was originally published in <a href="https://medium.com/c-sharp-programming">Any Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Filtering data without coding in AspNetCore]]></title>
            <link>https://medium.com/c-sharp-programming/filtering-data-without-coding-in-aspnetcore-b32f2dc905c2?source=rss-4c08bf8ed488------2</link>
            <guid isPermaLink="false">https://medium.com/p/b32f2dc905c2</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[filtering]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <dc:creator><![CDATA[Enis Necipoğlu]]></dc:creator>
            <pubDate>Sat, 10 Apr 2021 08:44:02 GMT</pubDate>
            <atom:updated>2021-09-26T10:28:12.397Z</atom:updated>
            <content:encoded><![CDATA[<p>Firstly, I want to say that, this article will be all about a feature which I developed and packed in <a href="https://github.com/enisn/AutoFilterer">AutoFilterer</a>. This logic uses <a href="https://devblogs.microsoft.com/dotnet/introducing-c-source-generators/">Source Generators</a> to generate filter objects and that generated types keep you safe with strong type coding and also keeps your API in Open API Specifications. Let’s make a sample.</p><p>Create an Asp.Net Core Web API. Make sure you’ve checked <strong>Enable OpenAPI Support</strong> checkbox. I used MyAwesomeApp name while generating.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*pyE-v85xYFQyeZbvkCcJ1g.png" /></figure><p>We’ll use default WeatherForecastController and WeatherForecast object instead of connecting a database. Also you can try with a database.</p><p>Then, Add <a href="https://www.nuget.org/packages/AutoFilterer.Generators">AutoFilterer.Generators</a> package from NuGet into your project. After successfully installation, find <strong>WeatherForecast.cs</strong> and add [GenerateAutoFilter] attribute over it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2fcb452eacd051570da6f3c2c5e0abef/href">https://medium.com/media/2fcb452eacd051570da6f3c2c5e0abef/href</a></iframe><p>When you add GenerateAutoFilter attribute, your project will have one more type which is {ClassName}Filter . In this situation, your project has WeatherForecastFilter type. You can start to use it directly without writing any custom code.</p><p>Find <strong>WeatherForecastController.cs</strong> and apply a filter with using auto-generated <strong>WeatherForecastFilter</strong> type.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2cfa967ff0c60cbe069aa9ad923dc4ab/href">https://medium.com/media/2cfa967ff0c60cbe069aa9ad923dc4ab/href</a></iframe><p><strong>Notice That: </strong>If you’re using Visual Studio, intellisense might not repond <a href="https://devblogs.microsoft.com/dotnet/introducing-c-source-generators/">Source Generators</a> immediately, but you’ll see all generated types after re-open Visual Studio.</p><p>Start the application even IDE says there is no such a type as WeatherForecastFilter, and you’ll see following endpoint in swagger UI:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1mPxsDWMD9cVgu3QLjvF7A.png" /></figure><p>That’s it, your filtering is ready to use. BTW, pay attention, WeatherForecast data is created randomly, so that means pagination won’t work properly in this sample because, all data is re-created at each request.</p><p>If you’re interested in filtering data without coding, you should read the <a href="https://github.com/enisn/AutoFilterer/blob/master/docs/generators/AutoFilterer-Generators.md">rest of documentation</a> and <a href="https://github.com/enisn/AutoFilterer">give a star on github</a> :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b32f2dc905c2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/c-sharp-programming/filtering-data-without-coding-in-aspnetcore-b32f2dc905c2">Filtering data without coding in AspNetCore</a> was originally published in <a href="https://medium.com/c-sharp-programming">Any Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Blazor Localization with I18NPortable]]></title>
            <link>https://medium.com/c-sharp-programming/blazor-localization-with-i18nportable-b2159123b36a?source=rss-4c08bf8ed488------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2159123b36a</guid>
            <category><![CDATA[blazor]]></category>
            <category><![CDATA[blazor-localization]]></category>
            <category><![CDATA[localization]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[blazor-webassembly]]></category>
            <dc:creator><![CDATA[Enis Necipoğlu]]></dc:creator>
            <pubDate>Thu, 11 Feb 2021 06:58:23 GMT</pubDate>
            <atom:updated>2021-07-05T08:45:23.618Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I’ll show how to use lightest localization library, <a href="https://github.com/xleon/I18N-Portable">I18NPortable </a>with Blazor. This library provides static methods instead of IStringLocalizer implementation. That is a different approach. It’s not topic of this document if it’s good solution or not.</p><h3>Set-up</h3><ul><li>Install I18NPortable into your Blazor project</li></ul><pre>Install-Package I18NPortable</pre><ul><li>Create localization files</li></ul><p>By default, this library provides a couple of localization file format such as json , csv , plain. I’ll use plain text for this example. So let’s create some localization files in your blazor app:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/235/1*3Sk0xG58v5sE7K1ymL1fvQ.png" /></figure><ul><li>Locales/en-US.txt</li></ul><pre>Welcome = Hello, World from US!</pre><ul><li>Locales/en-GB.txt</li></ul><pre>Welcome = Hello, World from GB!</pre><ul><li>Set Localization files as Embed Resource</li></ul><p>Add following code into your <strong>.csproj</strong> file:</p><pre>&lt;ItemGroup&gt;<br>    &lt;EmbeddedResource Include=&quot;Locales\*.txt&quot; /&gt;<br>&lt;/ItemGroup&gt;</pre><ul><li>Initialize <strong>I18NPortable</strong></li></ul><p>Go your <strong>Program.cs</strong> file. Initialize I18NText and add it into service collection as singleton.</p><p><em>Yes singleton for client-side blazor. If you’re using server-side, use lifetime as Scoped.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c817530f07f29df5e396dcd23afab24d/href">https://medium.com/media/c817530f07f29df5e396dcd23afab24d/href</a></iframe><ul><li>Use it!</li></ul><p>Now you’re ready to use localization via injectingII18N interface into your pages. Go your <strong>Index.razor</strong> and replace welcome message from resources:</p><pre><a href="http://twitter.com/page">@page</a> &quot;/&quot;</pre><pre><a href="http://twitter.com/using">@using</a> I18NPortable</pre><pre><a href="http://twitter.com/inject">@inject</a> II18N L</pre><pre>&lt;h1&gt;<a href="http://twitter.com/L">@L</a>[&quot;Welcome&quot;]&lt;/h1&gt;</pre><pre>Welcome to your new app.</pre><pre>&lt;SurveyPrompt Title=&quot;How is Blazor working for you?&quot; /&gt;</pre><p>Until here, everything works great. But we need to change language and blazor application should reflect language changes. So, following steps are all about changing language and notifying components about it.</p><h3>Changing Language</h3><p>When you directly set current language, nothing gonna happen. Because all components which uses localization, should be rendered again. So let’s create a simple event bus in you blazor application.</p><ul><li>Create a class which is named <strong>Events.cs</strong></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1399be30b11e88e69852b4e862d5d62a/href">https://medium.com/media/1399be30b11e88e69852b4e862d5d62a/href</a></iframe><ul><li>Register <strong>Events </strong>class into ServiceCollection</li></ul><p>Go your <strong>Program.cs</strong> and register Events as Singleton for Client-Side, Scoped for Server-Side Blazor app.</p><pre>builder.Services.AddSingleton(new Events());</pre><p><em>All componenets &amp; background jobs should use same instance to communicate with each other. That’s why we use Singleton here.</em></p><ul><li>Create a base component</li></ul><p>We’ll crate a base component which listens <strong>LanguageChanged </strong>event and re-renders itself when required.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/71bca11ec3a28dcd8ff9bef8770ed080/href">https://medium.com/media/71bca11ec3a28dcd8ff9bef8770ed080/href</a></iframe><ul><li>Inherit your <strong>Index.razor</strong> from <strong>MyComponentBase</strong></li></ul><p>Using just @inherits MyComponentBase` enough:</p><pre><a href="http://twitter.com/page">@page</a> &quot;/&quot;</pre><pre><a href="http://twitter.com/using">@using</a> I18NPortable<br><a href="http://twitter.com/using">@using</a> BetterBlazorApp.Components</pre><pre><a href="http://twitter.com/inherits">@inherits</a> MyComponentBase</pre><pre><a href="http://twitter.com/inject">@inject</a> II18N L</pre><pre>&lt;h1&gt;<a href="http://twitter.com/L">@L</a>[&quot;Welcome&quot;]&lt;/h1&gt;</pre><pre>Welcome to your new app.</pre><pre>&lt;SurveyPrompt Title=&quot;How is Blazor working for you?&quot; /&gt;</pre><p>Now your application is ready to react language changes at runtime without reloading.</p><ul><li>Add languages menu</li></ul><p>Go your <strong>MainLayout.razor</strong> and add locale flags to change languages at the top of application:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d310edfbc3ef37a7cd5534be3093278/href">https://medium.com/media/3d310edfbc3ef37a7cd5534be3093278/href</a></iframe><p>And hit the RUN button</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*j-GjqbeRaqBBLyhjTr5XRw.gif" /></figure><p>Your application is completely responsive against language changes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2159123b36a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/c-sharp-programming/blazor-localization-with-i18nportable-b2159123b36a">Blazor Localization with I18NPortable</a> was originally published in <a href="https://medium.com/c-sharp-programming">Any Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to develop a NuGet Package?]]></title>
            <link>https://enisn.medium.com/how-to-develop-a-nuget-package-d37400d9e1d3?source=rss-4c08bf8ed488------2</link>
            <guid isPermaLink="false">https://medium.com/p/d37400d9e1d3</guid>
            <category><![CDATA[nuget]]></category>
            <category><![CDATA[dot-net-core]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Enis Necipoğlu]]></dc:creator>
            <pubDate>Thu, 15 Oct 2020 18:53:26 GMT</pubDate>
            <atom:updated>2020-10-15T18:53:26.810Z</atom:updated>
            <content:encoded><![CDATA[<p>Each .Net Developer knows <a href="https://nuget.org/">nuget.org</a> and NuGet Packages. So, have you ever been though about how to create a nuget package? Nuget packages are easy to plug-in libraries. So a nuget package can be added to any project via using NuGet Package Manager.</p><h3>Anatomy of a Nuget Package</h3><p>Nuget packages aren’t just <strong>dll </strong>files. A nuget package is portable and includes any content which you want to place into a .Net Project. You can place a txt file or a png file in it. That’s why we call them as ‘Package’. You can pack some of development files and move them project to project with .nupkg format.</p><p>I’ve just extracted my InputKit nuget package, you can see tree-view of an nupkg file in the following image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*m9HzJiC-VYKCU-esJPI6-A.png" /><figcaption>Xamarin.Forms.InputKit.3.4.3.nupkg</figcaption></figure><p>So just review folders and files in it.</p><p><strong>icon.png:</strong> This is icon file of your NuGet package. It’s embeded in .nupkg now, but it could be defined only as url in earlier version of NuGet.</p><p><strong>.nuspec</strong>: Nuspec is a metadata file about your nuget package. In earlier version, it used to use to pack your nuget package. But in new dotnet CLI this file is generated from your .csproj file by roslyn compiler. It includes your package’s target frameworks, names, license, icon, tags, dependencies to other packages and static files described in it to place to added project.</p><p><strong>[Content_Types].xml: </strong>This is a metadata file which provides each file extensions included in package.</p><p><strong>lib: </strong>Main folder of your package. This folder includes your build output. In another say, it includes your bin folder after build. So you can see different target framework’s folders as same as your project output. For example, if your .csproj file is multi-targeted, you can see a folder for each of your target framework like as mine.</p><p><strong>package: </strong>This folder includes more metadata files about your package. This data is same data as what you see in nuget packages list: ‘creator’, ‘description’, ‘identifier’, ‘version’ and‘keywords’.</p><p><strong>_rels/.rels: </strong>This is an xml formatted file extension which created and used by microsoft. You can see more information about .rels format from <a href="https://fileinfo.com/extension/rels">here</a>. It’s used for Microsoft Office mostly.</p><h3>Create your first Library</h3><p>Each .Net Developer knows about class libraries. They are hard to move or use in different project. Because their outputs are <strong>dll</strong> files. I won’t talk about how to build a library in this article. I’ll just show how to convert them into a portable nuget packages. So let’s start with first step.</p><p><strong>1- Choosing Target Framework</strong></p><p>Choosing target framework is so important! Just plan your project and define your dependencies. If your dependencies require .Net Core like Entity Framework or something which targets .Net Core, just pick your target framework as <em>‘.Net Core’</em>. But if not, try always to build your library on <em>‘.Net Standard’</em>. By the way, you can build a multi-targeting project. You can read more about <a href="https://docs.microsoft.com/en-us/nuget/create-packages/multiple-target-frameworks-project-file">multi-targeting projects from here.</a></p><p><strong>2-Fill the MetaData</strong></p><p>MetaData is most important thing in the age which we live in. MetaData makes easier to find your package and describes best what it does. So please fill your metadata correctly. After you created you Class Library in Visual Studio, just <strong>Right Click</strong> and go <strong>Properties</strong>. You can see all fields which you can fill under <strong>Package</strong> tab.</p><p>If your environment isn’t Visual Studio, you can modify directly your .csproj file like below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2dd3f183c3756d24c78f0299ff4f4d9c/href">https://medium.com/media/2dd3f183c3756d24c78f0299ff4f4d9c/href</a></iframe><p><strong>3- PACK IT!</strong></p><p>Here is the where magic happen! Prepare your code, <strong>Right Click</strong> your project and click the <strong>Pack</strong> button. Your nupkg file will be waiting for you in your project’s <strong>bin</strong> folder.</p><p>If your development environment isn’t Visual Studio, you can do it with command prompt like following:</p><pre>dotnet pack My.Package.csproj</pre><p><strong>4- Share with whole World!</strong></p><p>Go <a href="https://nuget.org/">nuget.org</a> and log in to your account. Then navigate to <strong>Publish</strong> tab and drop your .nupkg file into that page. Fill information fields about your package and submit it. That’s it! This is the easiest way to publish your package on nuget.org.</p><p><strong>With command prompt</strong></p><p>But you can do it with command prompt too. Let’s see how it can be in this way.</p><p>Firsly you need an Api-Key to communicate with nuget API. Go to your profile on nuget.org and find <strong>API Keys </strong>section like below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*WuYy2fQJ7ZnBPjJqtbHM5w.png" /></figure><p>Create an API-Key and keep that. You can not be able to see it again. So you need to keep it.</p><p>Now, start with packing then you can push via CLI.</p><p>dotnet pack --configuration Release -o .packages/</p><p>That means build project in Release mode, and place output files into ‘.packages’ folder. So we can find easily our output from .pacakges folder. So your nupkg file is ready to push. Use following command to push your package to nuget.org or your custom defined source:</p><p>dotnet nuget push .\.packages\My.Pacakge.1.0.1.nupkg --source <a href="https://api.nuget.org/v3/index.json">https://api.nuget.org/v3/index.json</a> --api-key YOUR_API_KEY --skip-duplicate</p><p>I used skip-duplicate argument, because if you’re configuring a CI, same version of package can be pushed multiple times and if you’re pushing already existing version, you’ll get an error and CI-CD process will be failed. So using skip-duplicate argument, ignores already existing version pushes and completes operation successful.</p><p>Thank you for reading. See you at next article 👋</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d37400d9e1d3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[C# — Sorgular Üzerine Sohbetler]]></title>
            <link>https://enisn.medium.com/c-sorgular-%C3%BCzerine-sohbetler-dbef9b329b4c?source=rss-4c08bf8ed488------2</link>
            <guid isPermaLink="false">https://medium.com/p/dbef9b329b4c</guid>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[linq]]></category>
            <category><![CDATA[expression]]></category>
            <dc:creator><![CDATA[Enis Necipoğlu]]></dc:creator>
            <pubDate>Sat, 16 May 2020 22:48:18 GMT</pubDate>
            <atom:updated>2020-05-16T23:07:31.329Z</atom:updated>
            <content:encoded><![CDATA[<h3>C# — Sorgular Üzerine Sohbetler</h3><p>Bu yazıyı İngilizce ve Türkçe yazmak arasında çok gidip geldim. En sonunda apaçık anlaşıldığı üzere Türkçe yazmaya karar verdim. 🤟</p><p>Bu yazıda .NET ortamında LINQ Expression’ların çalışma mantığı ve performansından bahsedeğim. Nasıl çalıştıklarına, hangi aşamalardan gçetiklerine veya en çok nerede zaman kaybı yaşanıyor gibi sorulara cevap aramaya çalışacağız. Tabii ki nanosaniyeler arasında dolaşacağız. Over-Engineering yapmaya hazırsanız başlayalım. Zira bahsi geçen süreler, milyonlarca data ile çalışıyor olsanız dahi asla insan gözüyle fark edilemeyecek süreler.</p><h3>Func ve Expression</h3><p>En çok karıştırılan bu iki kavramdan bahsedeyim. Func dediğimiz tip bir expression veya lambda değil ve hatta LINQ expression hiç değildir. <strong>Func </strong>dediğimiz şey hepimizin çok yakından bildiği ‘değer döndüren bir <strong>metot</strong>’tur. Bunun bir diğer arkadaşı ise <strong>Action</strong> idir. Bu da değer döndürmeyen metottur. <em>(Çoğumuzun void olarak bildiği şey.)</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e8a2a54cf148b41600ed0621e2ed2db8/href">https://medium.com/media/e8a2a54cf148b41600ed0621e2ed2db8/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/98ad356c25bf87ae55d7f8cde2ecb3c1/href">https://medium.com/media/98ad356c25bf87ae55d7f8cde2ecb3c1/href</a></iframe><p>Kısacası Func sadece bir değer döndüren <strong>metod</strong>u bir değişkende tutmamızı sağlayan bir tiptir. Bir metot gövdesi (method body) vardır ve içerisinde bir metotta yapabildğimiz her şeyi yapabiliriz. Fakat <strong>Expression</strong> bir ifadedir, bir işaretleme, gösterme şeklidir. İçerisinde başka bir metot çağıramaz veya asenkron bir işlemi yürütemezsiniz. Çoğumuzun Entity Framework yazarken en az bir kere başına benzer bir problem gelmiştir: <em>“Expression içerisinde Convert kullanmaya çalıştığınızda hata aldığınızı görürsünüz.” </em>Bu sorun çoğu .NET Developer’ın başına en az bir kere gelmiştir diye düşünüyorum. Expression bir ifade, bir işaretleme olduğundan, bu expression’ı herhangi bir assembly’deki herhangi bir method çalıştırmak isteyebilir ve bu hemen olmak zorunda değildir. Dolayısı ile sizin o anki state’iniz kaybolmuş olur ve çağırmak istediğiniz metot erişilebilir olmayabilir, metot için kullandığınız başka bir parametre dispose olmuş olabilir vs. vs. pek çok durum gerçekleşebilir. Dolayısı ile <strong>Expression’lar Stateless olmak zorundadır. </strong>Bundan sebepten dolayı Func’tan farklıdırlar. State barındıramazlar. FakatContains, ToLower gibi string methodları kullandığımızda neden bir hata almadığımızı sorabilirsiniz. Cevabı da aslında oldukça basit: “Aslında kullanamıyoruz.” Kullandığımız çoğu string metot özel bir durum olarak bir anlam ifade edecek şekilde yorumlanır. Aslında ToLower().Contains() kullandığınızda .NET Runtime’ındaki metotlar çağrılmaz. Yorumlayıcı,<em>(Entity Framework, Mongo Driver vs.)</em> bunu bir işaret olarak kullanır ve Case-Insensitive bir sql sorgusu üretir.</p><h3>Lambda Expression</h3><p>Lambda her .NET Developer’ın karşılaştığı bir C# özelliğidir ve C# 3.0&#39;dan beri hayatımızda aktif olarak rol alıyor. Lamda bir yazılış şeklidir aslında. Biraz önceki verdiğim kod bloğu örneğini lambda kullanarak yazdım. Şu şekilde =&gt; bir gösterim şeklidir. LINQ’in veya Expression’ın bir parçası değil tamamen C# dilinin bir özelliğidir. Expression yazmak Lambda’dan önce şuna benzer bir şekildeydi:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b3378dca2a79e2ffc152e9d3d7e6553/href">https://medium.com/media/1b3378dca2a79e2ffc152e9d3d7e6553/href</a></iframe><p>Daha sonralarında Lambda ile tek satırda yazabilir hale geldik:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5df3b41ba03263c2d727726616620fa9/href">https://medium.com/media/5df3b41ba03263c2d727726616620fa9/href</a></iframe><p>Görüntü olarak çok farklı iki yazım şekli, yazım şekli diyorum çünkü arkada oluşturtukları şey bire bir aynı, ortak bir şey üretiyor. “<strong>Expression”</strong>.</p><h3><strong>Expression</strong></h3><p>Asıl heyecanlandığım kısım burası, buraya kadar olan kısmı sırf bu kısma bağlayabilmek için yazdım. <strong>Expression</strong> .NET ortamında <em>System.Linq.Expressions </em>assembly’sinden gelen bir class aslında. Microsoft dokümanı da <a href="https://docs.microsoft.com/en-US/dotnet/api/system.linq.expressions.expression?view=netcore-3.1">hemen şurada</a>. Peki bu arkadaşın olayı nedir? Günlük hayatta bu class’ı doğrudan kullanmıyoruz ve pek çok kişi de daha önce görmemiş dahi olabilirken kendisi tüm yazılmış sorguların tam kalbinde durmakta. <strong>Where</strong> metodunun kaynağına gittiğimizde, bu arkadaşa rastlamış oluyoruz. Gönderdiğimiz parametrenin tipini Expression olarak görüyoruz:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1021/1*Fh82XfMV7R57sl7BGHP11g.png" /></figure><p>Doğrudan bir func değil de, Generic TSource tipinde parametre alıp bool döndüren bir func expression parametresi isteniyor. Yani yukarıda belirtmiş olduğum her iki örnekte de aslında bir expression oluşturuyoruz fakat C# dili bunu bize kolaylaştıracak kısayollar sunduğundan, oluşturduğumuzu göremiyoruz. Bu Expression’ların nasıl oluştuğunu ele alacak olursak; Lambda’nın yalnızca bir yazım, belirtme şekli olduğundan bahsetmiştik. Yani yazmış olduğumuz bu lambda, alınıp, yorumlanıp bir expression oluşturuluyor. Kabaca bir şema çizmeye çalıştım:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*D4GrKgxMZrMtdw63zQkfxQ.png" /></figure><p>Peki aynı Query’i doğrudan Expression ile yazsaydık ne olurdu? Aradan parse ve convert mantığını çıkartıp, direkt Expression da yazmamız mümkün. Tabi ki de bu şekilde yazması zahmetli, okunaksız ve biraz zor. Zaten bundan dolayı LINQ ve Lambda hayatımıza girdi. Fakat yine de nasıl yapıldığını inceleyelim:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*7NS7tZ0Qq3ncf5TSiSAZxg.png" /></figure><p>İki sorgunun da bire bir aynısını ürettiğini görüyoruz. Aradan Parse ve Convert işlemini çıkardığımıza göre bir değişiklik olması gerekiyor. Hemen basit bir StopWatch yardımı ile arada bir zaman farkı var mı diye bakalım:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*ztz1Sb_XXmbeErKFPuNufA.png" /></figure><p>Doğrudan expression ile üretilen sorgu yaklaşık 6 kat daha kısa sürede üretilmiş oldu. Bu yanıltıcı bir değer olabilir. Program ilk ayağa kalktığındaki RAM’e erişim ile ikinci erişim arasında ciddi bir fark olabilir, ondan dolayı 100biner kez çalıştırıp ortalamasını alırsak, ilk çalışmanın oluşturduğu dezavantaj oldukça az etki edecek ve bir nebze daha doğru bir sonuç alabileceğiz:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*p0BqWWIbGHqx_EG3Hl4Y7Q.png" /></figure><p>Bu işlemden sonra, doğrudan Expression yazmanın <strong>1.3</strong>~ kat daha hızlı çalıştığını görmüş olduk.</p><p>Fakat bu sizi kesinlikle büyülemesin. Yazının girişinde de bahsettiğim gibi, bu yalnızca bir over-engineering yapmayı sevenler için bir inceleme. Bahsi geçen süreye değinmek gerekirse;</p><ul><li>a işlemi için 0,062 ms</li><li>b işlemi için 0,042 ms</li></ul><p>olarak görünüyor. 1 milisaniyenin 10&#39;da birinden bile küçük bir farktan bahsediyoruz. 50–60ms bile insan gözüyle fark edilemezken, bu farkın kayda bile değmeyecek olduğunu kabullenmemiz gerekir.</p><p>Burada bahsi geçen süreler tamamıyla C# sorguları üretmekle ilgilidir. Kesinlik herhangi bir veritabanı sorgusuyla uzaktan yakından alakası yoktur. Zira veritabanı sorguları bu oluşturmuş olduğumuz Expression’lardan okunarak üretilir, ve her bir provider’ın kendi sorgu oluşturma algoritması vardır. Sorgu performansı ve kalitesi kullanılan provider’dan provider’a farklılık gösterebilir. Entity Framework de, bu ortak Expression objesi sayesinde, bu kadar veritabanı destekliyor. Yazılmış aynı sorgu, her bir provider tarafından kendince yorumlanıp sql veya herhangi bir nosql sorgusuna dönüştürülüp kullanılabiliyor. Bu sayede yazılmış sorgularınızı değiştirmeden provider ve veritabanı değiştirebiliyorsunuz. Hatta siz de bu expression’ları yorumlayıp sorgu üreten bir provider yazabilirsiniz.</p><p>Özetle, bir programlama dilinde ne kadar alt seviyelere inerseniz, işi core kısımda çözmeye çalışırsanız, aradan çıkardığınız katmanlarla birlikte performans artacaktır. Fakat bu çoğu zaman over-engineering’den başka bir şey değildir. Bu konu, sizi biraz olsun eğlendirip, günlük temponuzdan uzaklaştırabildiyse ne mutlu bana.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dbef9b329b4c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kovaryans ve Kontravaryans nedir? — C#]]></title>
            <link>https://enisn.medium.com/kovaryans-ve-kontravaryans-nedir-c-ecd6e0fcbfd6?source=rss-4c08bf8ed488------2</link>
            <guid isPermaLink="false">https://medium.com/p/ecd6e0fcbfd6</guid>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Enis Necipoğlu]]></dc:creator>
            <pubDate>Sat, 09 May 2020 21:26:21 GMT</pubDate>
            <atom:updated>2020-07-27T09:18:05.374Z</atom:updated>
            <content:encoded><![CDATA[<h3>Kovaryans ve Kontravaryans nedir? — C#</h3><p>Pek çoğumuz, farklı farklı yerlerde IEnumerable&lt;T&gt; kullanımına rastlamışızdır. Peki neden doğrudan List&lt;T&gt; kullanmak yerine miras almış olduğu interface’i kullanırız? Bu sorunun tam anlamıyla cevabını verebilmem için öncelikle <strong>covariance</strong> ve <strong>contravariance</strong> hakkında bir kaç bilgi vermem gerekecek. Tabii ki tek sebebi contravariance değil, IEnumerable’ın iterable olması ve henüz tüm elemanların hesaplanmamış olması da var tabi ki fakat ona bu yazıda değinmeyeceğim. Öncelikle detaylı bilgi için <a href="https://docs.microsoft.com/tr-tr/dotnet/csharp/programming-guide/concepts/covariance-contravariance/">covariance-contravariance dokümanı</a>’nı ziyaret edebilirsiniz. Ben bir kaç örnek üzerinden anlatmaya çalışacağım.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*y_HcgX7RsK0fazaZ" /><figcaption>Photo by <a href="https://unsplash.com/@roman_lazygeek?utm_source=medium&amp;utm_medium=referral">Roman Mager</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Covariance &amp; Contravariance</h3><p>C#’da hepimizin aşina olduğu gibi, bir değişkenin içerisine kendisinden miras alan daha alt bir nesne atamasını yapabiliyoruz, ve tümünü miras aldıkları ortak özelliklerine göre işleme sokabiliyoruz. Fakat aynı değişkene farklı tipte bir nesne ataması yapamıyoruz. Örnek vermek gerekirse; string olarak tanımladığınız bir değişkene int değer ataması yapamamamız gibi. Tam olarak bu tip koruma işlemini yapan <strong>Covariance</strong> idir. Ancak bazı durumlarda bu tip korumasını delmemiz gerekebiliyor. Tıpkı bir nesneyi kendisinden daha büyük bir tipte tanımlanmış değişkenin içerisine aktarırken olduğu gibi. Örnek vermek gerekirse; objecttipinde tanımlanmış bir değişkenin içerisine string tipinde bir değer ataması yapabilmemiz. Bu ise <strong>Contravariance</strong>’dır. Tam olarak delmek diyemesek de, bazı özelliklerini ortak kullanmamıza olanak sağlamaktadır.</p><p>— -</p><p>Hemen bir örnek ile ilerleyelim. Şöyle bir interface’imizin olduğunu düşünelim:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/469565ca00bcb84ce564c1223fb5f210/href">https://medium.com/media/469565ca00bcb84ce564c1223fb5f210/href</a></iframe><p>Hemen sormak istediğim soru şu:</p><blockquote>Bir <strong>IDataProvider&lt;object&gt; </strong>tipinde tanımlanmış değişkenin içerisine, başka bir <strong>IDataProvider&lt;string&gt; </strong>değişkenindeki verinin atamasını yapabilir miyim?</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d04108a0cbab1e02fdc67fc12c62aa58/href">https://medium.com/media/d04108a0cbab1e02fdc67fc12c62aa58/href</a></iframe><p>Cevap işin daha da ilginçleşmesini sağlayacak. Çünkü normal şartlarda cevap “Hayır!”.</p><p>Hemen IDataProvider interface’ini IEnumerable olarak değiştirirsek, compiler’ın artık hata vermediğini ve bu atama işlemine izin verdiğini göreceğiz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/04b840df07579f158613ae4452453ef1/href">https://medium.com/media/04b840df07579f158613ae4452453ef1/href</a></iframe><p>Peki, IEnumerable bunu nasıl yapabiliyor? Kaynağını ziyaret ettiğinizde bir anahtar kelime göreceksiniz. “<strong>out</strong>” anahtar kelimesi. Contravariance ve Covariance C# ortamında out ve in anahtar kelimeleri ile yönetilir. Kısaca bunlara ve kullanımlarına da değindikten sonra her şey çok daha net olacak.</p><h3><strong>Out Generic Modifier</strong></h3><p>Türkçe’si Out Genel Değiştirici olan bu anahtar kelime hakkında detaylı bilgi için <a href="https://docs.microsoft.com/tr-tr/dotnet/csharp/language-reference/keywords/out-generic-modifier">microsoft dokümanını</a> ziyaret edebilirsiniz. Out parametresi generic type parametrelerinin önüne ekleyebileceğimiz bir modifier aslında. Kullanımı da şu şekilde:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec71553e057a6372e03a2ddf28c1cd27/href">https://medium.com/media/ec71553e057a6372e03a2ddf28c1cd27/href</a></iframe><p>Tabii ki bunu yapmak bize ne sağlayacak hemen buna değinelim. <strong>Out</strong> modifier’ını kullandığımız T tipi, bu interface’den yalnızca dışarı çıkabilir, içeriye bu tip giremez. Zaten bu sebepten ötürü ileride içerisine T tipinden inherit alan bir başka parametre ataması yapabileceğiz. Bu kurduğum cümle şu anlama geliyor; T tipi, bu interface içerisindeki herhangi bir metodun dönüş tipi olabilirken, hiçbir metot T tipinde bir parametre alamaz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/09140a6dfa7c842d64464df223593746/href">https://medium.com/media/09140a6dfa7c842d64464df223593746/href</a></iframe><h3><strong>In Generic Modifier</strong></h3><p>Bu anahtar kelime ise <strong>out</strong>’un tam tersi bir işleve sahip ve onun yaptığının aksine, tip korumasını daha da sağlamlaştırıyor. Kullanımı da şu şekilde:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3df457577028be658794a451aff5aef3/href">https://medium.com/media/3df457577028be658794a451aff5aef3/href</a></iframe><p>Peki bunu belirtmiş olmak ne anlama geliyor? <strong>In</strong> modifier kullandığımız T tipi, bu interface’e yalnızca girebilir, dışarı çıkarılamaz. Bu da şu anlama geliyor. T tipi herhangi bir metodun dönüş tipi olarak kullanılamaz, fakat herhangi bir metot T tipinde bir parametre alabilir.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/945f51699ff04739016aeb5e38e206ad/href">https://medium.com/media/945f51699ff04739016aeb5e38e206ad/href</a></iframe><h3>Peki nasıl kullanırız?</h3><p>Tabii ki bu kadar teorik bilgiden sonra, gerçek manada işimize yaradığına şahit olmak için örneğimize geri dönelim. <strong>IDataProvider</strong> örneğinde atama yapamamamızın sebebi, msbuild’in tip korumasından kaynaklı, fakat biz biliyoruz ki TData tipi, bu interface’den yalnızca dışarıya çıkarılıyor, içeriye alınmıyor. O zaman <strong>out</strong> işlecini kullanmamızda bir sakınca görünmüyor. Peki out işlecini eklediğimizde hayatımızda neler değişecek?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/78749259d3473a7c37a649a89596ff54/href">https://medium.com/media/78749259d3473a7c37a649a89596ff54/href</a></iframe><p>Tekrar bir önceki atama işlemine döndüğümüzde ise hata veren satırın artık hata vermediğini görebiliriz. Yani şu atama işlemini artık yapabileceğiz:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7cc86ddb79720c90284a6b3392babcc4/href">https://medium.com/media/7cc86ddb79720c90284a6b3392babcc4/href</a></iframe><p>Basit bir matematik aslında hayat kurtarabiliyor. Zekice kurgulanmış mimariler çok uzun süre ayakta kalabilirler. Hiçbir programlama dili if statement’lardan ibaret değildir. Yıkılmayacak sağlam mimariler kurmanız için umarım alet çantanıza bir alet de ben ekleyebilmişimdir.</p><h3>Referanslar</h3><ul><li><a href="https://docs.microsoft.com/tr-tr/dotnet/csharp/programming-guide/concepts/covariance-contravariance/">https://docs.microsoft.com/en-US/dotnet/csharp/programming-guide/concepts/covariance-contravariance/</a></li><li><a href="https://docs.microsoft.com/tr-tr/dotnet/csharp/language-reference/keywords/in-generic-modifier">https://docs.microsoft.com/en-US/dotnet/csharp/language-reference/keywords/in-generic-modifier</a></li><li><a href="https://docs.microsoft.com/en-US/dotnet/csharp/language-reference/keywords/out-generic-modifier">https://docs.microsoft.com/en-US/dotnet/csharp/language-reference/keywords/out-generic-modifier</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ecd6e0fcbfd6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Never null-check again in C#]]></title>
            <link>https://enisn.medium.com/never-null-check-again-in-c-bd5aae27a48e?source=rss-4c08bf8ed488------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd5aae27a48e</guid>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <dc:creator><![CDATA[Enis Necipoğlu]]></dc:creator>
            <pubDate>Fri, 08 May 2020 21:31:54 GMT</pubDate>
            <atom:updated>2020-05-08T21:39:28.268Z</atom:updated>
            <content:encoded><![CDATA[<p>Null-checks are most common and boring code-blocks. A simple null-check code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a6d7624994c5bdab067df32fb328cd43/href">https://medium.com/media/a6d7624994c5bdab067df32fb328cd43/href</a></iframe><p>Each parameter will be checked with if statement and throw <strong>ArgumentNullException</strong> one by one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nwrbIVWRelP25SB0" /><figcaption>Photo by <a href="https://unsplash.com/@moritz_photography?utm_source=medium&amp;utm_medium=referral">Moritz Kindler</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>— -</p><h3><strong>NotNullAttribute</strong></h3><p>There is an attribute which is [NotNull] from <em>System.Diagnostics.CodeAnalysis. </em>This doesn’t check anything at runtime. It only works with CodeAnalysis and raises warnings or errors at compile time <strong>NOT at runtime!</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/225d73ff79d097c9228553d2667c7391/href">https://medium.com/media/225d73ff79d097c9228553d2667c7391/href</a></iframe><h3>Custom Solution</h3><p>Let’s get rid of if statements for null-checks. How to handle assignment of method parameter in csharp? The answer is ‘<em>you can not</em>!’. But you can use another way to handle assignment with implicit operator. Let’s create <strong>NotNull &lt;T&gt;</strong>class and define an implicit operator then we can handle assignments.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b3f4849d302f7ceb8f62ed8cfffd4372/href">https://medium.com/media/b3f4849d302f7ceb8f62ed8cfffd4372/href</a></iframe><p>Now we can use NotNull object as method parameter</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7586d49d83325e60281665d7d131c6c3/href">https://medium.com/media/7586d49d83325e60281665d7d131c6c3/href</a></iframe><p>As you can see <strong>DoSomething()</strong> method has cleaner code then before. Also you can use NotNull class with any type:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc0a1643cf984ac81abcc6c7a64367b3/href">https://medium.com/media/fc0a1643cf984ac81abcc6c7a64367b3/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd5aae27a48e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Challenge #2 — Binding object to string — Deep Dive into Reflection]]></title>
            <link>https://enisn.medium.com/challenge-2-binding-object-to-string-deep-dive-into-reflection-b3ecbaadeff6?source=rss-4c08bf8ed488------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3ecbaadeff6</guid>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[software]]></category>
            <dc:creator><![CDATA[Enis Necipoğlu]]></dc:creator>
            <pubDate>Thu, 07 May 2020 21:24:23 GMT</pubDate>
            <atom:updated>2022-08-02T07:47:15.559Z</atom:updated>
            <content:encoded><![CDATA[<h3>Challenge #2 — Binding object to string — Deep Dive into Reflection</h3><p>Hi again,</p><p>This time, challenge is a simple problem which I thought at my daily routine. The idea comes from trying to pass and place some parameters into e-mail templates. There was no problem with plain text templates, but when try to use html templates, it has started to be harder and complicated to manage. So I needed basically to bind each object properties into placeholders in html string.</p><p>I’ll start with sharing some method to bind parameters to strings in .Net environment. But I need a different way which is easy to use with less lines of code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nNyyl5ybKn507Cqe" /><figcaption>Photo by <a href="https://unsplash.com/@glenncarstenspeters?utm_source=medium&amp;utm_medium=referral">Glenn Carstens-Peters</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>— -</p><p>Let’s start with a sample. I need exactly same thing with following usage. There is a raw string template with placeholders, then I want to be able to bind any type of object to string. Each object properties must be replaced with own placeholder. Let me show with some code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/acb43f16f6579191cbd4c2e1b0c91545/href">https://medium.com/media/acb43f16f6579191cbd4c2e1b0c91545/href</a></iframe><p>This one looks too simple and can be made any existing method in C#. But let’s make it a little bit complicated and bind object properties into html data:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df79f97e7fc0beb98ae06826c24f8711/href">https://medium.com/media/df79f97e7fc0beb98ae06826c24f8711/href</a></iframe><p>Now, my approach is more meaningful. So template string can be much much more complicated and can be read from a file or database. Maybe it can be an e-mail template or something else. This is the challenge: <strong><em>“Binding object proeprties to string!”</em></strong></p><p>— -</p><p>There is a couple of ways to do that in Csharp.</p><p>So let’s start with a classical way:</p><h3>Concatenate String Using + Operator</h3><p>This is really primitive way to build a string but it works well. See following example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b565366915fed80b2950a8c271c37ba/href">https://medium.com/media/2b565366915fed80b2950a8c271c37ba/href</a></iframe><h3>String Interpolation</h3><p>This one is awesome feature of C# and I love using it. String Interpolation is available since <strong>C# 6.0. </strong>Just place a ‘$’ operator at the beginning of string and use any variable between curly braces. It’s Amazing!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7fa3cb21ee80e2cd1c7d74c03928182e/href">https://medium.com/media/7fa3cb21ee80e2cd1c7d74c03928182e/href</a></iframe><h3>String Format</h3><p>This one is most common approach to place parameters into strings. Use some placeholders into string then give them one by one Format method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4dfd0e3cf0751f9bab02adbc171f92a8/href">https://medium.com/media/4dfd0e3cf0751f9bab02adbc171f92a8/href</a></iframe><p>There are much more approach to bind parameters into a string and get one single output. Most advanced approach is made by Microsoft and its name is Razor Engine. I think each .NET Developer knows that. It’s part of Asp.NET MVC and provides to generate HTML outputs with parameters which comes from C# models. This one is awesome, but too heavy to use my dynamic bindings. I needed to bind each object property into a string. For example I have a User object and it includes 16 properties. I don’t want to use + (plus) operator for 16 times to concatenate entire string. Also string format is almost same… I don’t want to write each 16 properties as method parameter. It’s unmanageable. Object properties can be changed, added or be deleted.</p><p>Before starting, we must know something like: how to find and iterate object properties at runtime and replace them with its placeholders. Let’s deep dive into Reflection.</p><h3>Reflection in .NET</h3><p>System.Reflection is a namespace which provides to explore Types and members in compiled assemblies. <a href="https://docs.microsoft.com/en-US/dotnet/framework/reflection-and-codedom/reflection">Visit here </a>for much more details.</p><p>We start with getting object properties with reflection. Just realize something, before diving into reflection.</p><p>“<em>How to reach object properties in normal ways?”</em></p><p><strong>Member Access Operator (.)</strong></p><p>Everyday, each developer uses dot (.) operator and mostly even don’t know it’s an operator to access a member of an object. When you use user.Email , you access <strong>Email</strong> member of object which placed in <strong>user</strong> named variable.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/95fd3d511d2c9f61b81f8c7677fc38ff/href">https://medium.com/media/95fd3d511d2c9f61b81f8c7677fc38ff/href</a></iframe><p>Let’s try to make same operation with reflection:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7bbfedd3fc3ce95ca27cb03e99e34218/href">https://medium.com/media/7bbfedd3fc3ce95ca27cb03e99e34218/href</a></iframe><p>As you can see, property name can be used as string. This makes me free to find any property name in any type of object.</p><h3>Iterate object properties</h3><p>Iterating object property names and values is easy and can be done with one single foreach statement.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7c775adffdd8a7507a22cf6a3a3c75f3/href">https://medium.com/media/7c775adffdd8a7507a22cf6a3a3c75f3/href</a></iframe><p>As you can see, I can access each property name and values as dynamically. That is an awesome knowledge to complete my challenge. I’ll find property names between curly braces and replace them.</p><p>— -</p><h3>Binding Object Properties into Placeholders in String</h3><p>This is most awesome part of article. Let’s use following string template which includes some property names in it.</p><p>Welcome back {Name}. You&#39;re authenticated as {Email}. Have a good day.</p><p>I can find each object property names and replace them easily.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/67ca5eadf6b104924e86029f42b86983/href">https://medium.com/media/67ca5eadf6b104924e86029f42b86983/href</a></iframe><p>Yeah, this one works. But it’s awful code. It is not performing. This is object-first approach and tries to replace even property placeholder doesn’t exist in string template. Let’s think about approaching template-first instead of object-first. To make that, I need to find all placeholders in string template. Following method helps me to find all placeholders in string.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/85e671173e1c044e20ca12e450dc5847/href">https://medium.com/media/85e671173e1c044e20ca12e450dc5847/href</a></iframe><p>Then I can iterate this IEnumerable</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/75e3619b89f6b42774b44662d545d474/href">https://medium.com/media/75e3619b89f6b42774b44662d545d474/href</a></iframe><p>That one works but it’s not perfectly yet. It works via accessing directly to object members.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ed6f6968d2351844749044a0b66f549/href">https://medium.com/media/0ed6f6968d2351844749044a0b66f549/href</a></iframe><p>❗ But will not work for nested object members with trying to access with multiple dots like following string. 🤔</p><p>Welcome back {Name}. You&#39;re logged in from {Profile.Address.Country.Code}. Have a good day.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06b9ed19517812c8b9e7770c7ad430eb/href">https://medium.com/media/06b9ed19517812c8b9e7770c7ad430eb/href</a></iframe><p>— -</p><p>I need to split each parameter name with ‘.’ (dot) and try to access each nested members to find last one. So, following method helps to do that:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f69474139bb3c3c9dc730e88c594ec8a/href">https://medium.com/media/f69474139bb3c3c9dc730e88c594ec8a/href</a></iframe><p>Now I can get nested object property values. Let’s complete binding method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0321f0afb2aa3065bf11098afdf32a2d/href">https://medium.com/media/0321f0afb2aa3065bf11098afdf32a2d/href</a></iframe><p>— -</p><p>Now works perfectly 👌</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4495f89c9274c023e4a992f96f294275/href">https://medium.com/media/4495f89c9274c023e4a992f96f294275/href</a></iframe><p>You can see and use entire <strong>BindingExtensions</strong> class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c9b7f83dcfb92a1bb80af1931898aae/href">https://medium.com/media/0c9b7f83dcfb92a1bb80af1931898aae/href</a></iframe><h3>Alternatives</h3><p>Thank you four reading until here. :)</p><p>This approach has alternatives to use. Most common one is Razor as I told before in article. If you know and use another alternatives you can inform me.</p><p>Have a good day :)</p><ul><li>Razor Engine</li><li><a href="https://github.com/scriban/scriban">Scriban</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3ecbaadeff6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>