<?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 olmezsude on Medium]]></title>
        <description><![CDATA[Stories by olmezsude on Medium]]></description>
        <link>https://medium.com/@olmezsude?source=rss-e2513e392b3b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*TSUH2sV4Tly6Bc9f9-2HbA.png</url>
            <title>Stories by olmezsude on Medium</title>
            <link>https://medium.com/@olmezsude?source=rss-e2513e392b3b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 16:55:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@olmezsude/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[Testing in .NET #1 — Unit Testing ile Sağlam Temeller Atmak]]></title>
            <link>https://medium.com/@olmezsude/testing-in-net-1-unit-testing-ile-sa%C4%9Flam-temeller-atmak-a376ebec4605?source=rss-e2513e392b3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/a376ebec4605</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[unit-testing]]></category>
            <dc:creator><![CDATA[olmezsude]]></dc:creator>
            <pubDate>Sun, 12 Jul 2026 12:45:18 GMT</pubDate>
            <atom:updated>2026-07-12T12:45:18.802Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yTKqVRYuNLhXsj-VH_OnRw.png" /></figure><h4><strong><em>Test Neden Yazılır?</em></strong></h4><p>Yazılım testinin temel amacı <strong>kodun çalıştığını kanıtlamak değil</strong>, yazılımın beklenen davranışı koruduğuna güven sağlamaktır. Bu yaklaşımla birlikte yazılan kodun request ve response sağlamlığını, güvenilirliğini sağlamak adına test yazmak gerekmektedir. Daha iyi bir deyişle şu şekilde özetlenebilir:</p><p><em>“Bu kodun bugün doğru çalıştığını ve yarın yapılacak değişikliklerden sonra bozulmadığını nasıl garanti ederim?”</em></p><p>Testin ana amacı budur.</p><p>Yazılım testinin temel amacı, yazdığımız kodun sadece bugün çalıştığını değil, gelecekte yapılacak değişikliklerden sonra da beklenen davranışı koruduğunu garanti etmektir. Bir geliştirici yeni bir özellik eklediğinde veya mevcut kodu refactor ettiğinde, eski çalışan özelliklerin bozulup bozulmadığını manuel olarak kontrol etmek hem zaman kaybettirir hem de hata yapma riskini artırır. Testler burada devreye girerek bize hızlı geri bildirim sağlar ve kod değişikliklerini daha güvenli hale getirir.</p><p>Örneğin bir e-ticaret uygulamasında sipariş oluşturma işlemi ilk başta basit olabilir ancak zamanla indirim, kampanya, stok kontrolü, ödeme ve bildirim gibi yeni kurallar eklendiğinde mevcut davranışların bozulma ihtimali artar; yazılan testler bu eski davranışların korunmasını sağlar.</p><p>Testler aynı zamanda refactoring yaparken geliştiriciye güven verir, çünkü kodun iç yapısını değiştirdiğinde dışarıdan beklenen davranışların aynı kaldığını kontrol edebilir. Bunun yanında iyi yazılmış testler yaşayan bir dokümantasyon görevi görür; örneğin CreateOrder_Should_Fail_When_Stock_Is_Not_Enough isimli bir test, sistemin yetersiz stok durumunda sipariş oluşturmadığını açıkça ifade eder ve yeni geliştiricilerin sistemi daha hızlı anlamasına yardımcı olur.</p><p>Test yazmak aynı zamanda yazılım tasarımının kalitesini de artırır, çünkü kolay test edilebilen kod genellikle düşük bağımlılığa sahip, sorumlulukları ayrılmış ve daha temiz tasarlanmış koddur. Örneğin bir servis içinde doğrudan veritabanı bağlantısı açmak, mail göndermek ve ödeme yapmak gibi birçok sorumluluğu toplamak test yazmayı zorlaştırırken, bu bağımlılıkları interface&#39;ler aracılığıyla dışarıdan almak sistemi daha esnek ve test edilebilir hale getirir. Kısacası test yazmak, sadece hata bulma yöntemi değil; yazılımın güvenli şekilde gelişmesini, kolay değiştirilebilir olmasını ve ekip içinde daha anlaşılır hale gelmesini sağlayan bir mühendislik pratiğidir.</p><p><strong><em>1.2. Testing Pyramid</em></strong></p><p><strong>Testing Pyramid (Test Piramidi)</strong>, bir yazılım projesinde hangi tür testlerden ne kadar yazmamız gerektiğini gösteren bir test stratejisidir. İlk olarak Mike Cohn tarafından ortaya atılan bu yaklaşımın temel fikri şudur: <strong>Bir projede en fazla hızlı ve düşük maliyetli testler (Unit Test), daha az sayıda ise yavaş ve maliyetli testler (Integration, UI/E2E Test) bulunmalıdır.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*2daGK0jcQMJrsMwqNb0v0A.png" /></figure><p>Biz bu yazımızda, en çok yazılan, hızlı ve daha az maliyetli bir yaklaşım olan unit test üzerine konuşuyor olacağız.</p><h3><strong>Unit Test</strong></h3><p>Unit test, uygulamadaki <strong>en küçük test edilebilir parçayı</strong> izole şekilde test eder. Genellikle bir class, method veya business kuralı test edilir. Çok hızlı çalışır çünkü herhangi bir database’e gitmez, network kullanmaz veya bir dosya işlemi yapmaz. Amacımız burada, yazmış olduğumuz kodun, doğru bir request ile uygun bir response veriyor mu, kod üzerinde yapmış olduğumuz bir değişiklik ile herhangi bir bozulma yaşanmış mı şeklinde sorulara cevap verebilmektir. Unit Test yazımında dikkat edilen hususlar vardır.</p><p><strong><em>AAA Pattern Nedir?</em></strong></p><p>Test yazımını standartlaştıran, okunabilirliğini arttıran bir tasarım desenidir. 3 adımdan oluşur.</p><ul><li><strong>Arrange (Düzenle):</strong> Testin çalışması için gerekli ortamı hazırlar, değişkenleri tanımlar ve test edilecek nesneleri oluşturur.</li><li><strong>Act (Harekete Geç):</strong> Test edilecek fonksiyonu veya metodu çalıştırır.</li><li><strong>Assert (Doğrula):</strong> Beklenen sonuç ile elde edilen sonucun uyuşup uyuşmadığını kontrol eder.</li></ul><p>Test yazımından önce, örnek olması adına ShopHub adında basic bir solution oluşturdum. Burada önce testler olmak üzere, sırasıyla önemli yapıları test edip, kapsamlı bir repo oluşturuyor olacağız.</p><p>Unit test ile başlamak adına, basit bir seviyede OrderService.cs dosyası oluşturdum. Burada en basit seviyede sipariş oluşturmak adına bir fonksiyon yer almakta.</p><pre> public async Task&lt;CreateOrderResponse&gt; CreateOrderAsync(<br>        CreateOrderRequest request,<br>        CancellationToken cancellationToken = default)</pre><p>Request ve Response olarak beklenen parametreler belli. Burada, kod içerisinde herhangi bir değişiklik yapıldığında dönüşün değişip değişmediğini test etmek gerekiyor. Bunun için istediğimiz senaryolarda, bu değişikliği kontrol edebilmek için test yazmalıyız. Bu projede yazdığımız örnek senaryolar şu şekilde:</p><pre>  [Fact]<br>    public async Task CreateOrder_Should_Create_Order_When_Request_Is_Valid()<br>...<br>  [Fact]<br>    public async Task CreateOrder_Should_Throw_When_Product_Not_Found()<br>...</pre><p>Test sınıfının yazılması için test edilmek istenen sınıfların mock’lanması gerekmektedir. O yüzden şu şekilde bir girizgah yapılmalıdır:</p><pre>public class OrderServiceTests<br>{<br>    private readonly Mock&lt;IOrderRepository&gt; _orderRepositoryMock;<br>    private readonly Mock&lt;IProductRepository&gt; _productRepositoryMock;<br>    private readonly OrderService _sut;<br><br>    public OrderServiceTests()<br>    {<br>        _orderRepositoryMock = new Mock&lt;IOrderRepository&gt;();<br>        _productRepositoryMock = new Mock&lt;IProductRepository&gt;();<br>        _sut = new OrderService(_orderRepositoryMock.Object, _productRepositoryMock.Object);<br>    }...</pre><p>Request in düzgün olması halinde düzgün bir siparişin oluşturulması için çalışacak test ise şu şekilde yazılabilir:</p><pre>[Fact]<br>    public async Task CreateOrder_Should_Create_Order_When_Request_Is_Valid()<br>    {<br>        // Arrange<br>        var customerId = Guid.NewGuid();<br>        var productId = Guid.NewGuid();<br>        var product = CreateProduct(productId, price: 25.00m);<br><br>        _productRepositoryMock<br>            .Setup(repository =&gt; repository.GetByIdAsync(productId, It.IsAny&lt;CancellationToken&gt;()))<br>            .ReturnsAsync(product);<br><br>        var request = new CreateOrderRequest(<br>            customerId,<br>            [new CreateOrderItemRequest(productId, 2)]);<br><br>        // Act<br>        var response = await _sut.CreateOrderAsync(request);<br><br>        // Assert<br>        response.Should().NotBeNull();<br>        response.OrderId.Should().NotBeEmpty();<br>        response.CustomerId.Should().Be(customerId);<br>        response.TotalAmount.Should().Be(50.00m);<br>        response.Items.Should().HaveCount(1);<br>        response.Items[0].ProductId.Should().Be(productId);<br>        response.Items[0].Quantity.Should().Be(2);<br>    }</pre><p>IOrderRepository ve IProductRepositoryinterface&#39;leri mock&#39;lanarak test ortamında kontrol edilebilir hale getirilmiştir. _sut değişkeni ise <strong>System Under Test </strong>anlamına gelir ve test edilen ana nesneyi temsil eder; burada tüm testlerin odak noktası OrderService sınıfıdır. Yukarıda da eklemiş olduğum CreateOrder_Should_Create_Order_When_Request_Is_Valid, geçerli bir sipariş isteği gönderildiğinde siparişin başarılı şekilde oluşturulduğunu kontrol eder. Arrange bölümünde gerekli test verileri hazırlanır, ürün repository&#39;sinin belirli bir ürün döndürmesi için Moq ile Setup yapılır, Act bölümünde gerçek metot çağrılır ve Assert bölümünde <strong>FluentAssertions </strong>kullanılarak sonucun beklenen değerlere sahip olup olmadığı doğrulanır. Bu doğrulama XUnit ile de yapılabilir.</p><pre>    [Fact]<br>    public async Task CreateOrder_Should_Throw_When_Product_Not_Found()<br>    {<br>        // Arrange<br>        var productId = Guid.NewGuid();<br><br>        _productRepositoryMock<br>            .Setup(repository =&gt; repository.GetByIdAsync(productId, It.IsAny&lt;CancellationToken&gt;()))<br>            .ReturnsAsync((Product?)null);<br><br>        var request = new CreateOrderRequest(<br>            Guid.NewGuid(),<br>            [new CreateOrderItemRequest(productId, 1)]);<br><br>        // Act<br>        var act = () =&gt; _sut.CreateOrderAsync(request);<br><br>        // Assert<br>        await act.Should().ThrowAsync&lt;NotFoundException&gt;()<br>            .WithMessage($&quot;*{productId}*&quot;);<br>    }</pre><p>Yukarıda bulunan ve ikinci test olan CreateOrder_Should_Throw_When_Product_Not_Found, hata senaryosunu test eder; burada repository ürün bulamadığında nulldönecek şekilde ayarlanır ve servisin doğru exception fırlatıp fırlatmadığı kontrol edilir. Bu testte ThrowAsync kullanılması async çalışan metotlarda hata davranışını doğrulamak için kullanılan bir FluentAssertions özelliğidir.</p><p>Testlerde kullanılan <strong>Arrange-Act-Assert (AAA) pattern</strong>, her testin üç aşamalı okunabilir bir yapıya sahip olmasını sağlar: önce gerekli ortam hazırlanır, sonra test edilen işlem çalıştırılır, son olarak sonuç kontrol edilir. CreateProduct yardımcı metodu ise testlerde sürekli aynı Product nesnesini tekrar oluşturmamak için kullanılan bir test helper metodudur ve testlerin daha okunabilir olmasını sağlar. Genel olarak bu sınıf; xUnit ile test organizasyonu, Moq ile bağımlılıkların taklit edilmesi, FluentAssertions ile okunabilir doğrulamalar yapılması, async exception testleri, interaction testing (Verify) ve business rule testleri gibi modern .NET Unit Testing pratiklerini bir arada göstermektedir. Bu yaklaşım sayesinde OrderService üzerinde yapılacak değişikliklerde, sipariş oluşturma davranışının bozulup bozulmadığı hızlı ve güvenilir şekilde kontrol edilebilir.</p><p>Biz bu testlerimizde, request i kendimiz oluşturduk. Daha büyük projelerde, işimizi kolaylaştırması adına bir kütüphane de kullanılabilmekte. <strong>AutoFixture</strong>, .NET testlerinde kullanılan bir <strong>test data generation (test verisi üretme) kütüphanesidir</strong>. Temel amacı, testlerde ihtiyaç duyduğumuz nesneleri otomatik olarak oluşturmak ve manuel veri hazırlama yükünü azaltmaktır.</p><p>Örneğin, normalde request i şu şekilde oluştururuz,</p><pre>var product = new Product<br>{<br>    Id = Guid.NewGuid(),<br>    Name = &quot;Test Product&quot;,<br>    Price = 25.00m,<br>    StockQuantity = 10,<br>    CreatedAt = DateTime.UtcNow<br>};</pre><p>AutoFixture ile birlikte şu şekilde request’ler kendiliğinden oluşabilmektedir.</p><pre>var fixture = new Fixture();<br>var product = fixture.Create&lt;Product&gt;();</pre><p>Buna ek olarak Bogus ile birlikte kullanılırsa, daha gerçeğe yakın veriler üretilebilmektedir.</p><pre>var faker = new Faker();<br>var name = faker.Name.FullName();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eGAb0DJ6Q_11iX1WvKElpw.png" /></figure><p>Modern yazılım geliştirmede test yazmak sadece hata bulmak için kullanılan bir teknik değildir; aynı zamanda yazılımın sürdürülebilirliğini sağlayan önemli bir mühendislik pratiğidir. İyi yazılmış testler geliştiricilere güven verir, refactoring yapmayı kolaylaştırır ve yeni özelliklerin sisteme daha güvenli şekilde eklenmesini sağlar. Bu yazıda testlerin neden gerekli olduğunu, Testing Pyramid yaklaşımını, Unit Test kavramını, AAA Pattern’i, xUnit ile test oluşturmayı, FluentAssertions ile doğrulama yapmayı, Moq ile bağımlılıkları izole etmeyi, AutoFixture ve Bogus ile test verisi üretmeyi konuşmuş olduk. Bu şekilde, diğer testler ve farklı konular ile de çalışmalar yapıp, github reposunda use case’ler olarak ilerlemeye devam edeceğiz.</p><p>Repoya <a href="https://github.com/sudelmez/ShopHub/tree/main">buradan</a> ulaşabilirsiniz.</p><p>Okuduğunuz için teşekkürler!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a376ebec4605" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fullstack Bir Proje Nasıl Oluşturulur?]]></title>
            <link>https://medium.com/@olmezsude/fullstack-bir-proje-nas%C4%B1l-olu%C5%9Fturulur-af5d23057cf0?source=rss-e2513e392b3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/af5d23057cf0</guid>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[fullstack-development]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[software]]></category>
            <dc:creator><![CDATA[olmezsude]]></dc:creator>
            <pubDate>Thu, 04 Jul 2024 18:08:09 GMT</pubDate>
            <atom:updated>2024-07-04T18:51:40.249Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*VcBgH4FNfEh0RywDYQ93sw.jpeg" /></figure><p>Uzun bir süredir ara ara deneyimlemekte olduğum fakat tam olarak içine derinlemesine girmediğim bir konuydu böyle bir proje, özellikle backend. Yapmakta olduğum stajım sayesinde de bu konu ile fazlasıyla haşır neşir olmuş biri olarak bugün hala öğrenirken sizlere de sıfırdan sona kısa bir fullstack projeyi nasıl yaptığımı aktarmak istedim.</p><p><em>Not: MACOS üzerinde yaptığım için sizin işletim sisteminize göre özellikle komutlarda bazı değişiklikler olabilir.</em></p><p><em>Hazırsanız başlayalım…:)</em></p><p>Öncelikle yapacağımız projenin ana konusunu özetleyeyim;</p><p>Amacımız, basit sigorta işlemlerinin yapıldığı bir frontend ve backend yazmaktır. Kısaca; giriş yapılabilen, ayrıca diğer kişilerin listelendiği, düzenlenebildiği bir sistemdir. Bu yazıda kısaca email ve şifre kontrolü ile sisteme girişi nasıl sağladığımı göstereceğim.</p><blockquote><strong>Peki nelere ihtiyacımız var?</strong></blockquote><ul><li>VsCode kullanıyorsanız .Net ve JavaScript eklentileri</li><li>MongoDB için NoSqlBooster</li><li>(Opsiyonel) projemizi daha da ileri taşımak istiyorsak Azure Data Studio(for MSSQL) <em>, Eğer Mac kullanıyorsanız Docker da indirmelisiniz.</em></li></ul><h3>1) .Net Projemizi Oluşturalım</h3><p>.Net projemizi oluşturmak için Microsoft kaynakları ingilizceniz varsa fazlasıyla yeterli. Buradan da inceleyebilirsiniz. .Net projesi oluşturmanın birden fazla yolu var. Ben aşağıdaki komutun sonuna projemin adını ekleyerek çalıştırdım. Böylelikle SOLID mantığını uygulayabileceğim controller vb. dosyaları içeren basit bir .Net projesi üretilmiş oldu.</p><pre>dotnet new webapi --use-controllers -o {project name}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*cA19pIcGMLDXEaFWzQXgJw.png" /></figure><p>Görüntülendiği üzere yukarıdaki dosyalar oluşturulmuş oldu. Mantığını basit olarak anlatmak gerekirse, Program.cs dosyası projemizin ilk başlatıldığı dosya denebilir. İçinde gerekli konfigürasyonlar yer almaktadır. Bazı geliştiriciler, bu dosyanın yanında bir de Startup.cs dosyasını konfigürasyon için tercih etmektedirler. Siz dilediğiniz gibi tercih edebilirsiniz.</p><p>Controllers dosyası, tüm http isteklerini yönetebileceğimiz bir yapıyı sağlar. Ayrıca Program.cs dosyasının içinde bulunan konfigürasyon olan, &lt;builder.Services.AddSwaggerGen();&gt; komutu ise http isteklerimizi kolaylıkla kontrol edebileceğimiz bir arayüzü bize sağlar.</p><p><em>Şimdi geliştirmeye başlayabiliriz.</em></p><p>Öncelikle kullanıcıya giriş yaptırabilmemiz için bizim bir modelimizin olması lazım. Bu model ile database ve arayüz arasında bolca alışveriş yapacağız. Modelimizi aşağıdaki gibi oluşturalım.</p><pre>public class User<br>{<br>    [BsonRepresentation(BsonType.ObjectId)]<br>    public ObjectId Id { get; set; }<br>    public string UId { get; set; }<br>    public string Name { get; set; }<br>    public string LastName { get; set; }<br>    public string Password { get; set; }<br>    public string Email { get; set; }<br>    public string RoleId { get; set; }<br>}</pre><p>MongoDB ile bağladığımızda, bize otomatik bir Id dönüyor. Bu yüzden bunu otomatik olarak ObjectId olarak kaydediyorum. Aynı zamanda login isteği yapılırken de bu verileri almak için ayrıca bir Login Request sınıfı oluşturuyorum.</p><pre>public class LoginRequest<br>{<br>    public string Email { get; set; }<br>    public string Password { get; set; }<br>    public BsonDocument ToBson(LoginRequest req)<br>}</pre><p>Normal şartlarda, daha karmaşık yapılarda Entity ve Dto lar ile bu alışverişi yapmak daha doğru olacaktır. Onlar da yine yukarıda belirtilen modeller şeklindedir. Böylelikle, repository ile database dosyamızdan verileri alıp, service dosyasında işleyecektir. Biz şu anlık mongoDB ile bağlayacağımız ve fazlasıyla basit işlemler olduğu için Repository oluşturmak yerine, controller ve service dosyalarımızı oluşturuyoruz. Öncelikle aşağıdaki gibi bir controller dosyası oluşturalım.</p><pre>public class AuthController : ControllerBase{<br>    private IMongoDBService _mongoDbService;<br>    private IAuthService _authService;<br>    public AuthController(ILogger&lt;AuthController&gt; logger, IMongoDBService mongoDbService, IAuthService authService)<br>    {<br>        _authService = authService;<br>        _mongoDbService = mongoDbService;<br>    }}</pre><p>İçerisinde instance şeklinde çağırdığımız fonksiyonları kullanacağız. Daha sonra göstereceğim MongoDb service ve AuthService Interface’lerimizi çağırıyoruz. Interface’ler, geliştirme ortamında kod okuma kolaylığı ve SOLID prensipleri açısından fazlasıyla kolaylık sağlıyor.</p><pre>[HttpPost(&quot;login&quot;)]<br>    public async Task&lt;IActionResult?&gt; Login(LoginRequest request)<br>    {<br>        var user = await _authService.Auth(request);<br>        else if (user.Email == request.Email &amp;&amp; user.Password == request.Password)<br>        {<br>            return Ok(new<br>            {user = new<br>                {<br>                    user.Email,<br>                    user.Name,<br>                    user.LastName,<br>                    user.RoleId}});<br>        }<br>        return Unauthorized(&quot;Unmatched email or password.&quot;);}</pre><p>Yukarıdaki kod, mongoDb servisinden aldığı userlar arasında kontrol yaparak eğer doğruysa bize user bilgilerini dönmektedir. IActionResult, controller içerisinde bir istek sonucu oluşan cevabı dönecektir.</p><p>AuthService.cs dosyamız ise aşağıdaki gibi olacaktır.</p><pre>public class AuthService : IAuthService<br>    {<br>        private IMongoDBService _mongoDbService;<br>        public AuthService(IMongoDBService mongoDbService)<br>        {<br>            _mongoDbService = mongoDbService;<br>        }<br>        public async Task&lt;User?&gt; Auth(LoginRequest request)<br>        {<br>            var receivedUser = await _mongoDbService.Auth(request.Email, request.Password);<br>            var user = BsonSerializer.Deserialize&lt;User&gt;(receivedUser);<br>            return user;}<br>    }</pre><p>Burada MongoDb servisinden gelen BsonDocument tipindeki veriyi modelimize uygun bir şekle dönüştürmektedir. Bu sınıfımızın aynı zamanda aşağıdaki gibi bir interfaceini oluşturabiliriz.</p><pre>public interface IAuthService<br>{<br>    Task&lt;AdminModel?&gt; Auth(LoginRequest request);<br>}</pre><p>Şimdi gelelim MongoDb servisimize. Bu servisimizin amacı basit olarak MongoDb ile kolay bir şekilde bağlantı sağlamak olacak.</p><pre>public class MongoDbService : IMongoDBService<br>{<br>    private readonly IMongoCollection&lt;BsonDocument&gt; _collectionAdmins;<br>    public MongoDbService()<br>    {<br>        var connectionString = &quot;mongodb://localhost:27017&quot;;<br>        var client = new MongoClient(connectionString);<br>        var database = client.GetDatabase(&quot;portal&quot;);<br>        _collectionAdmins = database.GetCollection&lt;BsonDocument&gt;(&quot;admins&quot;);<br>    }<br>    public async Task&lt;BsonDocument&gt;? Auth(string email)<br>    {<br>        var filter = Builders&lt;BsonDocument&gt;.Filter.Eq(&quot;Email&quot;, email);<br>        var resUser = await _collectionAdmins.Find(filter).FirstOrDefaultAsync();<br>        if (resUser == null)<br>        {<br>            return null;<br>        }<br>        return resUser;<br>    }<br>}</pre><p>Burada, projede ilk başta bahsettiğim gibi birçok rol olduğu için Admin olarak adlandırılmıştır. BsonDocument türünde veri dönmektedir ve MongoDB ile gerekli kontroller sağlanmıştır. Şu anlık mantığını anlamak için mongoDb kontrollerini kodun içine koyduk. Siz appSettings.json dosyanızda ConnectionStrings olarak da bu verileri tutarsanız daha sağlıklı olacaktır. Eğer bu şekilde erişmek isterseniz, Program.cs dosyanızda bunu tanımlamanız gerekecektir.</p><p>Ayrıca MongoDByi projemizde kullanabilmek için .Net projemize MongoDB driver pakedini indirmemiz gerekiyor.</p><pre>dotnet add package MongoDB.Driver</pre><h3>2) MongoDB</h3><p>Ben MACOS kullandığım için, paket kurmada fazlasıysa işime yarayan brew kullanmaktayım. Bu yüzden aşağıdaki komutlar ile Mongoyu bilgisayarıma kurup başlattım. MongoDB’yi kullanabilmek için NoSQL booster’ı yüklememiz gerekiyor. <a href="https://nosqlbooster.com/">Buradan</a> indirebilirsiniz.</p><pre>brew install mongodb-community@7.0<br>brew services start mongodb-community@7.0</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*we9oMX-Wq7rzoJq0iS8hCQ.png" /></figure><p>localhost servisine giriş yaptıktan sonra yukarıdaki gibi klasörler olacaktır. Burada portal klasörüne sağ tıklayıp Create Collection diyoruz. Daha sonrasında oluşturduğumuz collection’a sağ tıklayıp Insert Documents ile verileri ekleyebileceğimiz bir json sayfası açılacaktır. Buraya aşağıdaki şekilde istediğiniz verileri ekleyebiliyorsunuz. Auth sistemizimiz için collection adımız admins olacaktır.</p><pre>[{<br>    &quot;UId&quot;: &quot;f350771b-eb16-4288-a3a5-e434fed7dbf9&quot;,<br>    &quot;Email&quot;: &quot;john@gmail.com&quot;,<br>    &quot;Name&quot;: &quot;John&quot;,<br>    &quot;Password&quot;: &quot;qwerty&quot;,<br>    &quot;LastName&quot;: &quot;Doe&quot;,<br>    &quot;RoleId&quot;:&quot;1&quot;<br>}]</pre><p>Run komutu ile bu veriyi veritabanımıza direkt olarak ekleyebiliyoruz. Böylelikle backend tarafımızda basit bir auth sistemi kurulmuş oluyor.</p><h3>3) React</h3><p>React arayüzümüzü geliştirmek için Vscode kullanıyorsanız JavaScript eklentisi fazlasıyla lazım olacaktır. Onu kurduktan sonra react projemizi kurmak çok kolay. Birden fazla yöntemi var fakat benim en çok tercih ettiğim yöntem şu şekilde.</p><pre>npx create-react-app@latest {project_name}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*qLN_n6q_gWC0Ay5_ydwJuw.png" /></figure><p>Proje yüklenince ilk dosyalarımız yukarıdaki şekilde olacaktır. src içindeki App.js ve index.js dosyaları bizim projemizi başlatan dosyalardır. Öncelikle sayfalar arası geçişi sağlamak için route paketi indirmemiz gerekiyor. Ben bunun için react-router kullandım. Aşağıdaki komut ile indirebilirsiniz.</p><pre>npm install react-router-dom </pre><p>Router isminde bir dosya oluşturup tüm route işlemlerinizi ve pathlerinizi burada tutabilirsiniz.</p><pre>function RouteService() {<br>  const { loggedIn } = useAuth();<br>  return (<br>    &lt;Router&gt;<br>      &lt;Routes&gt;<br>        {loggedIn === false ? (<br>          &lt;&gt;<br>            &lt;Route path=&quot;/auth&quot; element={&lt;AuthPage /&gt;} /&gt;<br>            &lt;Route path=&quot;/notFound&quot; element={&lt;NotFoundView /&gt;} /&gt;<br>            &lt;Route path=&quot;*&quot; element={&lt;Navigate to=&quot;/auth&quot; /&gt;} /&gt;<br>          &lt;/&gt;<br>        ) : (<br>          &lt;&gt;<br>            &lt;Route path=&quot;/&quot; element={&lt;Navigate to=&quot;/home&quot; /&gt;} /&gt;<br>            &lt;Route path=&quot;/home&quot; element={&lt;HomePage /&gt;} /&gt;<br>            &lt;Route path=&quot;/notFound&quot; element={&lt;NotFoundView /&gt;} /&gt;<br>            &lt;Route path=&quot;*&quot; element={&lt;Navigate to=&quot;/notFound&quot; /&gt;} /&gt;<br>          &lt;/&gt;<br>        )}<br>      &lt;/Routes&gt;<br>    &lt;/Router&gt;<br>  );<br>}</pre><p>loggedIn bilgisini, kullanıcı sisteme giriş yapma bilgisine göre AuthProvider servisimizden alacağız. Böylelikle sisteme giriş yapılmadıysa herhangi bir sayfaya geçiş yapabilmesi engellenmiş olacak. Provider, uygulamada bazı değerleri state içerisinde tutup, istenilen yerde çağırılıp kullanılması anlamına geliyor. Aşağıdaki gibi authprovider oluşturuyoruz. Burada auth işlemini yapıp, eğer dönen cevap doğru ise user bilgisini tutuyoruz.</p><pre>const AuthContext = createContext();<br>const AuthProvider = ({ children }) =&gt; {<br>    const [user, setUser] = useState(null);<br>    const [loggedIn, setLoggedIn] = useState(false);<br>   <br>    const loginAction = async (data) =&gt; {<br>        try {<br>            const response = await fetch(&#39;http://localhost:5273/Auth/login/&#39;, {<br>                method: &#39;POST&#39;,<br>                headers: {<br>                    &quot;Content-Type&quot;: &quot;application/json&quot;<br>                },<br>                body: JSON.stringify(data)<br>            });<br>            if (response.status === 200) {<br>                const res = await response.json();<br>                setUser(res.user);<br>                setLoggedIn(true);<br>                return res.user;<br>            }<br>        } catch (error) {<br>            console.error(&quot;Login error:&quot;, error);<br>        }<br>    };<br>    const logOut = () =&gt; {<br>        setLoggedIn(false);<br>        setUser(null);<br>    }<br>    return &lt;AuthContext.Provider value={{ loggedIn, user, loginAction, logOut }}&gt;{children}&lt;/AuthContext.Provider&gt;;<br>};<br><br>export default AuthProvider;<br><br>export const useAuth = () =&gt; {<br>    return useContext(AuthContext);<br>};</pre><p>Aynı zamanda index.js dosyamızda App kısmını AuthProvider ile sarmalıyoruz. Böylelikle provider içindeki fonksiyonlar ve değişkenler erişilebilir hale geliyor.</p><pre>root.render(<br>  &lt;React.StrictMode&gt;<br>    &lt;AuthProvider&gt;<br>      &lt;App /&gt;<br>    &lt;/AuthProvider&gt;<br>  &lt;/React.StrictMode&gt;<br>);</pre><p>Auth sayfamızda ise aşağıdaki gibi girilen bilgileri almak için inputlar koyuyoruz. Ben stilini vb. düzenlediğim CustomTextInput oluşturdum. Siz direkt olarak &lt;input&gt; olarak da alabilirsiniz.</p><pre>  &lt;h1&gt;Welcome!&lt;/h1&gt;<br>  &lt;CustomTextInput hint={&#39;Email&#39;} setInputValue={setmail} input={mail}&gt;&lt;/CustomTextInput&gt;<br>  &lt;CustomTextInput hint={&#39;Password&#39;} setInputValue={setpassword} input={password}&gt;&lt;/CustomTextInput&gt;           <br>  &lt;CustomButton title={&#39;Login&#39;} handlePress={handlePress}&gt;&lt;/CustomButton&gt;<br>  {error ? (&lt;&gt;&lt;h2&gt;Wrong User!&lt;/h2&gt;&lt;/&gt;) : ( &lt;h1&gt; &lt;/h1&gt;)}</pre><p>Yukarıdaki şekilde sayfamızın bileşenlerini oluşturduk. Asıl önemli kısım inputları alıp doğru bir şekilde backendimize istekte bulunmak. Bunun için aşağıdaki değişkenleri tanımlıyorum. useNavigate, router paketinden gelen ve sayfa geçişini sağlayacak olan bir fonksiyon. useAuth ise daha önce oluşturmuş olduğumuz AuthProvider sınıfımızın içindekilere erişebilmemizi sağlıyor.</p><pre>const auth = useAuth();<br>const [mail, setmail] = useState(&#39;&#39;);<br>const [password, setpassword] = useState(&#39;&#39;);<br>const navigate = useNavigate();</pre><p>HandlePress fonksiyonumuz ise şu şekilde olacak.</p><pre>const handlePress = async () =&gt; {<br>        try {<br>            var res = await auth.loginAction({ &quot;email&quot;: mail, &quot;password&quot;: password });<br>            if (res !== null) {<br>                setError(false);<br>                navigate(&#39;/home&#39;);<br>            }<br>        } catch (err) {<br>            console.log(err);<br>        }<br>    }</pre><p>loginAction fonksiyonuna, useAuth olarak tanımladığımız bileşenden kolayca erişip istek atabilmekteyiz. Eğer dönüş başarılı olursa home sayfasına navigate edecektir.</p><p>Bu yazıda en basit şekilde fullstack bir projeyi nasıl oluşturabileceğimizi aktarmaya çalıştım, umarım faydalı olmuştur. En başta aktarmış olduğum portal için yine benzer şekilde çeşitli fonksiyonlar ile çalışıyor olacağız.</p><blockquote>Daha detaylı bir şekilde kodları incelemek için <a href="https://github.com/sudelmez/react-ui">frontend</a> ve <a href="https://github.com/sudelmez/dotnet-backend">backend</a> linklerinden ulaşabilirsiniz.</blockquote><blockquote><strong><em>Teşekkürler!</em></strong></blockquote><p><em>part 1</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af5d23057cf0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use Uni Links for Deep Linking in Flutter with Navigation Service]]></title>
            <link>https://medium.com/@olmezsude/how-to-use-uni-links-for-deep-linking-in-flutter-with-navigation-service-f1b0cedd2fea?source=rss-e2513e392b3b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1b0cedd2fea</guid>
            <category><![CDATA[google]]></category>
            <category><![CDATA[deep-linking]]></category>
            <category><![CDATA[https]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[flutter-app-development]]></category>
            <dc:creator><![CDATA[olmezsude]]></dc:creator>
            <pubDate>Mon, 12 Feb 2024 18:35:02 GMT</pubDate>
            <atom:updated>2024-02-12T18:55:33.198Z</atom:updated>
            <content:encoded><![CDATA[<p>We all use links to access a new, an image, a post etc. But do we actually know how to use it with our apps?</p><p>Let me start with a quick introduction to deep linking. Just like i mentioned on the first sentence, it is used to direct people who gets a link, to a web site or an app whether is preferred. In this way, you will be able to see the page that sent to you via a link. Also, if we have the application that the link is coming from; it directly opens the app, but if the opposite; it sometimes directs us to the Google Play or App Store to download the app or the website that was made for the link.</p><p>Here is a visual explanation for a better understanding…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cHo1pZ5ECNmIr9jjM1gjPA.png" /><figcaption><a href="https://support.google.com/google-ads/answer/10023042?hl=en">for details on google explanation…</a></figcaption></figure><p>To do that, with flutter, first we need to create an application as we all agree: <strong>flutter create …your_app_name…</strong></p><p>Then, we have the Flutter application. To provide the navigation between pages, I recommend using a navigation service to do all the navigations easily between pages also with props if it is necessary. You can see a part of my base navigation service codes below.</p><pre>class NavigationService implements BaseNavigationService {<br>  static NavigationService? _instance;<br>  static NavigationService get instance {<br>    _instance ??= NavigationService._init();<br>    return _instance!;<br>  }<br><br>  NavigationService._init();<br><br>  GlobalKey&lt;NavigatorState&gt; navigatorKey = GlobalKey();<br><br>  removeOldRoutes() =&gt; (Route&lt;dynamic&gt; route) =&gt; false;<br><br>  @override<br>  Future navigateToPage({required String path, Object? arguments}) async {<br>    return await navigatorKey.currentState!.pushNamed(path, arguments: arguments);<br>  }<br><br>  @override<br>  Future&lt;void&gt; navigatePop&lt;T extends Object?&gt;({T? res}) async {<br>    return navigatorKey.currentState!.pop&lt;T&gt;(res);<br>  }<br>}</pre><p>with this structure, i basically call my defined navigation types with my defined paths. The paths are defined as ‘/home, /..etc’. We need to understand that we also will be using these paths for deeplinking.</p><p>Here is an example of a route:</p><pre>Route generateRoute(RouteSettings args, {Uri? url}) {<br>    switch (args.name) {<br>      case NavigationPaths.home:<br>        Map&lt;String, dynamic&gt; arguments = args.arguments as Map&lt;String, dynamic&gt;;<br>        String? text = arguments[&quot;text&quot;];<br>        return normalNavigate(SecondView(<br>          text: text,<br>        ));<br>      default:<br>        return normalNavigate(const HomeView());<br>    }<br>  }</pre><p>and our main.dart file will contain our navigator key:</p><pre>...return MaterialApp(<br>      navigatorKey: NavigationService.instance.navigatorKey,<br>      onGenerateRoute: NavigationRoute.instance.generateRoute,<br>      ...<br>    );</pre><p><em>(all the codes of this structe will be given below!)</em></p><h3>Finally here is the our Deeplink part!</h3><p>At first, we have to upload the <a href="https://pub.dev/packages/uni_links"><strong>uni links</strong></a> package to our app.</p><p>And then, we need to make sure that we added these lines to our AndroidManifest.xml file to contain some permissions and our host informations!</p><pre>&lt;intent-filter android:autoVerify=&quot;true&quot;&gt;<br>            &lt;action android:name=&quot;android.intent.action.VIEW&quot; /&gt;<br>            &lt;category android:name=&quot;android.intent.category.DEFAULT&quot; /&gt;<br>            &lt;category android:name=&quot;android.intent.category.BROWSABLE&quot; /&gt;<br>            &lt;data<br>            android:scheme=&quot;https&quot;<br>            android:host=&quot;examplehost.com&quot; ---&gt;your host name<br>            android:pathPrefix=&quot;/news&quot;/&gt; ---&gt;here is the part if you have typical route (optional)<br>&lt;/intent-filter&gt;</pre><p>And for IOS in your ios/Runner/Runner.entitlements file;</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;!DOCTYPE plist PUBLIC &quot;-//Apple//DTD PLIST 1.0//EN&quot; &quot;http://www.apple.com/DTDs/PropertyList-1.0.dtd&quot;&gt;<br>&lt;plist version=&quot;1.0&quot;&gt;<br>&lt;dict&gt;<br>  &lt;!-- ... other keys --&gt;<br>  &lt;key&gt;com.apple.developer.associated-domains&lt;/key&gt;<br>  &lt;array&gt;<br>    &lt;string&gt;applinks:[YOUR_HOST]&lt;/string&gt;<br>  &lt;/array&gt;<br>  &lt;!-- ... other keys --&gt;<br>&lt;/dict&gt;<br>&lt;/plist&gt;</pre><p>And now we have permissions for deep linking!</p><p>As you now, we have a custom navigation service for our app. So, to me here was the difficult part to combine these routes. So now, let’s call the uni link function. This funciton returns whether Uri or String link as we desire if there is any. I mean, if the app is opened via a link, this function gets the url path and then we arrange the routing.</p><p>We write two functions, one is for taking the initialUri or String link as we open the app, the other one is for when we close the app but if it is still running on background.</p><pre>void getInitialLink() async {<br>    try {<br>      initialUri = await getInitialUri();<br>      // initialLink=await getInitialLink();<br>      if (initialUri!.pathSegments.isNotEmpty) {<br>        NavigationService.instance.navigateToPage(path: NavigationPaths.second, arguments: {&#39;text&#39;: Uri.parse(currentUri.toString()).pathSegments[1]});<br>      }<br>    } catch (e) {}<br>  }<br><br>  void getLinkStream() {<br>    sub = uriLinkStream.listen((Uri? uri) {<br>      if (uri!.pathSegments.isNotEmpty) {<br>        currentUri = uri;<br>        NavigationService.instance.navigateToPage(path: NavigationPaths.second, arguments: {&#39;text&#39;: Uri.parse(currentUri.toString()).pathSegments[1]});<br>      }<br>    }, onError: (err) {});<br>  }</pre><p>we call the <strong>getInitialUri() </strong>function comes from the package. It returns an Uri. With <strong>getInitialLink() </strong>, we return a string. Whether you choose, you need to write your code properly. In the first function, we check if the uri is empty, if it is not; we use our navigation and show the desired page. As arguments, if we take an information via our link <em>(such as id etc.)</em>, we send these props to our navigated page. Path segments are the parts of our url like “host.com/news/id…”. Surely, you can add any controls due to your link but in this example, i tried to use pretty basic.</p><pre>class _MyAppState extends State&lt;MyApp&gt; {<br>  DeepLinkingConfig deepLink = DeepLinkingConfig();<br>  @override<br>  void didChangeDependencies() {<br>    deepLink.getLinkStream();<br>    super.didChangeDependencies();<br>  }<br>...</pre><p>In the below function, just like I mentioned, we check if there is incoming link during the app is running. If it is, it is navigating to the desired page. And finally, we check that with <strong>didChangeDependencies </strong>function if there is any different behaviour. You can also use StreamBuilder, but to my experience, because it was running all the time; it caused some exceptions on my running app. But of course it is still an option!</p><p>After making all the changes, it is finally test it on your app! You can basically run this command on android:</p><pre>adb shell &#39;am start -W -a android.intent.action.VIEW -c android.intent.category.BROWSABLE -d &quot;unilinks://host/path/subpath&quot;&#39;</pre><p>On IOS:</p><pre>/usr/bin/xcrun simctl openurl booted &quot;unilinks://host/path/subpath&quot;</pre><p>or manually, on your device network, you can paste your link and try to open the address!</p><p>In this article, I tried to explain all I learnt while dealing with deep linking, and that was the best and suitable solution for my structure! I hope it works for you!</p><p>You can check codes <a href="https://github.com/sudelmez/deeplink_tutorial"><strong>here</strong></a>.</p><p><em>(my code does not contain a real host, so uni link will not bring a link for my app, but you can use certain parts as you desire!)</em></p><blockquote><em>Thanks for reading!</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1b0cedd2fea" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>