<?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 Göktuğ Yıldırım on Medium]]></title>
        <description><![CDATA[Stories by Göktuğ Yıldırım on Medium]]></description>
        <link>https://medium.com/@goktugyildirim?source=rss-cf49de83691a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Q48zd_pGmIgtz_yQAKYRLQ.png</url>
            <title>Stories by Göktuğ Yıldırım on Medium</title>
            <link>https://medium.com/@goktugyildirim?source=rss-cf49de83691a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 16:44:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@goktugyildirim/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[Unit Test Nedir? Niçin Gereklidir? xUnit ile Unit Test Nasıl Geliştirilir?]]></title>
            <link>https://medium.com/@goktugyildirim/unit-test-nedir-ni%C3%A7in-gereklidir-xunit-ile-unit-test-nas%C4%B1l-geli%C5%9Ftirilir-8067a4ebf8a1?source=rss-cf49de83691a------2</link>
            <guid isPermaLink="false">https://medium.com/p/8067a4ebf8a1</guid>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[net-core]]></category>
            <category><![CDATA[xunit]]></category>
            <category><![CDATA[moq]]></category>
            <dc:creator><![CDATA[Göktuğ Yıldırım]]></dc:creator>
            <pubDate>Thu, 21 Aug 2025 22:33:49 GMT</pubDate>
            <atom:updated>2025-08-21T22:33:49.144Z</atom:updated>
            <content:encoded><![CDATA[<p>Unit Test, yazılımda en küçük bağımsız parçaları (method, sınıf gibi) izole şekilde test ederek doğru çalıştığından emin olmamızı sağlayan otomatik testlerdir.</p><h3>Neden Gereklidir?</h3><ul><li>Hataları erken aşamada yakalar.</li><li>Refactoring sırasında güvence sağlar.</li><li>Kodun sürdürülebilirliğini ve güvenilirliğini artırır.</li><li>Dokümantasyon gibi çalışır, metodun beklenen davranışını gösterir.</li></ul><h3>xUnit Nedir?</h3><p>xUnit, .NET dünyasında en çok kullanılan test framework’lerinden biridir.<br>Basit, hafif ve modern bir yapıya sahiptir. MSTest ve NUnit gibi alternatifleri vardır. Bu makalemizde xUnit kullanacağız.</p><h3>İçindekiler</h3><ol><li>Arrange, Act, Assert (AAA) Yapısı</li><li>Fact</li><li>Theory ve InlineData</li><li>dotnet test komutu</li><li>Name Format</li><li>Moq servis nedir, nasıl kullanılır</li><li>Moq üzerinde Verify, Throws ve Callback</li><li>EF Core InMemory ve SQLite InMemory farkları</li></ol><h3>1. Arrange, Act, Assert (AAA) Yapısı</h3><p>Birim testlerin yazımında kullanılan en yaygın format, AAA (Arrange-Act-Assert) yapısıdır. Bu yapı, testlerinizi düzenli ve anlaşılır hale getirir.</p><ul><li>Arrange: Test için gerekli veriler hazırlanır.</li><li>Act: Test edilecek metod çağrılır.</li><li>Assert: Sonuçların beklenen ile aynı olup olmadığı kontrol edilir.</li></ul><h3>2. Fact</h3><p>[Fact] özniteliği, xUnit’te parametre almayan, her zaman aynı şekilde çalışan testler için kullanılır.</p><pre>[Fact]<br>public void Add_TwoNumbers_ReturnsSum()<br>{<br>    // Arrange - Hazırlık (test verilerini ve ortamını hazırlama)<br>    var calculator = new Calculator();<br>    int a = 5;<br>    int b = 7;<br>     <br>    // Act - Eylem (test edilecek metodu çağırma)<br>    int result = calculator.Add(a, b);<br>     <br>    // Assert - Doğrulama (beklenen sonuç ile gerçek sonucu karşılaştırma)<br>    Assert.Equal(12, result);<br>}</pre><h3>3. Theory ve InlineData</h3><p>[Theory] parametreli testler için kullanılır.<br>[InlineData] ile farklı test verileri sağlanabilir.</p><pre>[Theory]<br>[InlineData(2, 3, 5)]<br>[InlineData(10, 5, 15)]<br>public void Sum_ShouldReturnCorrectResult(int a, int b, int expected)<br>{<br>    var calculator = new Calculator();<br> <br>    var result = Calculator.Sum(a, b);<br>     <br>    Assert.Equal(expected, result);<br>}<br> <br>[Theory]<br>[InlineData(2, true)]<br>[InlineData(17, true)]<br>[InlineData(20, false)]<br>[InlineData(1, false)]<br>public void IsPrime_WithVariousNumbers_ReturnsCorrectResult(int number, bool expected)<br>{<br>    var calculator = new Calculator();<br> <br>    bool result = calculator.IsPrime(number);<br>     <br>    Assert.Equal(expected, result);<br>}</pre><p>InlineData özniteliği, test metoduna parametre olarak iletilecek değerleri belirtir. Bu sayede tek bir test metodunu farklı girdi kombinasyonlarıyla çalıştırabilirsiniz.</p><h3>4. dotnet test komutu</h3><p>.NET Core projelerinizde testleri çalıştırmak için dotnet test komutunu kullanabilirsiniz. Bu komut, test projenizde bulunan tüm testleri çalıştırır.</p><pre># Tüm testleri çalıştırma<br>dotnet test<br> <br># Belirli bir test projesindeki testleri çalıştırma<br>dotnet test API.Tests/API.Tests.csproj<br> <br># Belirli bir test sınıfı çalıştırma<br>dotnet test --filter &quot;FullyQualifiedName=CalculatorTests&quot;<br> <br># Belirli bir test metodunu çalıştırma<br>dotnet test --filter &quot;FullyQualifiedName=CalculatorTests.Add_TwoNumbers_ReturnsSum&quot;<br> <br># Detaylı çıktı ile testleri çalıştırma<br>dotnet test --verbosity normal<br> <br># Belirli isim desenini içeren testleri çalıştırma (~ operatörü)<br>dotnet test --filter &quot;FullyQualifiedName~CalculatorTests&quot;<br> <br># Test sonuçlarını XML formatında kaydetme<br>dotnet test --logger &quot;trx;LogFileName=testresults.trx&quot;<br> <br># Console üzerinde detaylı test sonucu alma<br>dotnet test --logger &quot;console; verbosity=detailed&quot;<br> <br># HTML raporu oluşturma<br>dotnet test --logger &quot;html;LogFileName=testresults.html&quot;<br> <br># JUnit XML raporu oluşturma (Jenkins / GitLab CI gibi araçlarda kullanılır)<br>dotnet test --logger &quot;junit;LogFileName=testresults.xml&quot;<br> <br># JSON formatında test sonucu alma<br>dotnet test --logger &quot;json;LogFileName=testresults.json&quot;</pre><figure><img alt="xUnit example run" src="https://cdn-images-1.medium.com/max/856/1*0t50oavYOmFlGr6BKSFAog.png" /></figure><h3>5. Test İsimlendirme Formatı</h3><p>İyi bir test ismi, testin amacını, test edilen senaryoyu ve beklenen sonucu açıkça ifade etmelidir. Yaygın bir format:<br>Genel format: MethodName_StateUnderTest_ExpectedBehavior</p><ul><li>Divide_ByZero_ThrowsDivideByZeroException</li><li>IsPrime_WithVariousNumbers_ReturnsCorrectResult</li><li>CalculateFactorial_WithNegativeNumber_ThrowsArgumentException</li></ul><p>Bu format, testlerin amacını ve kapsamını net bir şekilde ifade eder. Başarısız bir testle karşılaştığınızda, neyin test edildiğini ve neyin beklendiğini hızlıca anlayabilirsiniz.</p><h3>6. Moq Servis Nedir, Nasıl Kullanılır?</h3><p>Moq, .NET için popüler bir mocking (taklit) kütüphanesidir. Birim testlerde, test edilen sınıfın bağımlılıklarını izole etmek için kullanılır. Moq ile:</p><ol><li>Interface veya abstract sınıfların mock (sahte) versiyonlarını oluşturabilirsiniz.</li><li>Mock nesnelerin hangi metodlarının çağrıldığında ne döndüreceğini belirtebilirsiniz.</li><li>Mock nesnelerin hangi parametrelerle çağrıldığını doğrulayabilirsiniz.</li></ol><p>Örnek kullanım:</p><pre>// Mock repository oluşturma<br>var mockRepository = new Mock&lt;ITodoRepository&gt;();<br> <br>// Repository&#39;nin davranışını belirleme<br>mockRepository.Setup(repo =&gt; repo.GetByIdAsync(1, It.IsAny&lt;CancellationToken&gt;()))<br>    .ReturnsAsync(new TodoItem { Id = 1, Title = &quot;Test Todo&quot;, IsDone = false });<br> <br>// Mock nesneyi kullanma<br>var todoService = new TodoService(mockRepository.Object);</pre><h3>7. Moq Üzerinde Verify, Throws ve Callback</h3><p>Moq, mock nesnelerin davranışlarını ve etkileşimlerini doğrulamak için çeşitli yöntemler sunar:</p><h3>Verify</h3><p>Verify metodu, bir mock nesnenin belirli bir metodunun beklendiği gibi çağrılıp çağrılmadığını kontrol eder:</p><pre>// Repository&#39;nin AddAsync metodunun belirli parametrelerle çağrıldığını doğrulama<br>//Times ise bu servisin kaç defa çalıştığını belirtir. &#39;Once&#39; seçeneği bir kez çalıştığını belirtir.<br> <br>mockRepository.Verify(repo =&gt; repo.AddAsync(<br>    It.Is&lt;TodoItem&gt;(item =&gt; item.Title == &quot;New Todo&quot; &amp;&amp; item.IsDone == false), <br>    It.IsAny&lt;CancellationToken&gt;()), <br>    Times.Once);</pre><h3>Throws</h3><p>Throws veya ThrowsAsync metodları, mock nesnenin istisna fırlatmasını simüle etmenize olanak tanır:</p><pre>// Repository&#39;nin istisna fırlatmasını ayarlama<br>mockRepository.Setup(repo =&gt; repo.AddAsync(It.IsAny&lt;TodoItem&gt;(), It.IsAny&lt;CancellationToken&gt;()))<br>    .ThrowsAsync(new InvalidOperationException(&quot;Database error&quot;));<br> <br>// İstisnanın fırlatılacağını doğrulama<br>await Assert.ThrowsAsync&lt;InvalidOperationException&gt;(() =&gt; <br>    todoService.CreateAsync(new TodoCreateDto { Title = &quot;New Todo&quot;, IsDone = false }));</pre><h3>Callback</h3><p>Callback metodu, mock bir metodun çağrıldığında özel bir işlem gerçekleştirmenize olanak tanır:</p><pre>TodoItem capturedItem = null;<br> <br>mockRepository.Setup(repo =&gt; repo.UpdateAsync(It.IsAny&lt;TodoItem&gt;(), It.IsAny&lt;CancellationToken&gt;()))<br>    .Callback&lt;TodoItem, CancellationToken&gt;((item, ct) =&gt; capturedItem = item)<br>    .ReturnsAsync(new TodoItem { Id = 1, Title = &quot;Updated Todo&quot;, IsDone = true });<br> <br>// Yakalanan parametreyi kontrol etme<br>Assert.NotNull(capturedItem);<br>Assert.Equal(1, capturedItem.Id);<br>Assert.Equal(&quot;Updated Todo&quot;, capturedItem.Title);</pre><h3>8. EF Core InMemory ve SQLite InMemory</h3><p>Entity Framework Core, birim ve entegrasyon testlerinde kullanabileceğiniz iki farklı in-memory veritabanı sağlayıcısı sunar:</p><h3>EF Core InMemory</h3><p>EF Core InMemory, tamamen hafızada çalışan ve gerçek bir veritabanı motoru kullanmayan bir sağlayıcıdır:</p><pre>// InMemory veritabanı için options oluşturma<br>var options = new DbContextOptionsBuilder&lt;ApplicationDbContext&gt;()<br>    .UseInMemoryDatabase(databaseName: $&quot;TestDb_{Guid.NewGuid()}&quot;)<br>    .Options;<br> <br>// Context ve repository oluşturma<br>await using var context = new ApplicationDbContext(options);<br>var repository = new TodoRepository(context);<br> <br>// Test verileri ekleme<br>await context.Todos.AddRangeAsync(<br>    new TodoItem { Id = 1, Title = &quot;Test Todo 1&quot;, IsDone = false },<br>    new TodoItem { Id = 2, Title = &quot;Test Todo 2&quot;, IsDone = true }<br>);<br>await context.SaveChangesAsync();<br> <br>// Testi gerçekleştirme<br>var todos = await repository.GetAllAsync();<br>Assert.Equal(2, todos.Count);</pre><h3>SQLite InMemory</h3><p>SQLite InMemory, gerçek bir SQLite veritabanı motorunu hafızada çalıştırır:</p><pre>// SQLite InMemory bağlantısı oluşturma<br>var connection = new SqliteConnection(&quot;DataSource=:memory:&quot;);<br>connection.Open();<br> <br>var options = new DbContextOptionsBuilder&lt;ApplicationDbContext&gt;()<br>    .UseSqlite(connection)<br>    .Options;<br> <br>// Veritabanını oluşturma<br>await using (var context = new ApplicationDbContext(options))<br>{<br>    await context.Database.EnsureCreatedAsync();<br>    // Test verileri ekleme...<br>}<br> <br>// Yeni bir context ile test etme<br>await using (var context = new ApplicationDbContext(options))<br>{<br>    var repository = new TodoRepository(context);<br>    var result = await repository.GetByIdAsync(1);<br>    // Sonuçları doğrulama...<br>}<br> <br>// Bağlantıyı kapatma<br>await connection.CloseAsync();</pre><h3>Farkları</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*-WEPfKKpA0IN2MvK_Lgf5A.png" /></figure><h3>Sonuç</h3><p>xUnit ve Moq kullanarak birim testler yazmak, kodunuzun kalitesini artırmak ve hata riskini azaltmak için çok etkili bir yöntemdir. Bu makalede gördüğümüz gibi, testlerinizi düzenli bir yapıda yazarak, farklı senaryoları test ederek ve bağımlılıkları izole ederek kodunuzun beklenen şekilde çalıştığından emin olabilirsiniz.</p><p>Ayrıca, EF Core InMemory ve SQLite InMemory gibi araçlarla, gerçek veritabanına bağımlılık olmadan repository katmanınızı test edebilir, gerektiğinde gerçek veritabanı sistemleriyle de entegrasyon testleri yapabilirsiniz.</p><p>İyi bir test stratejisi, yazılım geliştirme sürecinizin ayrılmaz bir parçası olmalıdır. Testlerinizi erken ve sık çalıştırarak, kodunuzdaki potansiyel sorunları hızla tespit edebilir ve giderebilirsiniz.</p><p>Github: <a href="https://github.com/gyildirimm/unit-test">.NET Core’da xUnit ile Unit Test Örneği</a></p><p>KAYNAKÇA</p><ul><li><a href="https://xunit.net/">xUnit.net Resmi Websitesi</a> — xUnit framework’ünün resmi websitesi, dokümantasyon ve örnekler içerir.</li><li><a href="https://learn.microsoft.com/tr-tr/dotnet/core/testing/">Microsoft Learn — .NET’te Birim Testleri</a> — Microsoft’un resmi test dokümantasyonu.</li><li><a href="https://github.com/xunit/xunit">xUnit GitHub Repository</a> — xUnit’in açık kaynak kod tabanı ve dokümantasyonu.</li><li><a href="https://www.udemy.com/course/aspnet-core-mvc-api-unit-test-yazma">ASP.NET Core MVC &amp; API Unit Test Yazma (Türkçe)</a> — ASP.NET Core MVC ve API projeleriniz için unit test yazmayı öğreten Türkçe kurs.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8067a4ebf8a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OpenTelemetry .NET]]></title>
            <link>https://medium.com/@goktugyildirim/opentelemetry-net-04832c262e78?source=rss-cf49de83691a------2</link>
            <guid isPermaLink="false">https://medium.com/p/04832c262e78</guid>
            <category><![CDATA[loki]]></category>
            <category><![CDATA[opentelemetry]]></category>
            <category><![CDATA[grafana]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[tempo]]></category>
            <dc:creator><![CDATA[Göktuğ Yıldırım]]></dc:creator>
            <pubDate>Mon, 17 Mar 2025 20:43:24 GMT</pubDate>
            <atom:updated>2025-03-17T20:43:24.077Z</atom:updated>
            <content:encoded><![CDATA[<h3>OpenTelemetry .NET Uygulamaları için OpenTelemetry: Grafana, Loki, Tempo ve Prometheus ile Gözlemlenebilirlik</h3><h3>🔍 OpenTelemetry Nedir?</h3><p>OpenTelemetry (OTel), dağıtılmış sistemlerde telemetri verilerini (tracing, metrics, logs) toplamak ve birden fazla backend sistemine göndermek için kullanılan açık kaynaklı bir gözlemlenebilirlik çerçevesidir.<br>Prometheus, Grafana Tempo, Jaeger ve diğer sistemlerle entegrasyon sağlar.</p><h3>🚀 OpenTelemetry Bileşenleri</h3><ol><li>Tracing (İzleme): Servisler arası isteklerin nasıl ilerlediğini takip eder.</li><li>Metrics (Metrikler): Uygulamanın performansını ölçen zaman serisi verilerini toplar.</li><li>Logging (Loglama): Uygulamanın içindeki olayları detaylı olarak kaydeder.</li></ol><h3>🎛 OpenTelemetry Instrumentation’ları Nelerdir?</h3><p>Instrumentation, uygulamaların otomatik olarak telemetri verisi üretmesini sağlayan ara katman kütüphaneleridir.</p><h3>📌 .NET Core’da OpenTelemetry Instrumentation’ları</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*z8Evffu04EMRi_BlpSCeNg.png" /></figure><h3>📌 .NET Core OpenTelemetry Kullanımı</h3><pre>// OpenTelemetry yapılandırması<br>        builder.Services.AddOpenTelemetry()<br>        .WithTracing(tracerProvider =&gt;<br>        {<br>            tracerProvider<br>                .AddSource(activitySource.Name)<br>                .SetResourceBuilder(ResourceBuilder.CreateDefault()<br>                    .AddService(&quot;ExampleWebAPI&quot;)<br>                    .AddTelemetrySdk()<br>                    .AddEnvironmentVariableDetector())<br>                .AddAspNetCoreInstrumentation(options =&gt;<br>                {<br>                    options.Filter = null; // Tüm istekleri kaydet<br><br>                    options.RecordException = true;<br>                })<br>                .AddHttpClientInstrumentation(options =&gt;<br>                {<br>                    options.RecordException = true;<br>                })<br>                .AddConsoleExporter()<br>                .AddOtlpExporter(opts =&gt;<br>                {<br>                    opts.Endpoint = new Uri(&quot;http://observability-tempo:4317&quot;); // Tempo OTLP gRPC endpoint<br>                    opts.Protocol = OtlpExportProtocol.Grpc; // GRPC protokolünü kullan<br>                });<br>        })<br>        .WithMetrics(metrics =&gt;<br>        {<br>            metrics<br>                .SetResourceBuilder(ResourceBuilder.CreateDefault().AddService(&quot;MyMetricService&quot;))<br>                .AddAspNetCoreInstrumentation() // HTTP request metrikleri<br>                .AddHttpClientInstrumentation() // HTTP client metrikleri<br>                .AddProcessInstrumentation() // İşlem bazlı metrikler (CPU, memory)<br>                .AddRuntimeInstrumentation() // .NET runtime metrikleri<br>                .AddMeter(&quot;System.Runtime&quot;) // .NET Runtime metrikleri için gerekli.. // GC süresi, bellek kullanımı, CPU yükü<br>                .AddMeter(&quot;System.Threading&quot;) // Thread havuzu metrikleri<br>                .AddMeter(&quot;Custom.Http.Meter&quot;)<br>                .AddEventCountersInstrumentation(options =&gt;<br>                {<br>                    // HTTP istek ve bağlantı metrikleri<br>                    options.AddEventSources(&quot;System.Net.Http&quot;); // HTTP istemci istek sayısı<br>                    options.AddEventSources(&quot;System.Net.Sockets&quot;); // TCP bağlantıları<br>                    options.AddEventSources(&quot;System.Net.NameResolution&quot;); // DNS istekleri<br>                    <br>                    // ASP.NET Core metrikleri<br>                    options.AddEventSources(&quot;Microsoft.AspNetCore.Hosting&quot;); // Request süreleri<br>                    options.AddEventSources(&quot;Microsoft.AspNetCore.Http.Connections&quot;); // WebSocket ve SignalR metrikleri<br>                })<br>                .AddConsoleExporter() // Konsola yazdırma<br>                .AddPrometheusExporter(); // Prometheus exporter&#39;ı ekle<br>        });</pre><p>👉 Bu ayarlar sayesinde OpenTelemetry, uygulamanın tracing, metrik ve loglarını otomatik olarak toplayarak uygun backend sistemlerine (Tempo, Prometheus, Loki) aktarır.</p><h3>1️⃣ Grafana Nedir?</h3><p>Grafana, metrikleri, logları ve izleme verilerini görselleştirmek için kullanılan bir açık kaynaklı izleme platformudur.<br>Verileri Prometheus, Loki, Tempo gibi sistemlerden çeker ve bunları dashboard’lar ile sunar.</p><h3>📌 Docker Compose ile Grafana Nasıl Eklenir?</h3><pre>services:<br>  observability-grafana:<br>    image: grafana/grafana:latest<br>    container_name: observability-grafana<br>    ports:<br>      - &quot;9190:3000&quot; # 3000 dış port yerine 9190 kullanıldı<br>    networks:<br>      - observability-example-network<br>    volumes:<br>      - .deploy/grafana:/var/lib/grafana<br>      - .deploy/grafana/provisioning:/etc/grafana/provisioning<br>    environment:<br>      - GF_SECURITY_ADMIN_PASSWORD=admin<br>      - GF_AUTH_ANONYMOUS_ENABLED=true</pre><p>👉 Grafana’yı http://localhost:9190 üzerinden açabilirsin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xXGl8PHXBLaAOGEZ.png" /></figure><h3>2️⃣ Loki Nedir?</h3><p>Loki, merkezi bir log yönetim sistemidir. Promtail ile logları toplayıp Grafana üzerinden görselleştirmeye olanak tanır.<br>Grafana Loki’yi kullanarak sistem loglarını analiz edebiliriz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ix-CyJiFSTSYE3OL.png" /></figure><h3>📌 Docker Compose ile Loki Nasıl Eklenir?</h3><pre>services:<br>  observability-loki:<br>    image: grafana/loki:latest<br>    container_name: observability-loki<br>    ports:<br>      - &quot;9182:3100&quot;<br>    networks:<br>      - observability-example-network<br>    volumes:<br>      - .deploy/loki:/loki<br>      - .deploy/loki/loki-config.yaml:/etc/loki/local-config.yaml</pre><p>👉 Loki’ye Promtail veya Fluentd gibi log toplayıcıları bağlamalısın.</p><h3>📌 Loki Program.cs ve appsettings.json Konfigürasyonu</h3><h4>appsettings.json</h4><pre>&quot;Serilog&quot;: {<br>  &quot;Using&quot;: [ &quot;Serilog.Sinks.Console&quot;, &quot;Serilog.Sinks.Loki&quot; ],<br>  &quot;MinimumLevel&quot;: &quot;Information&quot;,<br>  &quot;WriteTo&quot;: [<br>      {<br>        &quot;Name&quot;: &quot;GrafanaLoki&quot;,<br>        &quot;Args&quot;: {<br>          &quot;uri&quot;: &quot;http://observability-loki:3100&quot;,<br>          &quot;labels&quot;: [<br>            {<br>              &quot;key&quot;: &quot;app&quot;,<br>              &quot;value&quot;: &quot;ExampleWebAPI&quot;<br>            },<br>            {<br>              &quot;key&quot;: &quot;environment&quot;,<br>              &quot;value&quot;: &quot;development&quot;<br>            }<br>          ],<br>          &quot;propertiesAsLabels&quot;: [&quot;RequestId&quot;, &quot;RequestPath&quot;]<br>        }<br>      }<br>  ]<br>}</pre><h4>Program.cs</h4><pre>        builder.Host.UseSerilog((context, loggerConfig) =&gt; loggerConfig.ReadFrom.Configuration(context.Configuration));<br><br><br>        // OpenTelemetry Logging (Uygulama loglarını OpenTelemetry ile entegre eder)<br>        builder.Logging.AddOpenTelemetry(options =&gt;<br>        {<br>            // Log scope&#39;larını (kapsamlarını) dahil eder. <br>            // Örneğin, bir request sırasında oluşturulan kapsamlı logları takip etmeye yarar.<br>            options.IncludeScopes = true;<br><br>            // Log mesajlarının işlenmiş (formatlanmış) halini dahil eder.<br>            // Örneğin, içinde değişkenler olan bir log mesajını doğrudan kaydetmeyi sağlar.<br>            options.IncludeFormattedMessage = true;<br><br>            // Log state&#39;lerini ayrıştırarak (parse ederek) OpenTelemetry&#39;de kullanılabilir hale getirir.<br>            // Örneğin, structured logging formatında logları işlemeye yardımcı olur.<br>            options.ParseStateValues = true;<br>        });</pre><h3>3️⃣ Tempo Nedir?</h3><p>Tempo, dağıtılmış izleme (tracing) için kullanılan bir sistemdir.<br>OpenTelemetry, Jaeger ve Zipkin gibi sistemlerden gelen tracing verilerini saklar ve analiz eder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*a6ajI4uZCWIG4It9.png" /></figure><h3>📌 Docker Compose ile Tempo Nasıl Eklenir?</h3><pre>services:<br>  observability-tempo:<br>    image: grafana/tempo:latest<br>    container_name: observability-tempo<br>    ports:<br>      - &quot;9184:3200&quot;<br>      - &quot;9186:9411&quot;<br>    networks:<br>      - observability-example-network<br>    volumes:<br>      - .deploy/tempo:/tempo<br>      - .deploy/tempo/tempo-config.yaml:/etc/tempo.yaml<br>    expose:<br>      - &quot;4317&quot; # OTLP gRPC bağlantısı için<br>      - &quot;4318&quot; # OTLP HTTP bağlantısı için</pre><p>👉 Tempo’yu Grafana ile bağlayarak tracing verilerini görselleştirebilirsin.</p><h3>📌 Tempo Program.cs Konfigürasyonu</h3><pre>builder.Services.AddOpenTelemetry()<br>    .WithTracing(tracing =&gt;<br>    {<br>        tracing<br>            .AddSource(activitySource.Name)<br>            .SetResourceBuilder(ResourceBuilder.CreateDefault()<br>            .AddService(&quot;ExampleWebAPI&quot;)<br>            .AddTelemetrySdk()<br>            .AddEnvironmentVariableDetector())<br>            .AddAspNetCoreInstrumentation()<br>            .AddHttpClientInstrumentation()<br>            .AddConsoleExporter()<br>            .AddOtlpExporter(opts =&gt;<br>            {<br>                opts.Endpoint = new Uri(&quot;http://observability-tempo:4317&quot;);<br>                opts.Protocol = OtlpExportProtocol.Grpc;<br>            });<br>    });</pre><h3>4️⃣ Prometheus Nedir?</h3><p>Prometheus, metrikleri toplayan ve sorgulayan bir sistemdir.<br>Grafana ile birlikte kullanılarak sistem performansını izlemek ve alarmlar oluşturmak için idealdir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1d6L3SQ1WS88SP0p.png" /></figure><h3>📌 Docker Compose ile Prometheus Nasıl Eklenir?</h3><pre>services:<br>  observability-prometheus:<br>    image: prom/prometheus:latest<br>    container_name: observability-prometheus<br>    ports:<br>      - &quot;9188:9090&quot;<br>    networks:<br>      - observability-example-network<br>    volumes:<br>      - .deploy/prometheus:/prometheus<br>      - .deploy/prometheus/prometheus.yml:/etc/prometheus/prometheus.yml</pre><p>👉 Prometheus metriklerini görmek için: <a href="http://localhost:9188/">http://localhost:9188</a></p><h3>📌 Prometheus Program.cs Konfigürasyonu</h3><pre>builder.Services.AddOpenTelemetry()<br>    .WithMetrics(metrics =&gt;<br>    {<br>        metrics<br>                .SetResourceBuilder(ResourceBuilder.CreateDefault().AddService(&quot;MyMetricService&quot;))<br>                .AddAspNetCoreInstrumentation() // HTTP request metrikleri<br>                .AddHttpClientInstrumentation() // HTTP client metrikleri<br>                .AddProcessInstrumentation() // İşlem bazlı metrikler (CPU, memory)<br>                .AddRuntimeInstrumentation() // .NET runtime metrikleri<br>                .AddMeter(&quot;System.Runtime&quot;) // .NET Runtime metrikleri için gerekli.. // GC süresi, bellek kullanımı, CPU yükü<br>                .AddMeter(&quot;System.Threading&quot;) // Thread havuzu metrikleri<br>                .AddMeter(&quot;Custom.Http.Meter&quot;)<br>                .AddEventCountersInstrumentation(options =&gt;<br>                {<br>                    // HTTP istek ve bağlantı metrikleri<br>                    options.AddEventSources(&quot;System.Net.Http&quot;); // HTTP istemci istek sayısı<br>                    options.AddEventSources(&quot;System.Net.Sockets&quot;); // TCP bağlantıları<br>                    options.AddEventSources(&quot;System.Net.NameResolution&quot;); // DNS istekleri<br>                    <br>                    // ASP.NET Core metrikleri<br>                    options.AddEventSources(&quot;Microsoft.AspNetCore.Hosting&quot;); // Request süreleri<br>                    options.AddEventSources(&quot;Microsoft.AspNetCore.Http.Connections&quot;); // WebSocket ve SignalR metrikleri<br>                })<br>                .AddConsoleExporter() // Konsola yazdırma<br>                .AddPrometheusExporter(); // Prometheus exporter&#39;ı ekle<br>    });<br><br>app.UseOpenTelemetryPrometheusScrapingEndpoint();</pre><h3>🎯 Sonuç</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*jxzXjjCvXAlHhxIrKp1iAA.png" /></figure><p>🚀 Bu rehberi takip ederek Observability sistemini eksiksiz bir şekilde Docker Compose ve .NET Core ile çalıştırabilirsin.</p><p><strong>Github:</strong> <a href="https://github.com/gyildirimm/observability-example">OpenTelemetry &amp; Grafana &amp; Tempo &amp; Loki &amp; Prometheus</a></p><p><strong>Blog: </strong><a href="https://goktugyildirim.com/opentelemetry-net-uygulamalari-icin-opentelemetry-grafana-loki-tempo-ve-prometheus-ile-gozlemlenebilirlik/">OpenTelemetry &amp; Grafana Blog</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=04832c262e78" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Serilog ve Seq ile .NET Uygulamalarında Yapılandırılmış Loglama]]></title>
            <link>https://medium.com/@goktugyildirim/serilog-ve-seq-ile-net-uygulamalar%C4%B1nda-yap%C4%B1land%C4%B1r%C4%B1lm%C4%B1%C5%9F-loglama-24339311566a?source=rss-cf49de83691a------2</link>
            <guid isPermaLink="false">https://medium.com/p/24339311566a</guid>
            <category><![CDATA[serilog]]></category>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[seq]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[net-core]]></category>
            <dc:creator><![CDATA[Göktuğ Yıldırım]]></dc:creator>
            <pubDate>Mon, 17 Mar 2025 20:31:14 GMT</pubDate>
            <atom:updated>2025-03-17T20:33:19.968Z</atom:updated>
            <content:encoded><![CDATA[<h3>Serilog ve Seq ile .NET Uygulamalarında Yapılandırılmış Loglama</h3><h3>Giriş</h3><p>Modern yazılım geliştirmede loglama, uygulamaların sağlığını izlemek ve hata ayıklamak için kritik bir öneme sahiptir. Bu yazıda, .NET ekosisteminde popüler olan Serilog ve Seq teknolojilerini inceleyeceğiz.</p><h3>Serilog Nedir?</h3><p>Serilog, .NET platformu için geliştirilmiş, yapılandırılmış log kayıtları oluşturmaya odaklanmış güçlü bir loglama kütüphanesidir. Geleneksel string formatlamalı loglar yerine, Serilog structured (yapılandırılmış) loglama yaklaşımını benimser.</p><h3>Serilog’un Avantajları</h3><ul><li>Yapılandırılmış Veri: Loglar sadece metin değil, aynı zamanda aranabilir ve filtrelenebilir veri nesneleri olarak saklanır</li><li>Farklı Hedeflere Loglama: Konsoldan veritabanına, dosyadan bulut servislerine kadar çeşitli hedeflere log gönderebilir</li><li>Zenginleştiriciler: Log kayıtlarını otomatik olarak ek bilgilerle zenginleştirebilir</li><li>Performans Odaklı: Minimum performans etkisiyle çalışacak şekilde tasarlanmıştır</li></ul><h3>Seq Nedir?</h3><p>Seq, yapılandırılmış logları toplamak, araştırmak ve analiz etmek için geliştirilmiş modern bir log sunucusudur. Özellikle Serilog gibi yapılandırılmış loglama kütüphaneleriyle mükemmel bir şekilde entegre olur.</p><h3>Seq’in Sunduğu Özellikler</h3><ul><li>Gerçek Zamanlı İzleme: Logları anında görüntüleme ve filtreleme</li><li>Güçlü Sorgu Dili: LINQ benzeri bir sözdizimi ile kompleks sorgulamalar yapabilme</li><li>Dashboard ve Görselleştirme: Log verilerini anlamlı grafikler ve panolarla görselleştirme</li><li>Uyarılar: Belirli koşullar oluştuğunda e-posta, Slack vb. kanallar üzerinden bildirim gönderme</li><li>API Desteği: RESTful API aracılığıyla programatik erişim</li></ul><p>Seq, özellikle çoklu uygulama ortamlarında ve mikroservis mimarilerinde log yönetimini basitleştirir.</p><h3>Gerekli NuGet Paketlerini Yükleme</h3><p>Serilog ve Seq ile çalışmak için aşağıdaki NuGet paketlerini projenize eklemeniz gerekir:</p><pre>dotnet add package Serilog.AspNetCore<br>dotnet add package Serilog.Sinks.Console<br>dotnet add package Serilog.Sinks.Seq<br>dotnet add package Serilog.Enrichers.Environment<br>dotnet add package Serilog.Enrichers.Thread</pre><h3>Paket Açıklamaları</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*Xm14UeALcfqVABJg7qxp7w.png" /></figure><h3>ASP.NET Core Uygulamasında Serilog Konfigürasyonu</h3><p>Sadece uygulamanızda Program.cs içerisinde aşağıdaki configleri eklemelisiniz.</p><pre>builder.Host.UseSerilog((context, loggerConfig) =&gt; loggerConfig.ReadFrom.Configuration(context.Configuration));<br>.<br>.<br>.<br><br>app.UseSerilogRequestLogging();</pre><h3>Endpointler ve kullanımları</h3><p>Serilog’u kullanarak çeşitli loglama seviyelerinde nasıl log yazabileceğinize dair örnekler:</p><pre>app.MapGet(&quot;/information&quot;, (ILogger&lt;Program&gt; logger) =&gt; {<br>    logger.LogInformation(&quot;/information endpoint&#39;i çağrıldı&quot;);<br>    return &quot;Information log message created&quot;;<br>});<br><br>// Yeni warning endpoint&#39;i<br>app.MapGet(&quot;/warning&quot;, (ILogger&lt;Program&gt; logger) =&gt; {<br>    logger.LogWarning(&quot;/warning endpoint&#39;i çağrıldı&quot;);<br>    return &quot;Warning log message created&quot;;<br>});<br><br>// Yeni error endpoint&#39;i<br>app.MapGet(&quot;/error&quot;, (ILogger&lt;Program&gt; logger) =&gt; {<br>    logger.LogError(&quot;/error endpoint&#39;i çağrıldı&quot;);<br>    return &quot;Error log message created&quot;;<br>});</pre><h3>Appsettings ayarlama</h3><pre>  &quot;Serilog&quot;: {<br>    &quot;Using&quot;: [<br>      &quot;Serilog.Sinks.Console&quot;,<br>      &quot;Serilog.Sinks.Seq&quot;<br>    ],<br>    &quot;MinimumLevel&quot;: {<br>      &quot;Default&quot;: &quot;Information&quot;,<br>      &quot;Override&quot;: {<br>        &quot;Microsoft&quot;: &quot;Information&quot;<br>      }<br>    },<br>    &quot;WriteTo&quot;: [<br>      { &quot;Name&quot;: &quot;Console&quot; },<br>      {<br>        &quot;Name&quot;: &quot;Seq&quot;,<br>        &quot;Args&quot;: { &quot;serverUrl&quot;: &quot;http://observability-seq:5341&quot; }<br>      }<br>    ],<br>    &quot;Enrich&quot;: [ &quot;FromLogContext&quot;, &quot;WithMachineName&quot;, &quot;WithThreadId&quot; ],<br>    &quot;Properties&quot;: {<br>      &quot;Application&quot;: &quot;Observability.Api&quot;<br>    }<br>  }</pre><h3>Docker ile Seq Kurulumu</h3><p>En hızlı kurulum yöntemi Docker kullanmaktır:</p><pre>docker run --name seq -d --restart unless-stopped -e ACCEPT_EULA=Y -p 5341:5341 -p 5342:80 datalust/seq:latest</pre><p>Dilerseniz compose dosyanıza da ekleyebilirsiniz</p><pre>  observability-seq:<br>    image: datalust/seq:latest<br>    container_name: observability-seq<br>    ports:<br>      - &quot;9179:5341&quot;<br>      - &quot;9180:80&quot;<br>    environment:<br>      - ACCEPT_EULA=Y <br>    volumes:<br>      - seq-data:/data<br>    networks:<br>      - observability-example-network</pre><h3>Seq’i Kullanmaya Başlama</h3><p>Kurulum tamamlandıktan sonra, tarayıcınızda http://localhost:9180 adresine giderek Seq arayüzüne erişebilirsiniz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-9Wnr8IZLMmZRCsY.png" /></figure><h3>Seq’te Sorgu Örnekleri</h3><p>Seq’in güçlü sorgu yeteneklerinin birkaç örneği:</p><pre>// Hata loglarını bulmak<br>@Level = &#39;Error&#39;<br><br>// Belirli bir kullanıcının işlemlerini bulmak<br>UserId = &#39;user@example.com&#39;<br><br>// Belirli bir süre içinde gerçekleşen yavaş istekleri bulmak<br>RequestPath like &#39;/api/%&#39; and ElapsedMilliseconds &gt; 500<br><br>// HTTP 500 hatalarını bulmak<br>StatusCode = 500</pre><h3>Sonuç</h3><p>Serilog ve Seq, .NET uygulamalarınızda yapılandırılmış loglama ve log analizi için güçlü bir kombinasyon sunar. Yapılandırılmış loglar, uygulama sorunlarını daha hızlı tanımlamanızı ve çözmenizi sağlar. Seq gibi bir görselleştirme ve analiz aracı ise, bu verileri anlamlandırmayı ve proaktif bir şekilde izlemeyi kolaylaştırır.</p><p>Bu teknolojileri kullanarak, uygulamanızın davranışını daha iyi anlayabilir, performans sorunlarını erken tespit edebilir ve kullanıcı deneyimini iyileştirebilirsiniz.</p><p><strong>Github:</strong> <a href="https://github.com/gyildirimm/observability-example">Serilog &amp; Seq Article Example</a></p><p><strong>Blog:</strong> <a href="https://goktugyildirim.com/serilog-ve-seq-ile-net-uygulamalarinda-yapilandirilmis-loglama/">Serilog &amp; Seq</a></p><h3>Kaynaklar</h3><ul><li><a href="https://serilog.net/">Serilog Resmi Web Sitesi</a></li><li><a href="https://datalust.co/seq">Seq Resmi Web Sitesi</a></li><li><a href="https://github.com/serilog/serilog">Serilog GitHub Repository</a></li><li><a href="https://docs.datalust.co/docs">Seq Dokümantasyon</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24339311566a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[.NET Aspire Nedir? Nasıl kullanılır?]]></title>
            <link>https://medium.com/@goktugyildirim/net-aspire-nedir-nas%C4%B1l-kullan%C4%B1l%C4%B1r-7c04b7f6f191?source=rss-cf49de83691a------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c04b7f6f191</guid>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[aspire]]></category>
            <category><![CDATA[net-core]]></category>
            <dc:creator><![CDATA[Göktuğ Yıldırım]]></dc:creator>
            <pubDate>Mon, 03 Feb 2025 20:43:08 GMT</pubDate>
            <atom:updated>2025-02-03T20:46:19.655Z</atom:updated>
            <content:encoded><![CDATA[<p>.NET Aspire, bulut tabanlı modern uygulamaların geliştirilmesini ve yönetilmesini kolaylaştıran bir orkestrasyon aracıdır. .NET ekosistemindeki mikroservis tabanlı mimarileri daha yönetilebilir ve ölçeklenebilir hale getirmek için geliştirilmiştir.</p><h3>Aspire Host Nedir?</h3><p>Aspire Host, uygulamalarınızı çalıştırmak, yapılandırmak ve yönetmek için kullanılan bir ana bileşendir. Uygulama içindeki servislerin birbirleriyle nasıl iletişim kuracağını belirler ve dış bağımlılıkları (Redis, PostgreSQL gibi) yönetir.</p><h3>Avantajları</h3><ul><li>Kolay Orkestrasyon: Mikroservislerin yönetilmesini ve birbirleriyle haberleşmesini kolaylaştırır.</li><li>Entegre Servis Yönetimi: Veritabanları, önbellekleme servisleri gibi bağımlılıkları Aspire içinden yönetebilirsiniz.</li><li>Kolay Geliştirme ve Debug Desteği: .NET ortamında geliştirme sürecini hızlandırır.</li><li>Konfigürasyon Kolaylığı: YAML ve C# kodlarıyla yapılandırılabilir.</li></ul><h4><strong>Örnek</strong></h4><p>Bu örnekte, .NET Aspire kullanarak bir Web API uygulamasını PostgreSQL ile ayağa kaldıracağız. Aspire, bu servisleri yönetecek ve bağlantılarını düzenleyecek.</p><h3>Aspire Uygulaması Nasıl Tanımlanır?</h3><pre>var builder = DistributedApplication.CreateBuilder(args);<br><br>builder.Services.AddLogging(logging =&gt;<br>{<br>    logging.ClearProviders();<br>    logging.AddConsole(); // Konsola loglama ekle<br>});<br><br>var configuration = builder.Configuration;<br>var postgresConfig = configuration.GetSection(&quot;Postgres&quot;);<br><br>var username = builder.AddParameter(&quot;postgresuser&quot;, secret: true);<br>var password = builder.AddParameter(&quot;postgrespassword&quot;, secret: true);<br><br>var postgresServer = builder.AddPostgres(<br>    name: &quot;postgres-server&quot;,<br>    userName: username,<br>    password: password,<br>    port: 5432<br>).WithHealthCheck();<br><br>var postgreAdmin = postgresServer<br>                        .WithPgAdmin(c =&gt; c.WithHostPort(5050)<br>                        .WaitFor(dependency: postgresServer));<br><br><br>var postgresProductDb = postgresServer.AddDatabase(&quot;pDb&quot;, databaseName: &quot;ProductDb&quot;);<br><br>builder.AddProject&lt;Projects.ExampleWebAPI&gt;(&quot;examplewebapi&quot;)<br>    .WithReference(postgresProductDb)<br>    .WithEnvironment(&quot;ConnectionStrings__DefaultConnection&quot;, builder.Configuration.GetConnectionString(&quot;DefaultConnection&quot;))<br>    .WaitFor(dependency: postgresServer);<br><br>builder. Build().Run();</pre><h3>Docker compose üzerinde AppHost’u kullanmak istersek ne yapmalıyız?</h3><ul><li>Aspirate (Aspir8): YAML dosyasını generate etmek için kullanılan bir tool. AppHost dosyanızda çalıştırdığınız zaman Program.cs içerisinde yapmış olduğunuz konfigürasyonları YAML dosyası haline getirip derler.<br>Github link: <a href="https://github.com/prom3theu5/aspirational-manifests">Aspirate</a></li><li>Docker Compose: Projenizde mevcut bir docker compose dosyanız varsa bu kısmı bozmak istemezseniz aşağıdaki gibi ekleyebilirsiniz.</li></ul><pre>version: &#39;3.9&#39;<br><br>networks:<br>  aspire-network:<br>    driver: bridge<br><br>services:<br>  aspire-dashboard:<br>    image: mcr.microsoft.com/dotnet/aspire-dashboard:9.0<br>    container_name: aspire-dashboard<br>    environment:<br>        DOTNET_DASHBOARD_UNSECURED_ALLOW_ANONYMOUS: &quot;true&quot;<br>    ports:<br>      - &quot;18888:18888&quot;<br>      - &quot;4317:18889&quot;<br>    networks:<br>      - aspire-network<br>    depends_on:<br>      - postgres<br>      - redis<br>      - rabbitmq<br><br>  examplewebapi:<br>    image: ${DOCKER_REGISTRY-}examplewebapi<br>    build:<br>      context: .<br>      dockerfile: ExampleWebAPI/Dockerfile<br>    environment:<br>      - ASPNETCORE_ENVIRONMENT=Development<br>      - OTEL_DOTNET_EXPERIMENTAL_OTLP_EMIT_EXCEPTION_LOG_ATTRIBUTES=true<br>      - OTEL_DOTNET_EXPERIMENTAL_OTLP_EMIT_EVENT_LOG_ATTRIBUTES=true<br>      - OTEL_DOTNET_EXPERIMENTAL_OTLP_RETRY_ENABLED=true<br>      - ASPNETCORE_FORWARDEDHEADERS_ENABLED=true<br>      - HTTP_PORTS=5000<br>      - OTEL_EXPORTER_OTLP_ENDPOINT=http://aspire-dashboard:18889<br>      - OTEL_SERVICE_NAME=example-webapi<br>      - ConnectionStrings__DefaultConnection=Host=postgres;Database=ProductDb;Username=postgres;Password=postgrespassword<br>    ports:<br>      - &quot;5000:5000&quot;<br>    networks:<br>      - aspire-network<br>    depends_on:<br>      - aspire-dashboard</pre><h3>Sonuç</h3><p>.NET Aspire, modern .NET uygulamalarını kolayca yönetmek ve dağıtmak için güçlü bir çözümdür. Bu örnek, temel bir Aspire projesinin nasıl oluşturulacağını ve bağımlılıkların nasıl yönetileceğini göstermektedir. Daha ileri seviye senaryolarda, Kubernetes ve Docker Compose entegrasyonlarıyla ölçeklenebilir mimariler tasarlamak mümkündür.</p><h4>NOT: Instrumentation özellikleri kullanılarak trace’ler detaylandırılabilir!!!</h4><p><strong>Aspire Dashboard</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*besspLRPPCEXMGFwWLDaYw.png" /></figure><p><strong>Traces</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A1m01qtWZsWxCSlLMOe1nA.png" /></figure><p>Github: <a href="https://github.com/gyildirimm/aspire-article-example">Aspire Example</a><br>Blog: <a href="https://goktugyildirim.com/net-aspire-nedir-nasil-kullanilir/">Aspire Article</a></p><h3>Kaynakça</h3><ul><li>Gençay Yıldız: <a href="https://www.gencayyildiz.com/blog/net-aspire-nedir-nasil-kullanilir-detaylica-inceleyelim/">https://www.gencayyildiz.com/blog/net-aspire-nedir-nasil-kullanilir-detaylica-inceleyelim/</a></li><li>Aspirate: <a href="https://github.com/prom3theu5/aspirational-manifests">https://github.com/prom3theu5/aspirational-manifests</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c04b7f6f191" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Server-Sent Events (SSE) Nedir?]]></title>
            <link>https://medium.com/@goktugyildirim/server-sent-events-sse-nedir-2bd4ba428259?source=rss-cf49de83691a------2</link>
            <guid isPermaLink="false">https://medium.com/p/2bd4ba428259</guid>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[net-core]]></category>
            <category><![CDATA[server-sent-events]]></category>
            <dc:creator><![CDATA[Göktuğ Yıldırım]]></dc:creator>
            <pubDate>Tue, 14 Jan 2025 22:01:48 GMT</pubDate>
            <atom:updated>2025-01-14T22:01:48.707Z</atom:updated>
            <content:encoded><![CDATA[<p>Server-Sent Events (SSE), HTTP üzerinden sunucudan istemciye sürekli veri akışı sağlayan bir teknolojidir. İstemci, sunucudan gelen verileri gerçek zamanlı olarak alabilir. Bu, özellikle canlı bildirimler, durum güncellemeleri, canlı skorlar gibi uygulamalar için kullanışlıdır.</p><p>SSE, HTTP protokolüne dayalıdır ve iletişim formatı olarak text/event-stream kullanır. Tarayıcılar yerleşik olarak SSE’yi destekler ve istemci tarafında JavaScript kullanılarak kolayca kullanılabilir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9nYfYkYFUZph2JuZ9ayrOQ.jpeg" /></figure><h3>Server-Sent Events ve WebSocket’in Farkları</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*EF1GjyHzBU2w511tHzHBIg.png" /></figure><h3>SSE’nin Avantajları</h3><ol><li><strong>Basitlik: </strong>HTTP protokolü üzerine kurulu olduğundan uygulaması kolaydır.</li><li><strong>Yerleşik Destek:</strong> Modern tarayıcılar tarafından doğrudan desteklenir.</li><li><strong>Otomatik Yeniden Bağlantı:</strong> İstemci bağlantısı kesilirse tarayıcı otomatik olarak yeniden bağlanmaya çalışır.</li><li><strong>Hafiflik:</strong> Tek yönlü iletişim gerektiğinde daha az kaynak tüketir.</li><li><strong>HTTP Tabanlı Çalışma:</strong> Proxy’ler ve güvenlik duvarları ile uyumludur.</li></ol><h3>Server-Sent Events (SSE) ile Notification Örneği</h3><p>Bu proje, Server-Sent Events (SSE) kullanılarak kullanıcıya özel bildirimlerin gerçek zamanlı olarak sunulmasını sağlamaktadır. Bildirimler bir In-Memory Database üzerinde saklanır ve istemciler UserId‘ye göre bildirim akışını dinleyebilir.</p><p><strong>Not: </strong>Projenizi genişletmek için JWT tabanlı kimlik doğrulama ekleyebilir veya daha kalıcı bir veritabanı (örneğin, PostgreSQL) kullanabilirsiniz.</p><h3>Code Structure</h3><p>1-) Notification Sınıfı</p><pre>public class Notification<br>{<br>    public int Id { get; set; }<br>    public string Message { get; set; }<br>    public string UserId { get; set; }<br>    public DateTime CreatedAt { get; set; }<br>}</pre><p>2-) NotificationDbContext</p><pre>public class NotificationDbContext : DbContext<br>{<br>    public NotificationDbContext(DbContextOptions&lt;NotificationDbContext&gt; options) : base(options) { }<br> <br>    // Bildirimlerin saklanacağı veri tablosu<br>    public DbSet&lt;Notification&gt; Notifications { get; set; }<br>}</pre><p>3-) Program.cs</p><pre>var builder = WebApplication.CreateBuilder(args);<br> <br>// In-Memory Database&#39;i ekle<br>builder.Services.AddDbContext&lt;NotificationDbContext&gt;(options =&gt;<br>    options.UseInMemoryDatabase(&quot;Notifications&quot;));<br> <br>var app = builder.Build();<br> <br>// Bildirim ekleme endpoint&#39;i<br>app.MapPost(&quot;/notifications&quot;, async (NotificationDbContext db, Notification notification) =&gt;<br>{<br>    notification.CreatedAt = DateTime.UtcNow;<br>    db.Notifications.Add(notification);<br>    await db.SaveChangesAsync();<br>    return Results.Created($&quot;/notifications/{notification.Id}&quot;, notification);<br>});<br> <br>// SSE ile kullanıcıya özel bildirimleri yayınlama endpoint&#39;i<br>app.MapGet(&quot;/notifications/stream/{userId}&quot;, async (HttpContext context, NotificationDbContext db, string userId) =&gt;<br>{<br>    context.Response.Headers.Add(&quot;Content-Type&quot;, &quot;text/event-stream&quot;);<br> <br>    var lastNotificationId = 0;<br> <br>    while (!context.RequestAborted.IsCancellationRequested)<br>    {<br>        var newNotifications = await db.Notifications<br>            .Where(n =&gt; n.UserId == userId &amp;&amp; n.Id &gt; lastNotificationId)<br>            .ToListAsync();<br> <br>        if (newNotifications.Any())<br>        {<br>            foreach (var notification in newNotifications)<br>            {<br>                await context.Response.WriteAsync(<br>                    $&quot;data: {System.Text.Json.JsonSerializer.Serialize(notification)}\n\n&quot;);<br>                await context.Response.Body.FlushAsync();<br>                lastNotificationId = notification.Id;<br>            }<br>        }<br> <br>        await Task.Delay(1000); // 1 saniye bekle<br>    }<br>});<br> <br>app.Run();</pre><h3>Kullanım</h3><p>1-) Bildirim Ekleme (POST /notifications)</p><pre>POST http://localhost:5000/notifications<br>Content-Type: application/json<br> <br>{<br>    &quot;message&quot;: &quot;Yeni bir bildirim var!&quot;,<br>    &quot;userId&quot;: &quot;1998&quot;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1v6v_veSgGT3fSpc6Lu0qA.png" /></figure><p>2. Servis Nasıl Çağrılır? (GET /notifications/stream/{userId})</p><pre>curl http://localhost:5000/notifications/stream/1998</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GQ5pihVAmThAaqYWZ_4ZGQ.gif" /></figure><p>Blog: <a href="https://goktugyildirim.com/server-sent-events-sse-nedir/">https://goktugyildirim.com/server-sent-events-sse-nedir/</a></p><p>Github: <a href="https://github.com/gyildirimm/server-sent-events">https://github.com/gyildirimm/server-sent-events</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2bd4ba428259" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Template Design Pattern — C#]]></title>
            <link>https://medium.com/@goktugyildirim/template-design-pattern-c-9a6a6dcf28ef?source=rss-cf49de83691a------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a6a6dcf28ef</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[net-core]]></category>
            <category><![CDATA[template-design-pattern]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <dc:creator><![CDATA[Göktuğ Yıldırım]]></dc:creator>
            <pubDate>Sat, 11 Jan 2025 13:43:14 GMT</pubDate>
            <atom:updated>2025-01-11T13:43:14.578Z</atom:updated>
            <content:encoded><![CDATA[<h3>Template Design Pattern — C#</h3><p>Template Design Pattern, bir algoritmanın ana yapısını (iskeletini) tanımlayan ve belirli adımların alt sınıflar tarafından özelleştirilmesine olanak tanıyan bir davranışsal (behavioral) tasarım desenidir.<br>Bu desen, algoritmanın ortak adımlarını üst sınıfta tanımlar ve özelleştirilmesi gereken adımları alt sınıflara bırakır.</p><p>Bu örnekte, farklı veri kaynaklarından (Configuration Dosyası ve Veritabanı) veri okuma işlemini Template Design Pattern ile ele alıyoruz.</p><h3><strong>UML Diagram</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*eX6u2lbzmHOJ7n6_k6cvig.jpeg" /></figure><h3>Template Design Pattern Avantajları</h3><ul><li><strong>Esneklik: </strong>Alt sınıflar, şablonun belirli adımlarını özelleştirerek farklı davranışlar sağlayabilir. Bu, aynı algoritmanın farklı varyasyonlarını kolayca oluşturmayı mümkün kılar.</li><li><strong>Kod Tekrarını Azaltır: </strong>Ortak işlemler üst sınıfta bir kez tanımlandığı için aynı işlemi farklı şekillerde uygulayan sınıflar arasında kod tekrarını önler.</li><li><strong>Kolay Genişletilebilirlik: </strong>Yeni bir davranış eklemek gerektiğinde, mevcut üst sınıfı değiştirmeden yeni bir alt sınıf eklenebilir. Bu, yazılımın genişletilmesini daha kolay ve güvenli hale getirir.</li><li><strong>Algoritmanın İskeleti Korunur:</strong> Algoritmanın genel yapısı üst sınıfta sabit tutulur, böylece alt sınıflar yalnızca gerekli adımları özelleştirir. Bu, algoritmanın tutarlılığını ve güvenilirliğini sağlar.</li><li><strong>Bakım Kolaylığı:</strong> Algoritmanın genel işleyişi merkezi bir yerde tanımlandığından, yapılan değişiklikler tüm alt sınıflara otomatik olarak yansır. Bu, bakım sürecini hızlandırır ve hata riskini azaltır.</li></ul><h3>Code Structure</h3><ul><li>DataReader: Abstract sınıf. Veri okuma işleminin ana iskeletini tanımlar (ReadData() metodu). Alt sınıfların Connect() ve FetchData() metodlarını uygulaması beklenir.</li><li>ConfigFileReader: Configuration dosyasından veri okumayı gerçekleştiren sınıf.</li><li>DatabaseReader: Veritabanından veri okumayı gerçekleştiren sınıf.</li></ul><h3>1-) DataReader</h3><pre>public abstract class DataReader<br>{<br>    public void ReadData()<br>    {<br>        Connect();<br>        FetchData();<br>        Disconnect();<br>    }<br>     <br>    protected abstract void Connect();<br>    protected abstract void FetchData();<br>     <br>    protected virtual void Disconnect()<br>    {<br>        Console.WriteLine(&quot;Bağlantı kapatıldı.&quot;);<br>    }<br>}</pre><h3>2-) Concrete</h3><pre>public class ConfigFileReader : DataReader<br>{<br>    protected override void Connect()<br>    {<br>        Console.WriteLine(&quot;Configuration dosyasına bağlanılıyor...&quot;);<br>    }<br> <br>    protected override void FetchData()<br>    {<br>        Console.WriteLine(&quot;Configuration dosyasından veri okundu: &#39;AppSettings:ApiKey=12345&#39;&quot;);<br>    }<br>}</pre><pre>public class DatabaseReader : DataReader<br>{<br>    protected override void Connect()<br>    {<br>        Console.WriteLine(&quot;Veritabanına bağlanılıyor...&quot;);<br>    }<br> <br>    protected override void FetchData()<br>    {<br>        Console.WriteLine(&quot;Veritabanından veri okundu: &#39;SELECT * FROM Users&#39;&quot;);<br>    }<br> <br>    // Veritabanı özel bir kapatma işlemi gerektiriyor<br>    protected override void Disconnect()<br>    {<br>        Console.WriteLine(&quot;Veritabanı bağlantısı güvenli bir şekilde kapatıldı.&quot;);<br>    }<br>}</pre><h3>Uygulama ve Sonuç</h3><pre>Console.WriteLine(&quot;Configuration Dosyasından Veri Okuma:&quot;);<br>DataReader configReader = new ConfigFileReader();<br>configReader.ReadData();<br> <br>Console.WriteLine(&quot;\nVeritabanından Veri Okuma:&quot;);<br>DataReader dbReader = new DatabaseReader();<br>dbReader.ReadData();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lCNnEv3Sw4_GJChYGwbH1Q.png" /></figure><p>Blog: <a href="https://goktugyildirim.com/template-design-pattern-c-sharp/">https://goktugyildirim.com/template-design-pattern-c-sharp/</a><br>Github: <a href="https://github.com/gyildirimm/design-patterns/blob/master/Behavioral/TemplateDesignPattern">https://github.com/gyildirimm/design-patterns/blob/master/Behavioral/TemplateDesignPattern</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a6a6dcf28ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Strategy Design Pattern — C#]]></title>
            <link>https://medium.com/@goktugyildirim/strategy-design-pattern-c-a6efbaec405d?source=rss-cf49de83691a------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6efbaec405d</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[net-core]]></category>
            <category><![CDATA[strategy-pattern]]></category>
            <dc:creator><![CDATA[Göktuğ Yıldırım]]></dc:creator>
            <pubDate>Sat, 04 Jan 2025 20:48:02 GMT</pubDate>
            <atom:updated>2025-01-05T11:12:06.884Z</atom:updated>
            <content:encoded><![CDATA[<h3>Strategy Design Pattern — C#</h3><p>Strategy Design Pattern, davranışsal (behavioral) tasarım desenlerinden biridir ve bir nesnenin algoritmasını çalışma zamanında (runtime) değiştirmeyi sağlar. Bu desen, algoritmaları birbirinden bağımsız olarak tanımlar ve birbirlerinin yerine kullanılabilecek şekilde tasarlar. Bu sayede kodun esnekliği ve yeniden kullanılabilirliği artar.</p><p>Bu tasarım desenini bir ödeme sisteminde kullandığımızı hayal edelim. Sistem içerisinde herhangi bir ödeme yöntemi seçtiğimizde, birden fazla ödeme seçeneği ile karşı karşıya kalıyoruz. Peki, bu durumda arka planda yani çalışma zamanı (runtime) sırasında seçilen ödeme yöntemine göre kodumuzu nasıl şekillendirebiliriz?</p><h3>UML Diagram</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*xZKPcC53r5vB_GkTNSKDGQ.jpeg" /></figure><h3>Strategy Design Pattern Avantajları</h3><ul><li>Esneklik: Mevcut kodu değiştirmeden kolayca yeni ödeme yöntemleri eklenebilir.</li><li>Ölçeklenebilirlik: Yeni stratejileri zahmetsizce destekleyen genişletilebilir bir yapıdır.</li><li>Bakım Kolaylığı: Her ödeme yöntemi izole edilmiştir, bu da minimum bağımlılık sağlar.</li></ul><h3>Code Structure</h3><ul><li>IPaymentStrategy: Ödeme yapma işleminin interface’ini tanımlar.</li><li>Concrete Strategies: Çeşitli ödeme yöntemlerinin uygulanması (CreditCardPayment, PayPalPayment, CryptoPayment).</li><li>ShoppingCart: Farklı ödeme stratejileriyle etkileşime giren Context Class.</li></ul><h3>1-) Strategy Arayüz</h3><pre>public interface IPaymentStrategy<br>{<br>    public void Pay(decimal amount);<br>}</pre><h3>2-) Concrete Strategy</h3><pre>public class CreditCardPayment : IPaymentStrategy<br>{<br>    public void Pay(decimal amount)<br>    {<br>        Console.WriteLine($&quot;Kredi Kartı ile {amount} TL ödendi.&quot;);<br>    }<br>}<br> <br>public class PayPalPayment : IPaymentStrategy<br>{<br>    public void Pay(decimal amount)<br>    {<br>        Console.WriteLine($&quot;PayPal üzerinden {amount} TL ödendi.&quot;);<br>    }<br>}<br> <br>public class CryptoPayment : IPaymentStrategy<br>{<br>    public void Pay(decimal amount)<br>    {<br>        Console.WriteLine($&quot;Kripto Para ile {amount} TL ödendi.&quot;);<br>    }<br>}</pre><h3>3-) Context Class</h3><pre>public class ShoppingCart<br>{<br>    private IPaymentStrategy _paymentStrategy;<br>     <br>    public void SetPaymentStrategy(IPaymentStrategy paymentStrategy)<br>    {<br>        _paymentStrategy = paymentStrategy;<br>    }<br>     <br>    public void Checkout(decimal totalAmount)<br>    {<br>        if (_paymentStrategy is null)<br>        {<br>            Console.WriteLine(&quot;Lütfen bir ödeme yöntemi seçiniz!&quot;);<br>        }<br>        else<br>        {<br>            _paymentStrategy.Pay(totalAmount);<br>        }<br>    }<br>}</pre><h3>Uygulama ve Sonuç</h3><pre>var cart = new ShoppingCart();<br>decimal totalAmount = 1500m;<br> <br>Console.WriteLine(&quot;Kredi Kartı Ödeme:&quot;);<br>cart.SetPaymentStrategy(new CreditCardPayment());<br>cart.Checkout(totalAmount);<br> <br>Console.WriteLine(&quot;\nPayPal ile Ödeme:&quot;);<br>cart.SetPaymentStrategy(new PayPalPayment());<br>cart.Checkout(totalAmount);<br> <br>Console.WriteLine(&quot;\nKripto Para ile Ödeme:&quot;);<br>cart.SetPaymentStrategy(new CryptoPayment());<br>cart.Checkout(totalAmount);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*Es7LopyEhPdrqKaeGvoX5w.png" /></figure><p>Blog: <a href="https://goktugyildirim.com/strategy-design-pattern-c-sharp/">https://goktugyildirim.com/strategy-design-pattern-c-sharp/</a><br>Github: <a href="https://github.com/gyildirimm/design-patterns/tree/master/Behavioral/StrategyDesignPattern">https://github.com/gyildirimm/design-patterns/tree/master/Behavioral/StrategyDesignPattern</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6efbaec405d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>