<?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 Sametkarademir on Medium]]></title>
        <description><![CDATA[Stories by Sametkarademir on Medium]]></description>
        <link>https://medium.com/@sametkarademir244?source=rss-adc52b500845------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*F2hKEOEEcBXDK6UDBEB_RA.jpeg</url>
            <title>Stories by Sametkarademir on Medium</title>
            <link>https://medium.com/@sametkarademir244?source=rss-adc52b500845------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 21:10:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sametkarademir244/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[Stop Writing Tenant Filters Manually — Automate Multi-Tenancy in .NET Core with EF Core]]></title>
            <link>https://medium.com/@sametkarademir244/stop-writing-tenant-filters-manually-automate-multi-tenancy-in-net-core-with-ef-core-ebe81c3384cd?source=rss-adc52b500845------2</link>
            <guid isPermaLink="false">https://medium.com/p/ebe81c3384cd</guid>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[multi-tenant-architecture]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[ef-core]]></category>
            <dc:creator><![CDATA[Sametkarademir]]></dc:creator>
            <pubDate>Mon, 23 Mar 2026 15:12:44 GMT</pubDate>
            <atom:updated>2026-03-23T15:24:48.279Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y15z51mEn16SdIMdjpHuTA.png" /></figure><p>If you’ve ever worked on a multi-tenant SaaS application, you know the pain: every query needs a WHERE TenantId = @tenantId, every insert needs the tenant set, and one missed filter means a data leak between tenants. It&#39;s repetitive, error-prone, and it pollutes your business logic.</p><p>What if I told you that you could handle all of this <strong>once</strong>, at the infrastructure level, and never think about it again in your application services?</p><p>In this article, I’ll walk you through a pattern I built for a .NET Core project that makes multi-tenancy completely transparent. No base class magic, no manual filtering — just interfaces and EF Core’s powerful expression tree API doing the heavy lifting.</p><h3>The Problem</h3><p>In a typical multi-tenant app, you end up with code like this scattered everywhere:</p><pre>var products = await _dbContext.Products<br>    .Where(p =&gt; p.TenantId == _currentTenantId)<br>    .Where(p =&gt; !p.IsDeleted)<br>    .ToListAsync();</pre><p>Multiply this by dozens of entities and hundreds of queries. Forget one filter? Congratulations — Tenant A can now see Tenant B’s data.</p><p>The goal is simple: <strong>write your queries as if tenancy doesn’t exist</strong>, and let the infrastructure handle it.</p><h3>The Approach</h3><p>The solution has three pillars:</p><ol><li><strong>A marker interface</strong> (IMultiTenant) that declares an entity is tenant-scoped</li><li><strong>Dynamic global query filters</strong> that automatically inject WHERE TenantId = X into every query</li><li><strong>A </strong><strong>SaveChangesInterceptor</strong> that auto-assigns TenantId on insert</li></ol><p>The tenant context itself comes from the authenticated user’s JWT claims — no ambient state, no async locals, just the HTTP context.</p><h3>Step 1: The Marker Interface</h3><pre>public interface IMultiTenant<br>{<br>    Guid TenantId { get; set; }<br>}</pre><p>Any entity that implements IMultiTenant will automatically get tenant filtering and auto-assignment. That&#39;s it — no base class inheritance, no attributes.</p><pre>public class Product : IMultiTenant<br>{<br>    public Guid Id { get; set; }<br>    public string Name { get; set; }<br>    public Guid TenantId { get; set; }<br>}</pre><h3>Step 2: Resolving the Current Tenant from JWT</h3><p>The tenant identity lives in the JWT token as a custom claim. When a user logs in, their TenantId is embedded into the token:</p><pre>public static class CustomClaimTypes<br>{<br>    public const string TenantId = &quot;tenant_id&quot;;<br>}<br><br>public static ClaimsIdentity AddTenantId(this ClaimsIdentity identity, Guid tenantId)<br>{<br>    identity.AddClaim(new Claim(CustomClaimTypes.TenantId, tenantId.ToString()));<br>    return identity;<br>}<br><br>public static Guid? GetTenantId(this ClaimsPrincipal user)<br>{<br>    var value = user.FindFirst(CustomClaimTypes.TenantId)?.Value;<br>    return Guid.TryParse(value, out var tenantId) ? tenantId : null;<br>}</pre><p>During token generation, TenantId is added alongside other claims:</p><pre>var claimIdentity = new ClaimsIdentity();<br>claimIdentity.AddUserId(request.Id);<br>claimIdentity.AddUserEmail(request.Email);<br>claimIdentity.AddTenantId(request.TenantId);<br>claimIdentity.AddRoles(request.Roles);</pre><p>The DbContext then exposes this as a property:</p><pre>public class AppDbContext : DbContext<br>{<br>    private readonly IHttpContextAccessor? _httpContextAccessor;<br>    public Guid? CurrentTenantId =&gt; _httpContextAccessor?.HttpContext?.User.GetTenantId();<br>    <br>    public AppDbContext(<br>        DbContextOptions&lt;AppDbContext&gt; options,<br>        IHttpContextAccessor? httpContextAccessor = null) : base(options)<br>    {<br>        _httpContextAccessor = httpContextAccessor;<br>    }<br>}</pre><p>Note that CurrentTenantId is Guid? — this is intentional. When it&#39;s null (e.g., background jobs, migrations, admin endpoints), the filter is bypassed. More on this in a moment.</p><h3>Step 3: Dynamic Query Filters with Expression Trees</h3><p>This is where the real magic happens. Instead of manually configuring query filters per entity, we scan the entire model at startup and generate them dynamically:</p><pre>public static void ApplyMultiTenantQueryFilters(<br>    this ModelBuilder builder,<br>    AppDbContext dbContext)<br>{<br>    foreach (var entityType in builder.Model.GetEntityTypes())<br>    {<br>        if (!typeof(IMultiTenant).IsAssignableFrom(entityType.ClrType))<br>            continue;<br><br>        var parameter = Expression.Parameter(entityType.ClrType, &quot;entity&quot;);<br>        // entity.TenantId<br><br>        var tenantIdProperty = Expression.Property(<br>            parameter, nameof(IMultiTenant.TenantId));<br><br>        // dbContext.CurrentTenantId<br>        var currentTenantId = Expression.Property(<br>            Expression.Constant(dbContext),<br>            nameof(AppDbContext.CurrentTenantId));<br><br>        // Bypass filter when no tenant context exists (null check)<br>        var tenantIdIsNull = Expression.Equal(<br>            currentTenantId,<br>            Expression.Constant(null, typeof(Guid?)));<br><br>        // entity.TenantId == dbContext.CurrentTenantId<br>        var tenantIdEquals = Expression.Equal(<br>            Expression.Convert(tenantIdProperty, typeof(Guid?)),<br>            currentTenantId);<br><br>        // Final: CurrentTenantId == null || entity.TenantId == CurrentTenantId<br>        var tenantCondition = Expression.OrElse(tenantIdIsNull, tenantIdEquals);<br>        <br>        // Combine with soft-delete filter if entity supports it<br>        Expression body;<br>        if (typeof(ISoftDelete).IsAssignableFrom(entityType.ClrType))<br>        {<br>            var softDeleteFilter = Expression.Equal(<br>                Expression.Property(parameter, nameof(ISoftDelete.IsDeleted)),<br>                Expression.Constant(false));<br>            body = Expression.AndAlso(softDeleteFilter, tenantCondition);<br>        }<br>        else<br>        {<br>            body = tenantCondition;<br>        }<br>        var filter = Expression.Lambda(body, parameter);<br>        builder.Entity(entityType.ClrType).HasQueryFilter(filter);<br>    }<br>}</pre><p>A few things to note here:</p><ul><li><strong>Null bypass</strong>: When CurrentTenantId is null, the condition short-circuits to true, so all rows are returned. This is critical for migrations, seeding, and admin/super-user scenarios.</li><li><strong>Soft-delete composition</strong>: Since EF Core only supports <strong>one</strong> query filter per entity, we compose the tenant and soft-delete filters into a single expression. Without this, adding a separate soft-delete filter would override the tenant filter.</li><li><strong>Dynamic discovery</strong>: We don’t list entities manually. Any entity implementing IMultiTenant is picked up automatically.</li></ul><p>This is called in OnModelCreating:</p><pre>protected override void OnModelCreating(ModelBuilder builder)<br>{<br>    base.OnModelCreating(builder);<br>    builder.ApplyConfigurationsFromAssembly(Assembly.GetExecutingAssembly());<br>    builder.ApplyMultiTenantQueryFilters(this);<br>}</pre><p>From this point on, every LINQ query on a tenant-scoped entity automatically includes the tenant filter. Your application services stay clean:</p><pre>// No tenant filter needed — it&#39;s already there<br>var products = await _dbContext.Products.ToListAsync();</pre><h3>Step 4: Auto-Assigning TenantId on Insert</h3><p>Filtering is only half the story. We also need to make sure new records get the correct TenantId without developers remembering to set it. This is handled by a SaveChangesInterceptor:</p><pre>public class EntityAuditInterceptor : SaveChangesInterceptor<br>{<br>    public override async ValueTask&lt;InterceptionResult&lt;int&gt;&gt; SavingChangesAsync(<br>        DbContextEventData eventData,<br>        InterceptionResult&lt;int&gt; result,<br>        CancellationToken cancellationToken = default)<br>    {<br>        var context = eventData.Context;<br>        if (context == null) return result;<br>        <br>        var httpContextAccessor = context.GetService&lt;IHttpContextAccessor&gt;();<br>        context.SetTenantId(httpContextAccessor);<br>        return await base.SavingChangesAsync(eventData, result, cancellationToken);<br>    }<br>}</pre><p>The SetTenantId extension does the actual work:</p><pre>public static void SetTenantId(<br>    this DbContext context,<br>    IHttpContextAccessor httpContextAccessor)<br>{<br>    var tenantId = httpContextAccessor.HttpContext?.User.GetTenantId();<br>    if (tenantId == null) return;<br>    <br>    var addedEntries = context.ChangeTracker.Entries()<br>        .Where(e =&gt; e is { Entity: IMultiTenant, State: EntityState.Added });<br>    foreach (var entry in addedEntries)<br>    {<br>        var entity = (IMultiTenant)entry.Entity;<br>        if (entity.TenantId == Guid.Empty)<br>        {<br>            entity.TenantId = tenantId.Value;<br>        }<br>    }<br>}</pre><p>Key detail: we only set TenantId when it&#39;s Guid.Empty. This allows explicit assignment when needed (e.g., data migration between tenants) while still auto-filling it in the normal flow.</p><h3>How It All Fits Together</h3><p>Here’s the full flow when an authenticated user creates a product:</p><ol><li><strong>Request arrives</strong> → JWT is validated, claims (including TenantId) are available via HttpContext.User</li><li><strong>Service calls</strong> _dbContext.Products.Add(product) → no TenantId set</li><li><strong>SaveChangesAsync is called</strong> → interceptor kicks in, reads TenantId from claims, sets it on the entity</li><li><strong>Later, a query runs</strong> → _dbContext.Products.ToListAsync() → EF Core injects WHERE TenantId = @currentTenantId automatically</li><li><strong>Admin endpoint with no tenant claim</strong> → CurrentTenantId is null → filter is bypassed, all data is visible</li></ol><p>The beauty is that steps 3 and 4 are invisible to anyone writing application code. You add IMultiTenant to your entity, and you&#39;re done.</p><h3>Alternative Tenant Resolution Strategies</h3><p>In this implementation, the tenant is resolved from JWT claims — which works well for SPAs and API-first applications where each request carries a token. But this isn’t the only approach:</p><ul><li><strong>Header-based</strong>: A custom header like X-Tenant-Id is sent with each request. Simple, but requires client cooperation and careful validation.</li><li><strong>Subdomain-based</strong>: tenantA.app.com vs tenantB.app.com. The tenant is resolved from the host in middleware. Great for full white-label scenarios.</li><li><strong>Database lookup</strong>: A middleware resolves tenant from API key, subdomain, or other identifier and looks it up in a tenants table.</li></ul><p>The infrastructure code shown here (query filters, interceptor, expression trees) is <strong>independent of the resolution strategy</strong>. Only the GetTenantId() implementation changes. You could swap JWT for subdomain resolution without touching a single query filter or entity configuration.</p><h3>Wrapping Up</h3><p>Multi-tenancy doesn’t have to be a source of bugs and boilerplate. By combining EF Core’s global query filters with expression trees and SaveChangesInterceptor, you can build a system where:</p><ul><li><strong>Tenant isolation is guaranteed at the data layer</strong>, not hoped for at the service layer</li><li><strong>Application services stay clean</strong> — no tenant-aware queries, no manual assignments</li><li><strong>New entities opt in by implementing an interface</strong> — no configuration, no registration</li><li><strong>The filter bypasses gracefully</strong> when there’s no tenant context</li></ul><p>The key insight is that cross-cutting concerns like tenancy belong in the infrastructure, not in the business logic. Let the framework do the work.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ebe81c3384cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Soft Delete in Entity Framework Core with Generic Repository]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@sametkarademir244/implementing-soft-delete-in-entity-framework-core-with-generic-repository-b44b070b8822?source=rss-adc52b500845------2"><img src="https://cdn-images-1.medium.com/max/1536/1*KZHfpQT1uz9oR2knGgoErg.png" width="1536"></a></p><p class="medium-feed-snippet">Why Soft Delete?</p><p class="medium-feed-link"><a href="https://medium.com/@sametkarademir244/implementing-soft-delete-in-entity-framework-core-with-generic-repository-b44b070b8822?source=rss-adc52b500845------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@sametkarademir244/implementing-soft-delete-in-entity-framework-core-with-generic-repository-b44b070b8822?source=rss-adc52b500845------2</link>
            <guid isPermaLink="false">https://medium.com/p/b44b070b8822</guid>
            <category><![CDATA[soft-delete]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[entity-framework-core]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[repository-pattern]]></category>
            <dc:creator><![CDATA[Sametkarademir]]></dc:creator>
            <pubDate>Tue, 07 Oct 2025 19:43:01 GMT</pubDate>
            <atom:updated>2025-11-06T19:45:38.689Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Building an Advanced and Customizable Logging Infrastructure with Serilog in .NET Core]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-snippet">Logging is a critical part of any professional software project. It helps us monitor the health of applications, track down bugs, and&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@sametkarademir244/building-an-advanced-and-customizable-logging-infrastructure-with-serilog-in-net-core-727be6a4fb07?source=rss-adc52b500845------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@sametkarademir244/building-an-advanced-and-customizable-logging-infrastructure-with-serilog-in-net-core-727be6a4fb07?source=rss-adc52b500845------2</link>
            <guid isPermaLink="false">https://medium.com/p/727be6a4fb07</guid>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[logger]]></category>
            <category><![CDATA[serilog]]></category>
            <category><![CDATA[net-core]]></category>
            <category><![CDATA[logging]]></category>
            <dc:creator><![CDATA[Sametkarademir]]></dc:creator>
            <pubDate>Mon, 30 Jun 2025 20:38:06 GMT</pubDate>
            <atom:updated>2025-06-30T20:38:06.398Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Dependency Injection in .NET with Lifetime-Based Service Registration]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-snippet">Dependency Injection (DI) is a cornerstone of modern software development, enabling developers to create scalable, maintainable, and&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@sametkarademir244/dependency-injection-in-net-with-lifetime-based-service-registration-b2323177876c?source=rss-adc52b500845------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@sametkarademir244/dependency-injection-in-net-with-lifetime-based-service-registration-b2323177876c?source=rss-adc52b500845------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2323177876c</guid>
            <category><![CDATA[net-core]]></category>
            <category><![CDATA[lifetime]]></category>
            <category><![CDATA[service-registry]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <dc:creator><![CDATA[Sametkarademir]]></dc:creator>
            <pubDate>Thu, 26 Dec 2024 18:16:58 GMT</pubDate>
            <atom:updated>2024-12-26T18:16:58.975Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Advanced Audit Logging in .NET Core Using Middleware]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@sametkarademir244/advanced-audit-logging-in-net-core-using-middleware-5d682d9dee30?source=rss-adc52b500845------2"><img src="https://cdn-images-1.medium.com/max/1200/0*2D4a1v6Yb62WGDyN.png" width="1200"></a></p><p class="medium-feed-snippet">Building upon the foundation of implementing an Audit Log system in&#xA0;.NET Core API projects, we can take the concept further by integrating&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@sametkarademir244/advanced-audit-logging-in-net-core-using-middleware-5d682d9dee30?source=rss-adc52b500845------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@sametkarademir244/advanced-audit-logging-in-net-core-using-middleware-5d682d9dee30?source=rss-adc52b500845------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d682d9dee30</guid>
            <category><![CDATA[logging]]></category>
            <category><![CDATA[middleware]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[audit]]></category>
            <dc:creator><![CDATA[Sametkarademir]]></dc:creator>
            <pubDate>Sun, 08 Dec 2024 14:30:20 GMT</pubDate>
            <atom:updated>2024-12-08T14:32:27.965Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Effective Code Documentation with C# XML Comments]]></title>
            <link>https://medium.com/@sametkarademir244/effective-code-documentation-with-c-xml-comments-372f8434fdbf?source=rss-adc52b500845------2</link>
            <guid isPermaLink="false">https://medium.com/p/372f8434fdbf</guid>
            <category><![CDATA[code-comments]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[xml]]></category>
            <category><![CDATA[comment]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <dc:creator><![CDATA[Sametkarademir]]></dc:creator>
            <pubDate>Mon, 02 Dec 2024 18:26:16 GMT</pubDate>
            <atom:updated>2024-12-02T18:26:16.620Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XWBRnNR83vNehm33WPt7BA.png" /></figure><p>The sustainability and readability of code are critical elements in software development processes. Especially in team projects or open-source initiatives, clearly explaining the purpose and usage of code is of utmost importance. This is where <strong>XML-based commenting</strong> in C# comes into play. In this article, we will explore the C# XML commenting system and provide detailed examples of frequently used tags.</p><h3>What is XML Commenting?</h3><p>XML commenting is a documentation system in C# used to define the purpose, usage details, and specific explanations of code elements. These comments, starting with ///, are automatically recognized by tools like IntelliSense, providing guidance to developers. Additionally, these comments can be used to generate API documentation automatically.</p><h3>XML Comment Tags and Examples</h3><h3>1. &lt;summary&gt;</h3><p>Defines a concise and meaningful description of the purpose of a class, method, property, or field. This helps developers quickly understand the intent of the code.</p><h4>Example:</h4><pre>/// &lt;summary&gt;<br>/// Represents a product in the system.<br>/// &lt;/summary&gt;<br>public class Product <br>{<br>    public int Id { get; set; }<br>    public string Name { get; set; }<br>}</pre><h3>2. &lt;remarks&gt;</h3><p>Provides additional details about the functionality, behavior, or limitations of a code element. It is useful for explaining nuances that a simple summary might not cover.</p><h4>Example:</h4><pre>/// &lt;summary&gt;<br>/// Adds a product to the catalog.<br>/// &lt;/summary&gt;<br>/// &lt;remarks&gt;<br>/// This method validates the product&#39;s name and ID before adding it to the catalog.<br>/// &lt;/remarks&gt;<br>/// &lt;param name=&quot;product&quot;&gt;The product to add.&lt;/param&gt;<br>public void AddProduct(Product product) <br>{<br>    // Implementation<br>}</pre><h3>3. &lt;param&gt;</h3><p>Explains the purpose of each parameter in a method. This is particularly useful for complex methods with multiple parameters, ensuring clarity about their roles and expected values.</p><h3>Example:</h3><pre>/// &lt;summary&gt;<br>/// Links a product to a category.<br>/// &lt;/summary&gt;<br>/// &lt;param name=&quot;productId&quot;&gt;The ID of the product to link.&lt;/param&gt;<br>/// &lt;param name=&quot;categoryId&quot;&gt;The ID of the category to link the product to.&lt;/param&gt;<br>public void LinkProductToCategory(int productId, int categoryId) <br>{<br>    // Implementation<br>}</pre><h3>4. &lt;returns&gt;</h3><p>Describes what a method returns. It is essential for methods with non-void return types, clarifying the significance of the returned value and how it should be used.</p><h3>Example:</h3><pre>/// &lt;summary&gt;<br>/// Retrieves all products in a category.<br>/// &lt;/summary&gt;<br>/// &lt;param name=&quot;categoryId&quot;&gt;The ID of the category.&lt;/param&gt;<br>/// &lt;returns&gt;A list of products in the specified category.&lt;/returns&gt;<br>public List&lt;Product&gt; GetProductsByCategory(int categoryId) <br>{<br>    return new List&lt;Product&gt;();<br>}</pre><h3>5. &lt;exception&gt;</h3><p>Documents the types of exceptions a method can throw and under what conditions. This helps developers handle errors effectively and anticipate failure scenarios.</p><h3>Example:</h3><pre>/// &lt;summary&gt;<br>/// Retrieves a product by its ID.<br>/// &lt;/summary&gt;<br>/// &lt;param name=&quot;productId&quot;&gt;The ID of the product.&lt;/param&gt;<br>/// &lt;returns&gt;The product with the specified ID.&lt;/returns&gt;<br>/// &lt;exception cref=&quot;KeyNotFoundException&quot;&gt;Thrown when no product is found with the given ID.&lt;/exception&gt;<br>public Product GetProductById(int productId) <br>{<br>    // Implementation<br>    throw new KeyNotFoundException(&quot;Product not found.&quot;);<br>}</pre><h3>6. &lt;example&gt; and &lt;code&gt;</h3><p>Provides a concrete usage example for a method or class, helping developers understand how to use the code effectively in real-world scenarios.</p><p>Used within &lt;example&gt; or other tags to include formatted code snippets. It ensures that sample code is displayed clearly and correctly in documentation tools.</p><h3>Example:</h3><pre>/// &lt;summary&gt;<br>/// Updates the price of a product.<br>/// &lt;/summary&gt;<br>/// &lt;param name=&quot;productId&quot;&gt;The ID of the product to update.&lt;/param&gt;<br>/// &lt;param name=&quot;newPrice&quot;&gt;The new price of the product.&lt;/param&gt;<br>/// &lt;example&gt;<br>/// &lt;code&gt;<br>/// var catalog = new ProductCatalog();<br>/// catalog.UpdateProductPrice(1, 19.99);<br>/// &lt;/code&gt;<br>/// &lt;/example&gt;<br>public void UpdateProductPrice(int productId, double newPrice) <br>{<br>    // Implementation<br>}</pre><h3>7. &lt;see&gt; and &lt;seealso&gt;</h3><p>Creates an inline reference to another class, method, or member, helping developers navigate related elements directly from the documentation.</p><p>Provides a reference to other related code elements or documentation topics, helping developers explore relevant parts of the codebase more easily.</p><h3>Example:</h3><pre>/// &lt;summary&gt;<br>/// Represents a category that contains multiple products.<br>/// &lt;/summary&gt;<br>/// &lt;seealso cref=&quot;Product&quot;/&gt;<br>/// &lt;see cref=&quot;Product&quot;/&gt;<br>public class Category <br>{<br>    public int Id { get; set; }<br>    public string Name { get; set; }<br>}</pre><h3>8. &lt;value&gt;</h3><p>Describes the purpose or behavior of a property, focusing on what it represents and how it impacts the class or method it belongs to.</p><h3>Example:</h3><pre>/// &lt;summary&gt;<br>/// Gets or sets the name of the product.<br>/// &lt;/summary&gt;<br>/// &lt;value&gt;The name as a string.&lt;/value&gt;<br>public string Name { get; set; }</pre><h3>9. &lt;list&gt;</h3><p>Presents detailed information in a structured list format, such as bullet points or numbered lists. It is useful for enumerating options, steps, or types.</p><h3>Example:</h3><pre>/// &lt;summary&gt;<br>/// Lists the supported product types.<br>/// &lt;/summary&gt;<br>/// &lt;list type=&quot;bullet&quot;&gt;<br>/// &lt;item&gt;<br>/// &lt;description&gt;Electronics&lt;/description&gt;<br>/// &lt;/item&gt;<br>/// &lt;item&gt;<br>/// &lt;description&gt;Clothing&lt;/description&gt;<br>/// &lt;/item&gt;<br>/// &lt;item&gt;<br>/// &lt;description&gt;Groceries&lt;/description&gt;<br>/// &lt;/item&gt;<br>/// &lt;/list&gt;<br>public void ListProductTypes() <br>{<br>    // Implementation<br>}</pre><h3>10. &lt;typeparam&gt;</h3><p>Documents the type parameters of a generic class or method, explaining the role and constraints of each type parameter in the context of the generic implementation.</p><h3>Example:</h3><pre>/// &lt;summary&gt;<br>/// Filters a list of items.<br>/// &lt;/summary&gt;<br>/// &lt;typeparam name=&quot;T&quot;&gt;The type of items to filter.&lt;/typeparam&gt;<br>/// &lt;param name=&quot;items&quot;&gt;The collection of items to filter.&lt;/param&gt;<br>/// &lt;param name=&quot;predicate&quot;&gt;The filtering condition.&lt;/param&gt;<br>/// &lt;returns&gt;A filtered list of items.&lt;/returns&gt;<br>public List&lt;T&gt; Filter&lt;T&gt;(List&lt;T&gt; items, Func&lt;T, bool&gt; predicate) <br>{<br>    return items.Where(predicate).ToList();<br>}</pre><h3>11. &lt;inheritdoc&gt;</h3><p>Inherits comments from a base class or interface. It ensures that derived members have consistent and accurate documentation without redundancy.</p><h3>Example:</h3><pre>/// &lt;inheritdoc /&gt;<br>public override string ToString() <br>{<br>    return base.ToString();<br>}</pre><h3>12. &lt;para&gt;</h3><p>Divides lengthy descriptions into readable paragraphs, improving the clarity and flow of documentation for methods or classes with detailed explanations.</p><h3>Example:</h3><pre>/// &lt;summary&gt;<br>/// Deletes a product from the catalog.<br>/// &lt;para&gt;Make sure to check if the product is linked to any orders before deletion.&lt;/para&gt;<br>/// &lt;para&gt;This method will throw an exception if the product cannot be deleted.&lt;/para&gt;<br>/// &lt;/summary&gt;<br>/// &lt;param name=&quot;productId&quot;&gt;The ID of the product to delete.&lt;/param&gt;<br>public void DeleteProduct(int productId) <br>{<br>    // Implementation<br>}</pre><p>C# XML commenting is a cornerstone of creating a well-documented and maintainable codebase. The tags and methods described above not only guide developers in understanding your code but also significantly improve the long-term sustainability of software. An effective documentation process not only simplifies the development phase but also makes maintenance and extension efforts more efficient.</p><p>Remember, good code is not just code that works but also code that is easy to understand!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=372f8434fdbf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Audit Logs in .NET Core API Projects]]></title>
            <link>https://medium.com/@sametkarademir244/using-audit-logs-in-net-core-api-projects-4ff4ba5290bb?source=rss-adc52b500845------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ff4ba5290bb</guid>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[logging]]></category>
            <category><![CDATA[audit]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <dc:creator><![CDATA[Sametkarademir]]></dc:creator>
            <pubDate>Mon, 25 Nov 2024 14:24:06 GMT</pubDate>
            <atom:updated>2024-11-27T10:01:49.624Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-LOgACIFLYyRbL6dnru5Vw.png" /></figure><h3>Using Audit Logs in .NET Core API Projects</h3><p>In software projects, tracking how and by whom a system is used is a critical requirement. This is especially true in projects that involve security and regulatory compliance. This is where the <strong>Audit Log</strong> system becomes essential.</p><p>In this article, we will explore how to implement an Audit Log system in .NET Core API projects, the methods to integrate it, and the benefits it provides.</p><h3>What is an Audit Log and Why is it Important?</h3><p>An Audit Log is a mechanism used to record important events within a system. These events typically include:</p><ul><li>User login/logout activities,</li><li>CRUD operations such as data creation, updates, or deletion,</li><li>Significant actions like permission or access changes.</li></ul><p>With such a logging mechanism, you can understand what happens within the system, detect anomalies, and meet legal requirements.</p><h3>How to Implement an Audit Log in .NET Core API?</h3><h4>1. Getting Started</h4><p>To set up an Audit Log system in a .NET Core API project, you can follow these steps:</p><ol><li>If you are using <strong>Entity Framework Core</strong>, you can integrate a logging mechanism into the DbContext.</li><li>Use <strong>Action Filters</strong> or <strong>Middleware</strong> for API-level logging.</li><li>Store audit data in a database, file system, or a centralized log management system.</li></ol><h4>2. Entity Model Design</h4><p>You need to create a data model for the Audit Log records. An example model might look like this:</p><pre>public class AuditLog<br>{<br>    public Guid Id { get; set; }<br>    <br>    public string? BrowserInfo { get; set; }<br>    public string? HttpMethod { get; set; }<br>    public string? Url { get; set; }<br>    <br>    public string? ServiceName { get; set; }<br>    public string? MethodName { get; set; }<br>    public string? Parameters { get; set; }<br><br>    public string? EntityId { get; set; }<br>    public string? EntityName { get; set; }<br>    public string? UserId { get; set; }<br>}</pre><pre>public class EntityPropertyChange<br>{<br>    public string? NewValue { get; set; }<br>    public string? OriginalValue { get; set; }<br>    public string? PropertyName { get; set; }<br>    public string? PropertyTypeFullName { get; set; }<br>    public Guid AuditLogId { get; set; }<br>}</pre><h4>3. Adding Audit Logs in DbContext</h4><p>Extend your DbContext class to track changes and create audit log entries:</p><pre>public class AppDbContext : DbContext<br>{<br>    private readonly IHttpContextAccessor _httpContextAccessor;<br>    public AppDbContext(IHttpContextAccessor httpContextAccessor)<br>    {<br>        _httpContextAccessor = httpContextAccessor;<br>    }<br><br>    public DbSet&lt;AuditLog&gt; AuditLogs { get; set; }<br>    public DbSet&lt;EntityPropertyChange&gt; EntityPropertyChanges { get; set; }<br><br>    public override int SaveChanges()<br>    {<br>        var auditEntries = OnBeforeSaveChanges();<br>        var result = base.SaveChanges();<br>        OnAfterSaveChanges(auditEntries);<br>        return result;<br>    }<br><br>    private List&lt;EntityEntry&gt; OnBeforeSaveChanges()<br>    {<br>        return ChangeTracker.Entries().ToList();<br>    }<br><br>    private void OnAfterSaveChanges(List&lt;EntityEntry&gt; auditEntries)<br>    {<br>        var httpContext = _httpContextAccessor.HttpContext;<br><br>        foreach (var entry in auditEntries)<br>        {<br>            var model = entry.Metadata.GetTableName();<br>            <br>            if (entry.State == EntityState.Unchanged)<br>            {<br>                continue;<br>            }<br>      <br>            if (model == &quot;AuditLogs&quot; || model == &quot;EntityPropertyChanges&quot;)<br>            {<br>                continue;<br>            }<br><br>            var auditLog = new AuditLog();<br>            auditLog.Id = Guid.NewGuid();<br>            auditLog.UserId = httpContext?.User?.FindFirstValue(ClaimTypes.NameIdentifier);<br>            auditLog.BrowserInfo = httpContext?.Request.Headers[&quot;User-Agent&quot;].ToString();<br>            auditLog.HttpMethod = httpContext?.Request.Method;<br>            auditLog.Url = httpContext?.Request.Path.ToString();<br>            var routeData = httpContext?.GetRouteData();<br>            auditLog.ServiceName = routeData?.Values[&quot;controller&quot;]?.ToString();<br>            auditLog.MethodName = routeData?.Values[&quot;action&quot;]?.ToString();<br><br>            if (queryParams != null &amp;&amp; queryParams.Any())<br>            {<br>                 foreach (var param in queryParams)<br>                 {<br>                      var queryParameters = JsonConvert.SerializeObject(<br>                      queryParams.ToDictionary(param =&gt; param.Key, param =&gt; param.Value.ToString()));<br>                      parameters.Add($&quot;Query Parameters: {queryParameters}&quot;);<br>                 }<br>            }<br><br>            if (httpContext?.Request.Body.CanSeek == true)<br>            {<br>                 httpContext.Request.Body.Position = 0;<br>            }<br>            else<br>            {<br>                 httpContext.Request.EnableBuffering();<br>            }<br><br>            string originalContent;<br>            using (var reader = new StreamReader(httpContext.Request.Body, Encoding.UTF8, detectEncodingFromByteOrderMarks: false, leaveOpen: true))<br>            {<br>                 originalContent = await reader.ReadToEndAsync();<br>                 httpContext.Request.Body.Position = 0;<br>            }<br><br>            var bodyParameters = JsonConvert.DeserializeObject&lt;Dictionary&lt;string, object&gt;&gt;(originalContent);<br>            if (bodyParameters != null &amp;&amp; bodyParameters.Any())<br>            {<br>                 var bodyContent = JsonConvert.SerializeObject(bodyParameters);<br>                 parameters.Add($&quot;Body Parameters: {bodyContent}&quot;);<br>            }<br><br>            auditLog.Parameters = string.Join(&quot; - &quot;, parameters);<br><br>            auditLog.EntityId = entry.OriginalValues[entry.Metadata.FindPrimaryKey()!.Properties.First().Name]!.ToString();<br>            auditLog.EntityName = model;<br><br>            await AuditLogs.AddAsync(auditLog);<br><br>            foreach (var property in entry.Properties)<br>            {<br>                var columnName = property.Metadata.Name;<br>                var oldValue = property.OriginalValue?.ToString();<br>                var newValue = property.CurrentValue?.ToString();<br><br>                if (!Equals(oldValue, newValue) &amp;&amp; !columnName.Equals(&quot;CreatedDate&quot;))<br>                {<br>                     var entityPropertyChange = new EntityPropertyChange();<br>                     entityPropertyChange.Id = Guid.NewGuid();<br><br>                     entityPropertyChange.AuditLogId = auditLog.Id;<br>                     entityPropertyChange.PropertyName = columnName;<br>                     entityPropertyChange.PropertyTypeFullName = property.Metadata.ClrType.FullName;<br>                     entityPropertyChange.OriginalValue = oldValue;<br>                     entityPropertyChange.NewValue = newValue;<br><br>                     await EntityPropertyChanges.AddAsync(entityPropertyChange);<br>                }<br>             }<br>        }<br>    }<br>}</pre><p>Audit Logs are a critical component for ensuring security, compliance, and transparency in software projects. Implementing this mechanism in .NET Core projects not only enhances the security of your applications but also provides valuable tools to identify and address potential issues.</p><p>I hope this article helps you successfully implement the Audit Log mechanism in your .NET Core projects.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ff4ba5290bb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JwtBearerEvents in ASP.NET Core: Managing Token Events]]></title>
            <link>https://medium.com/@sametkarademir244/jwtbearerevents-in-asp-net-core-managing-token-events-04cdeb9dc30d?source=rss-adc52b500845------2</link>
            <guid isPermaLink="false">https://medium.com/p/04cdeb9dc30d</guid>
            <category><![CDATA[identity-user]]></category>
            <category><![CDATA[events]]></category>
            <category><![CDATA[net-core]]></category>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[bearer-token]]></category>
            <dc:creator><![CDATA[Sametkarademir]]></dc:creator>
            <pubDate>Thu, 21 Nov 2024 23:43:31 GMT</pubDate>
            <atom:updated>2024-11-22T00:34:02.427Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*hHHYRxjflQUMGEg81koGzA.png" /></figure><p>ASP.NET Core provides a robust and flexible framework for JWT-based authentication. One of its key components, JwtBearerEvents, allows us to handle events during the JWT validation process. In this article, we’ll explore the different methods in the JwtBearerEvents class, their purposes, and how to use them in various scenarios.</p><h3>What is JwtBearerEvents?</h3><p>JwtBearerEvents is a class that defines a set of events triggered during JWT validation. These events enable you to control how tokens are validated and processed.</p><p>Below are the main event methods in JwtBearerEvents and their use cases:</p><ol><li><strong>OnMessageReceived</strong></li><li><strong>OnTokenValidated</strong></li><li><strong>OnAuthenticationFailed</strong></li><li><strong>OnChallenge</strong></li><li><strong>OnForbidden</strong></li></ol><h3>1. OnMessageReceived</h3><p>This event is triggered when the JWT is received from the client to the server. For example, if you expect the token in a different HTTP header (default is Authorization) or in a query parameter, you can customize this method.</p><h3>Use Case:</h3><ul><li>Retrieving the token from a query string.</li><li>Dynamically identifying a custom header for the token.</li></ul><pre> services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)<br>            .AddJwtBearer(options =&gt;<br>            {<br>                options.TokenValidationParameters = new TokenValidationParameters<br>                {<br>                    ValidateIssuerSigningKey = true,<br>                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(&quot;token-key&quot;)),<br>                    ValidIssuer = &quot;issuer&quot;,<br>                    ValidateIssuer = true,<br>                    ValidateAudience = false,<br>                    ValidateLifetime = true,<br>                    ClockSkew = TimeSpan.Zero<br>                };<br>                <br>            options.Events = new JwtBearerEvents<br>            {<br>                OnMessageReceived = context =&gt;<br>                {<br>                    var accessToken = context.Request.Query[&quot;access_token&quot;];<br>                    if (!string.IsNullOrEmpty(accessToken))<br>                    {<br>                        context.Token = accessToken;<br>                    }<br>                    return Task.CompletedTask;<br>                }<br>            };<br>       });</pre><h3>2. OnTokenValidated</h3><p>This event is triggered when the token is successfully validated. Here, you can add additional authorization or session checks.</p><h3>Use Case:</h3><ul><li>Verifying a user’s session validity in a caching system.</li><li>Updating user information based on additional requirements.</li></ul><pre>options.Events = new JwtBearerEvents<br>{<br>    OnTokenValidated = async context =&gt;<br>    {<br>        var claimsPrincipal = context.Principal;<br>        var userId = claimsPrincipal.FindFirst(ClaimTypes.NameIdentifier)?.Value;<br><br>        if (string.IsNullOrEmpty(userId))<br>        {<br>            context.Fail(&quot;User ID could not be validated.&quot;);<br>            return;<br>        }<br><br>        var serviceProvider = context.HttpContext.RequestServices;<br>        var cacheService = serviceProvider.GetRequiredService&lt;ICacheService&gt;();<br><br>        var cache = await cacheService.GetAsync&lt;TokenModel&gt;(userId);<br>        if (cache == null)<br>        {<br>            throw new SecurityTokenException(&quot;Session has expired.&quot;);<br>        }<br>    }<br>};</pre><h3>3. OnAuthenticationFailed</h3><p>This event is triggered when an error occurs during token validation. You can handle the errors and implement custom logic in this method.</p><h3>Use Case:</h3><ul><li>Returning a custom error message when the token has expired.</li><li>Logging structural issues in the token.</li></ul><pre>options.Events = new JwtBearerEvents<br>{<br>    OnAuthenticationFailed = context =&gt;<br>    {<br>        if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))<br>        {<br>            context.Response.Headers.Add(&quot;Token-Expired&quot;, &quot;true&quot;);<br>        }<br><br>        return Task.CompletedTask;<br>    }<br>};</pre><h3>4. OnChallenge</h3><p>This event is triggered when authentication fails. You can use it to customize the response sent back to the client.</p><h3>Use Case:</h3><ul><li>Returning custom error codes in API responses.</li><li>Informing users why access is denied.</li></ul><pre>options.Events = new JwtBearerEvents<br>{<br>    OnChallenge = context =&gt;<br>    {<br>        context.Response.StatusCode = 401;<br>        context.Response.ContentType = &quot;application/json&quot;;<br>        var result = JsonConvert.SerializeObject(new { error = &quot;Authentication failed.&quot; });<br>        return context.Response.WriteAsync(result);<br>    }<br>};</pre><h3>5. OnForbidden</h3><p>This event is triggered when a user lacks permission to access a resource (403 status code). It can be used to provide a detailed message explaining why access is forbidden.</p><h3>Use Case:</h3><ul><li>Sending a detailed message for unauthorized access attempts.</li><li>Restricting access to admin panels or other sensitive areas.</li></ul><pre>options.Events = new JwtBearerEvents<br>{<br>    OnForbidden = context =&gt;<br>    {<br>        context.Response.StatusCode = 403;<br>        context.Response.ContentType = &quot;application/json&quot;;<br>        var result = JsonConvert.SerializeObject(new { error = &quot;You do not have access to this resource.&quot; });<br>        return context.Response.WriteAsync(result);<br>    }<br>};</pre><h3>When to Use?</h3><p>The JwtBearerEvents class is typically used in advanced scenarios such as:</p><ul><li><strong>Customizing the Token Validation Process:</strong> Making token handling, validation, and error management more manageable.</li><li><strong>User Session Management:</strong> After validating the token, ensuring the user’s session is valid through an additional service.</li><li><strong>Error Handling:</strong> Returning user-friendly responses for issues like expired tokens or invalid structures.</li><li><strong>Adding Custom Rules:</strong> Modifying how tokens are transported or detailing access permissions.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=04cdeb9dc30d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NET Core ve Entity Framework Kullanarak SQL Transaction’larını Yönetme]]></title>
            <link>https://medium.com/@sametkarademir244/net-core-ve-entity-framework-kullanarak-sql-transactionlar%C4%B1n%C4%B1-y%C3%B6netme-0370eab7085b?source=rss-adc52b500845------2</link>
            <guid isPermaLink="false">https://medium.com/p/0370eab7085b</guid>
            <category><![CDATA[repository-design-pattern]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[uow]]></category>
            <category><![CDATA[transactions]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Sametkarademir]]></dc:creator>
            <pubDate>Wed, 14 Feb 2024 17:36:55 GMT</pubDate>
            <atom:updated>2024-02-14T17:36:55.836Z</atom:updated>
            <content:encoded><![CDATA[<p>SQL transaction’ları, bir veritabanı işlemi sırasında birden çok sorgunun gruplanması ve bu sorguların birlikte ya tamamının gerçekleşmesi ya da hiçbirinin gerçekleşmemesi gerektiği durumlarda oldukça önemlidir. .NET Core ve Entity Framework (EF) kullanarak bu transaction’ları yönetmek, uygulamanızın veritabanı işlemlerini güvenli ve tutarlı bir şekilde gerçekleştirmenize yardımcı olur.</p><p>Bu makalede, .NET Core ve Entity Framework kullanarak Generic Repository ve Unit of Work desenlerini uygulayarak SQL transaction’larını yönetmeyi öğreneceğiz. Bu desenler, veritabanı işlemlerini soyutlayarak kodunuzu daha organize eder ve bakımını kolaylaştırır.</p><h3>Generic Repository ve Unit of Work Kavramları</h3><h3>Generic Repository</h3><p>Generic Repository, bir veritabanı işlemlerini soyutlamak için kullanılan bir tasarım desenidir. Bu desen, CRUD (Create, Read, Update, Delete) işlemlerini genel bir arabirim üzerinden yönetir ve veritabanı işlemlerinin tekrar kullanılabilirliğini artırır.</p><pre>public interface IRepository&lt;T&gt; where T : class<br>{<br>    Task&lt;T&gt; GetByIdAsync(int id);<br>    Task&lt;IEnumerable&lt;T&gt;&gt; GetAllAsync();<br>    void Add(T entity);<br>    void Update(T entity);<br>    void Delete(T entity);<br>}</pre><h3>Unit of Work</h3><p>Unit of Work deseni, bir grup işlemi birlikte yönetmek için kullanılır. Bu desen, bir veya daha fazla işlemi bir araya getirir ve bunların aynı transaction içinde gerçekleştirilmesini sağlar.</p><pre>public interface IUow : IAsyncDisposable<br>{<br>    IUserRepository UserRepository { get; }<br><br><br>    Task&lt;int&gt; SaveAsync();<br>    <br>    IDbContextTransaction BeginTransaction();<br>    Task&lt;IDbContextTransaction&gt; BeginTransactionAsync();<br>}</pre><pre>public class Uow : IUow<br>{<br>    <br>    private readonly AppDbContext _context;<br>    <br>    private readonly UserRepository _userRepository = null!;<br><br>    public Uow(AppDbContext context) { _context = context; }<br><br>    public IUserRepository UserRepository =&gt; _userRepository ?? new UserRepository(_context);<br>    <br>    public IDbContextTransaction BeginTransaction() { return _context.Database.BeginTransaction(); }<br>    public async Task&lt;IDbContextTransaction&gt; BeginTransactionAsync() { return await _context.Database.BeginTransactionAsync(); }<br>    public async Task&lt;int&gt; SaveAsync() { return await _context.SaveChangesAsync(); }<br>    public async ValueTask DisposeAsync() { await _context.DisposeAsync(); }<br>    <br>}</pre><h3>Kullanım Örneği</h3><p>Transaction içinde birden fazla işlem gerçekleştirmek için Unit of Work kullanımını gösteren bir örnek:</p><pre>public async Task ExampleMethod(IUow Uow)<br>{<br><br>    using (var transaction = await Uow.BeginTransactionAsync())<br>    {<br>        try<br>        {<br>          var repository1 = Uow.GetRepository&lt;Entity1&gt;();<br>          var repository2 = Uow.GetRepository&lt;Entity2&gt;();<br>        <br>          // Birden fazla işlem gerçekleştirme<br>          repository1.Add(entity1);<br>          repository2.Delete(entity2);<br>        <br>          await Uow.SaveChangesAsync();<br>          await transaction.CommitAsync();<br>        }<br>        catch (Exception ex)<br>        {<br>            // Herhangi bir hata durumunda işlemler geri alınır.<br>            transaction.Rollback();<br>            throw ex;<br>        }<br>    }<br>}</pre><p>Bu makalede, .NET Core ve Entity Framework kullanarak Generic Repository ve Unit of Work desenlerini kullanarak SQL transaction’larını nasıl yöneteceğinizi öğrendiniz. Bu desenler, veritabanı işlemlerini organize etmenize ve güvenli bir şekilde gerçekleştirmenize yardımcı olur.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0370eab7085b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Projesinde useState Hook’u Kullanarak Form Inputlarını onChange Metoduyla Güncelleme]]></title>
            <link>https://medium.com/@sametkarademir244/react-projesinde-usestate-hooku-kullanarak-form-inputlar%C4%B1n%C4%B1-onchange-metoduyla-g%C3%BCncelleme-eb49b648a470?source=rss-adc52b500845------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb49b648a470</guid>
            <category><![CDATA[usestate]]></category>
            <category><![CDATA[onchange]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[hooks]]></category>
            <category><![CDATA[forms]]></category>
            <dc:creator><![CDATA[Sametkarademir]]></dc:creator>
            <pubDate>Mon, 12 Feb 2024 08:12:53 GMT</pubDate>
            <atom:updated>2024-02-12T08:12:53.988Z</atom:updated>
            <content:encoded><![CDATA[<p>React, modern web uygulamaları geliştirmek için popüler bir JavaScript kütüphanesidir. Form işlemleri, web uygulamalarının temel taşlarından biridir ve React’in useState kancası, formların yönetimini kolaylaştıran güçlü bir araçtır. Bu makalede, React projesinde useState hook&#39;unu kullanarak form inputlarını onChange metoduyla nasıl güncelleyeceğimizi öğreneceğiz.</p><p>React’te useState hook&#39;u, işlevel bileşenlerde yerel durumu (state) yönetmek için kullanılır. Bu hook, işlevsel bileşenlerin durumlarını saklamak ve güncellemek için kullanılır. Genel kullanımı şu şekildedir:</p><pre>import React, { useState } from &#39;react&#39;;<br><br>const FormComponent = () =&gt; {<br>  // State tanımı<br>  const [state, setState] = useState(initialState);<br>};</pre><p>Form inputlarını useState ile yönetmek, formun içeriğini saklamak ve güncellemek için kolay bir yol sağlar. Örneğin, bir kullanıcı adı, e-posta ve şifre alanları içeren bir formumuz olduğunu varsayalım. Bu formdaki inputları useState ile yönetmek için şu adımları izleyebiliriz:</p><ul><li>İlgili inputların başlangıç değerlerini ve bu değerleri saklayacak olan state’i tanımlayın.</li></ul><pre>const [formData, setFormData] = useState({<br>  username: &#39;&#39;,<br>  email: &#39;&#39;,<br>  password: &#39;&#39;<br>});</pre><ul><li>Her input için bir onChange olayı ekleyerek input değerlerini güncelleyin.</li></ul><pre>const handleInputChange = (e) =&gt; {<br>  const { name, value } = e.target;<br>  setFormData(prevState =&gt; ({...prevState,[name]: value}));<br>};</pre><ul><li>Form İşlemlerini Tamamlama</li></ul><pre>      &lt;input<br>          type=&quot;text&quot;<br>          id=&quot;username&quot;<br>          name=&quot;username&quot;<br>          value={formData.username}<br>          onChange={handleInputChange}<br>        /&gt;</pre><p>Form inputlarını güncelledikten sonra, formun gönderilmesini işlemek için bir handleSubmit işlevi oluşturabiliriz. Bu işlev, formun verilerini alır ve gerekli işlemleri gerçekleştirir. Örneğin, bir API&#39;ye göndermek veya başka bir işlem yapmak gibi.</p><pre>const handleSubmit = (e) =&gt; {<br>  e.preventDefault();<br>  // Form işlemleri burada yapılabilir<br>};</pre><h4>Kodun Tamamı</h4><pre>import React, { useState } from &#39;react&#39;;<br><br>const FormComponent = () =&gt; {<br>  // Form verilerini saklayacak state<br>  const [formData, setFormData] = useState({<br>  username: &#39;&#39;,<br>  email: &#39;&#39;,<br>  password: &#39;&#39;<br>});<br><br>  // Input değişikliklerini takip eden fonksiyon<br>  const handleInputChange = (e) =&gt; {<br>    const { name, value } = e.target;<br>    setFormData(prevState =&gt; ({...prevState,[name]: value}));<br>  };<br><br>  // Form submit işlemi<br>  const handleSubmit = (e) =&gt; {<br>    e.preventDefault();<br>    // Form verilerini kullanarak istediğiniz işlemleri gerçekleştirin<br>    console.log(formData);<br>  };<br><br>  return (<br>    &lt;form onSubmit={handleSubmit}&gt;<br>      &lt;div&gt;<br>        &lt;label htmlFor=&quot;name&quot;&gt;Name:&lt;/label&gt;<br>        &lt;input<br>          type=&quot;text&quot;<br>          id=&quot;username&quot;<br>          name=&quot;username&quot;<br>          value={formData.username}<br>          onChange={handleInputChange}<br>        /&gt;<br>      &lt;/div&gt;<br>      &lt;div&gt;<br>        &lt;label htmlFor=&quot;email&quot;&gt;Email:&lt;/label&gt;<br>        &lt;input<br>          type=&quot;email&quot;<br>          id=&quot;email&quot;<br>          name=&quot;email&quot;<br>          value={formData.email}<br>          onChange={handleInputChange}<br>        /&gt;<br>      &lt;/div&gt;<br>      &lt;div&gt;<br>        &lt;label htmlFor=&quot;password&quot;&gt;Password:&lt;/label&gt;<br>        &lt;input<br>          type=&quot;password&quot;<br>          id=&quot;password&quot;<br>          name=&quot;password&quot;<br>          value={formData.password}<br>          onChange={handleInputChange}<br>        /&gt;<br>      &lt;/div&gt;<br>      &lt;button type=&quot;submit&quot;&gt;Submit&lt;/button&gt;<br>    &lt;/form&gt;<br>  );<br>};<br><br>export default FormComponent;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb49b648a470" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>