<?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 Semih Yücel on Medium]]></title>
        <description><![CDATA[Stories by Semih Yücel on Medium]]></description>
        <link>https://medium.com/@yucelarts?source=rss-226933b4b93d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*_fD3f6xVuZpwb-BcK5oxow.jpeg</url>
            <title>Stories by Semih Yücel on Medium</title>
            <link>https://medium.com/@yucelarts?source=rss-226933b4b93d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 20:57:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yucelarts/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[Pipeline Engine in .Net Core]]></title>
            <link>https://yucelarts.medium.com/pipeline-engine-in-net-core-98aee75310be?source=rss-226933b4b93d------2</link>
            <guid isPermaLink="false">https://medium.com/p/98aee75310be</guid>
            <category><![CDATA[pipeline-management]]></category>
            <category><![CDATA[workflow-management]]></category>
            <category><![CDATA[pipeline]]></category>
            <category><![CDATA[engine]]></category>
            <category><![CDATA[workflow]]></category>
            <dc:creator><![CDATA[Semih Yücel]]></dc:creator>
            <pubDate>Sat, 14 Sep 2024 09:31:07 GMT</pubDate>
            <atom:updated>2024-09-14T09:36:07.770Z</atom:updated>
            <content:encoded><![CDATA[<h3>Pipeline Engine in .Net</h3><h3>How about a simple sequential service project with .net.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OXMUby_05tdv80X0" /></figure><p>There is a sequential structure that most of us don’t realize but we use it all the time. and this structure is the Middleware structure.</p><p>Yes, you didn’t hear wrong.</p><p>But what is unusual here is that the request passes through the controls and comes to the HomeController and then we ensure that the pipeline structure we have prepared works.</p><p>You can dynamically define which job list you want to run in the request body or from the Repository layer after the request.</p><p>ps:<br>A build where I use <strong>HttpClientService</strong> for HttpClient requests<br>I use <strong>SmtpClientService</strong> to send mail<br><strong>ResponseService </strong>will be used for Response</p><p>The <strong>Parameters </strong><em>property key</em> field will be filled with each process’s own model.</p><p>Run Http Request as the first job. transfer the returned result to the first job and send SMS and show the result with the third job.</p><p><strong>To do all this, the following Json definition is sufficient</strong></p><pre>[<br>    {<br>        &quot;BaseID&quot;: 1,<br>        &quot;ParentId&quot;:0,<br>        &quot;JobType&quot;: &quot;HttpClientService&quot;,<br>        &quot;Parameters&quot;: {<br>            &quot;Url&quot;: &quot;https://official-joke-api.appspot.com/random_joke&quot;<br>              // other keys<br>        }<br>    },<br>{<br>        &quot;BaseID&quot;: 2,<br>        &quot;ParentId&quot;:1,<br>        &quot;JobType&quot;: &quot;SmtpClientService&quot;,<br>        &quot;Parameters&quot;: {}<br>    },<br>    {<br>        &quot;BaseID&quot;: 3,<br>        &quot;ParentId&quot;:2,<br>          &quot;JobType&quot;: &quot;ResponseService&quot;,<br>        &quot;Parameters&quot;: {}<br>    }<br>]</pre><p>For each Job, you can write separate activities in your project, which will allow you to do DI only in the relevant Middleware class and will be healthier for modular monolithic.</p><h3>You can follow my GitHub profile for the details of my project.</h3><p><a href="https://github.com/YucelArts/Ocean.Flow.PipelineManager">https://github.com/YucelArts/Ocean.Flow.PipelineManager</a></p><p><strong>PipelineManager: </strong>structure used to run services in work order</p><pre>    public class PipelineManagerService<br>    {<br>        private readonly IPipelineFactory _piplineFactory;<br><br>        public PipelineManagerService(IPipelineFactory piplineFactory)<br>        {<br>            _piplineFactory = piplineFactory;<br><br>        }<br><br>        public async Task&lt;object&gt; ExecutePipelineAsync(List&lt;JobDefinition&gt; jobs, object initialData)<br>        {<br>            // Tüm job&#39;ları BaseID ile ilişkilendiriyoruz<br>            var jobMap = jobs.ToDictionary(j =&gt; j.BaseID);<br><br>            // ParentId&#39;si 0 olan root job&#39;ları buluyoruz (başlangıç job&#39;ları)<br>            var rootJobs = jobs.Where(j =&gt; j.ParentId == 0).ToList();<br><br>            object result = initialData;<br><br>            // Root job&#39;ları sırasıyla işleyelim<br>            foreach (var rootJob in rootJobs)<br>            {<br>                result = await ExecuteJobAsync(rootJob, jobMap, result);<br>            }<br><br>            return result;<br>        }<br>        private async Task&lt;object&gt; ExecuteJobAsync(JobDefinition currentJob, Dictionary&lt;int, JobDefinition&gt; jobMap, object input)<br>        {<br>            // İşlenecek middleware&#39;i oluştur<br>            var middleware = _piplineFactory.CreateJob(currentJob.JobType);<br><br>            // Middleware&#39;i çalıştır ve input&#39;u güncelle<br>            input = await middleware.InvokeAsync(input, () =&gt; Task.FromResult(input), currentJob.Parameters);<br><br>            // Bu job&#39;un child&#39;larını bulalım<br>            var childJobs = jobMap.Values.Where(j =&gt; j.ParentId == currentJob.BaseID).ToList();<br><br>            // Child job&#39;ları sırayla çalıştıralım<br>            foreach (var childJob in childJobs)<br>            {<br>                input = await ExecuteJobAsync(childJob, jobMap, input);<br>            }<br><br>            return input;<br>        }<br><br>    }</pre><p><strong>PipelineFactory: </strong>provider selector in order of work</p><pre>    public class PipelineFactory : IPipelineFactory<br>    {<br>        private readonly IServiceProvider _serviceProvider;<br>        public PipelineFactory(IServiceProvider serviceProvider)<br>        {<br>            _serviceProvider = serviceProvider;<br>        }<br>        public IPipelineMiddleware CreateJob(string jobType) =&gt; jobType switch<br>        {<br>            nameof(JobType.HttpClientService) =&gt; _serviceProvider.GetRequiredService&lt;HttpClientJob&gt;(),<br>            nameof(JobType.SmtpClientService) =&gt; _serviceProvider.GetRequiredService&lt;SmtpClientJob&gt;(),<br>            nameof(JobType.ResponseService) =&gt; _serviceProvider.GetRequiredService&lt;ResponseJob&gt;(),<br>            //&quot;ProcessJob&quot; =&gt; _serviceProvider.GetRequiredService&lt;ProcessJob&gt;(),<br>            _ =&gt; throw new InvalidOperationException($&quot;Unknown job type: {jobType}&quot;)<br>        };<br><br>    }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*qC6rHGa6-sK13Dv3u__7gQ.png" /><figcaption>PipeLine Solition</figcaption></figure><h3>You can run your services sequentially by typing your activities.</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98aee75310be" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Dynamically Transform SQL Data into Rich JSON Formats]]></title>
            <link>https://yucelarts.medium.com/how-to-dynamically-transform-sql-data-into-rich-json-formats-cb435ae0b8cd?source=rss-226933b4b93d------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb435ae0b8cd</guid>
            <category><![CDATA[json]]></category>
            <category><![CDATA[datarender]]></category>
            <category><![CDATA[low-code]]></category>
            <category><![CDATA[dynamic-programming]]></category>
            <category><![CDATA[tree-list]]></category>
            <dc:creator><![CDATA[Semih Yücel]]></dc:creator>
            <pubDate>Thu, 22 Aug 2024 18:25:13 GMT</pubDate>
            <atom:updated>2024-08-23T08:52:47.404Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Data2JsonRender</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mqrYH3tmpvgO1DeV" /></figure><p>In today’s data-driven world, efficiently converting SQL database tables into JSON format is crucial for seamless integration between various applications and services. The “<strong>Data2JsonRender</strong>” project tackles this challenge head-on, providing a robust solution for dynamically generating JSON outputs from relational database structures.</p><p>This article will explore the architecture, design patterns, and implementation details of the <strong>Data2JsonRender </strong>tool, offering insights into its flexible and scalable approach to data transformation.</p><p>Join me as we break down the key components and strategies that make <strong>Data2JsonRender </strong>an essential tool for modern application development, and learn how you can leverage its capabilities in your own projects.</p><p>I need to talk about <strong>ModelStructure</strong>. <br><strong>Name </strong>field in this model represents the Key field in the Json Data Set.</p><p><strong>FiledType </strong>field represents the Data type in the Json Data Set. this section works as data type and section type. Definitions made as MODEL are rendered as { } json model type and definitions made as ARRAY are rendered as [ { } ] json array type</p><p><strong>TableField </strong>field represents the value section in the Json data set.</p><p><strong>Index</strong> field represents which DataTable in the sent DataSet to look for the data in.</p><p><strong>ParentName</strong> field refers to the section to which it is connected. You can think like Tree List.</p><pre>    public class ModelStructure<br>    {<br>        public string Name { get; set; }<br>        public string FiledType { get; set; }<br>        public string ParentName { get; set; }<br>        public int? Index { get; set; } // DataTable index (nullable)<br>        public string DefaultValue { get; set; }<br>        public string TableField { get; set; } = null;<br>    }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*EREykTjHlyBI6MKkHhdp8Q.png" /></figure><p><strong>Sample Json Data Set</strong></p><pre>{<br>  &quot;H_ProcOrder&quot;: { // MODEL<br>    &quot;OrderRefNr&quot;: &quot;PO0000504&quot;, // String<br>    &quot;VendorCode&quot;: &quot;BB201707154&quot;, // String<br>    &quot;H_ProcOrderDet&quot;: [  --ARRAY<br>      {<br>        &quot;odItemTreeID&quot;: &quot;01.004.100003&quot;, // String<br>        &quot;odPurchaseGroupCode&quot;: &quot;01&quot;,  // String<br>        &quot;odItemCategory&quot;: 100003  // Int<br>      },<br>      {<br>        &quot;odItemTreeID&quot;: &quot;01.004.100011&quot;, // String<br>        &quot;odPurchaseGroupCode&quot;: &quot;01&quot;, // String<br>        &quot;odItemCategory&quot;: 100011 -- Int<br>      },<br>      {<br>        &quot;odItemTreeID&quot;: &quot;08.010.100008&quot;,  // String<br>        &quot;odPurchaseGroupCode&quot;: &quot;08&quot;,  // String<br>        &quot;odItemCategory&quot;: 100008  // Int<br>      }<br>    ]<br>  }<br>}</pre><p><strong>ModelStructure of Sample Json Data Set</strong></p><pre><br>var model = new List&lt;ModelStructure&gt;<br>  {<br>    new ModelStructure { Name = &quot;H_ProcOrder&quot;, FiledType  = &quot;Model&quot;, ParentName = &quot;&quot; },<br>    new ModelStructure { Name = &quot;OrderRefNr&quot;, FiledType = &quot;string&quot;, ParentName = &quot;H_ProcOrder&quot;, TableField=&quot;OrderRefNr&quot;  },<br>    new ModelStructure { Name = &quot;VendorCode&quot;, FiledType  = &quot;string&quot;, ParentName = &quot;H_ProcOrder&quot;,TableField=&quot;VendorCode&quot; },<br>    new ModelStructure { Name = &quot;H_ProcOrderDet&quot;, FiledType = &quot;Array&quot;, ParentName = &quot;H_ProcOrder&quot; },<br>    new ModelStructure { Name = &quot;odItemTreeID&quot;, FiledType  = &quot;string&quot;, ParentName = &quot;H_ProcOrderDet&quot;, TableField=&quot;odItemTreeID&quot; },<br>    new ModelStructure { Name = &quot;odPurchaseGroupCode&quot;, FiledType  = &quot;string&quot;, ParentName = &quot;H_ProcOrderDet&quot;,TableField=&quot;odPurchaseGroupCode&quot; },<br>    new ModelStructure { Name = &quot;odItemCategory&quot;, FiledType  = &quot;int&quot;, ParentName = &quot;H_ProcOrderDet&quot;,TableField=&quot;odItemCategory&quot; }<br>  };</pre><p>The Data2JsonRender library offers versatile applications across various domains:</p><ul><li><strong>API Interactions:</strong> Enables the dynamic creation of raw JSON requests, allowing for flexible and precise data structuring tailored to each API call.</li><li><strong>TreeView Structures:</strong> Facilitates the development of complex TreeView components, essential for displaying hierarchical data interactively and clearly.</li><li><strong>Templater.io Integration:</strong> Enhances the Templater.io library by enabling seamless manipulation of JSON datasets, streamlining the customization and processing of templates.</li><li><strong>Navigation Bars:</strong> Simplifies the construction of NavBar structures, supporting the implementation of dynamic and responsive navigation systems within web and mobile applications.</li></ul><p>I share the result of the Multiple Data example below. You can see the output of xUnitTest when visiting the gitHup link.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*MwrA4L2A3j68WcBNFEpnYA.png" /><figcaption>ModelStructure</figcaption></figure><pre>        private DataSet MultipleDataSet()<br>        {<br>            DataSet dataSet = new DataSet();<br><br>            DataTable table0 = new DataTable();<br>            table0.Columns.Add(&quot;applicationCode&quot;, typeof(string));<br>            table0.Columns.Add(&quot;username&quot;, typeof(string));<br>            table0.Columns.Add(&quot;password&quot;, typeof(string));<br>            table0.Columns.Add(&quot;languageCode&quot;, typeof(string));<br>            table0.Columns.Add(&quot;correlationId&quot;, typeof(string));<br>            table0.Columns.Add(&quot;timeOut&quot;, typeof(string));<br>            table0.Rows.Add(&quot;TPORT&quot;, &quot;TUSER&quot;, &quot;123456&quot;, &quot;2&quot;, new Guid().ToString(), &quot;120&quot;);<br><br><br>            DataTable table1 = new DataTable();<br>            table1.Columns.Add(&quot;OrderRefNr&quot;, typeof(string));<br>            table1.Columns.Add(&quot;VendorCode&quot;, typeof(string));<br>            table1.Rows.Add(&quot;PO0000504&quot;, &quot;BB201707154&quot;);<br><br>            DataTable table2 = new DataTable();<br>            table2.Columns.Add(&quot;odItemTreeID&quot;, typeof(string));<br>            table2.Columns.Add(&quot;odPurchaseGroupCode&quot;, typeof(string));<br>            table2.Columns.Add(&quot;odItemCategory&quot;, typeof(int));<br>            table2.Rows.Add(&quot;01.004.100003&quot;, &quot;01&quot;, 100003);<br>            table2.Rows.Add(&quot;01.004.100011&quot;, &quot;01&quot;, 100011);<br>            table2.Rows.Add(&quot;08.010.100008&quot;, &quot;08&quot;, 100008);<br><br>            dataSet.Tables.Add(table0);<br>            dataSet.Tables.Add(table1);<br>            dataSet.Tables.Add(table2);<br>            return dataSet;<br>        }</pre><pre>{<br>  &quot;requestHeader&quot;: { // DataTable 0<br>    &quot;applicationCode&quot;: &quot;TPORT&quot;,<br>    &quot;username&quot;: null,<br>    &quot;password&quot;: null,<br>    &quot;languageCode&quot;: null,<br>    &quot;correlationId&quot;: null,<br>    &quot;timeOut&quot;: null<br>  },<br>  &quot;H_ProcOrder&quot;: {  // DataTable 1<br>    &quot;OrderRefNr&quot;: &quot;PO0000504&quot;,<br>    &quot;VendorCode&quot;: &quot;BB201707154&quot;,<br>    &quot;H_ProcOrderDet&quot;: [  // DataTable 2<br>      {<br>        &quot;odItemTreeID&quot;: &quot;01.004.100003&quot;,<br>        &quot;odPurchaseGroupCode&quot;: &quot;01&quot;,<br>        &quot;odItemCategory&quot;: 100003<br>      },<br>      {<br>        &quot;odItemTreeID&quot;: &quot;01.004.100011&quot;,<br>        &quot;odPurchaseGroupCode&quot;: &quot;01&quot;,<br>        &quot;odItemCategory&quot;: 100011<br>      },<br>      {<br>        &quot;odItemTreeID&quot;: &quot;08.010.100008&quot;,<br>        &quot;odPurchaseGroupCode&quot;: &quot;08&quot;,<br>        &quot;odItemCategory&quot;: 100008<br>      }<br>    ]<br>  }<br>}</pre><blockquote><strong>Here is the GitHup link to use this .net library</strong></blockquote><p><a href="https://github.com/YucelArts/Ocean.Core.Data2JsonRender">https://github.com/YucelArts/Ocean.Core.Data2JsonRender</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb435ae0b8cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Provider Factory Desing Pattern in .Net Core]]></title>
            <link>https://yucelarts.medium.com/provider-factory-desing-pattern-in-net-core-29b6b02783a7?source=rss-226933b4b93d------2</link>
            <guid isPermaLink="false">https://medium.com/p/29b6b02783a7</guid>
            <category><![CDATA[desing-pattern]]></category>
            <category><![CDATA[multitenancy]]></category>
            <category><![CDATA[multiple-provider]]></category>
            <category><![CDATA[dynamic-programming]]></category>
            <category><![CDATA[factory-pattern]]></category>
            <dc:creator><![CDATA[Semih Yücel]]></dc:creator>
            <pubDate>Fri, 16 Aug 2024 14:31:26 GMT</pubDate>
            <atom:updated>2024-08-16T14:35:47.918Z</atom:updated>
            <content:encoded><![CDATA[<h3>Provider Factory Desing Pattern in .Net Core</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*VgeOGga2q8sl-9dn" /></figure><p>Today, flexibility and maintainability in software development processes play a critical role in the success of a project. For this purpose, design patterns provide a powerful structure for software developers. In this article, we will examine the Provider Factory Design Pattern, which is used to create a flexible and manageable software architecture.</p><p>In particular, we will discuss how our IEngineProviderFactory class manages different SMS providers. We use two different SMS providers in our project: SmsOneClientService and SmsTwoClientService. These providers can be configured for different situations and needs. With the IEngineProviderFactory, it is possible to dynamically determine which provider to use.</p><p>This pattern can help you manage providers more flexibly in your projects and make your code more modular. Now, let’s take a closer look at how we implemented this pattern.</p><p>I have a model named EndpointOptions for IProviderFactory.</p><p>This model is populated in the MiddleWare layer during my request and distributed to other services.</p><p>In the examples I gave you can overcome this without using any model.</p><p>My solution is to specify the ProviderType when the request is received and access this information during the lifecycle of the request.</p><pre>public enum ProviderType<br>{<br>    KNOWN = 0,<br>    SMSONE= 1,<br>    SMSTWO = 2,<br><br>}<br>public class EndpointOptions<br>{<br>    public int providerType { get; set; }<br>    //.....<br>    //.....<br>}</pre><pre>//DefaultMiddleware.cs<br><br>var X_COMPANY_NAME=httpContext.Request.Headers[&quot;X-COMPNAY-NAME&quot;].ToString();<br>var endpointOptionsService = scope.ServiceProvider.GetRequiredService&lt;IEndpointOptionsService&gt;();<br>var _endpointOptions = await endpointOptionsService.GetEndpointOptionsAsync(X_COMPANY);<br>//Get the sms provider information I want according to the company information<br><br>var tenantProvider = httpContext.RequestServices.GetService(typeof(IOptions&lt;EndpointOptions&gt;)) as IOptions&lt;EndpointOptions&gt;;<br>// set providerType id<br>tenantProvider.Value.providerType = _endpointOptions.providerType; <br>//.....<br>//.....<br></pre><p>I get the X_COMPANY_NAME parameter from httpHeader. if this parameter is empty, it may give an error or you can change it to another parameter that suits you.</p><p>With the IEndpointOptionsService class I have prepared, I pull the information to fill my model. In this class, the method named GetEndpointOptionsAsync allows me to get my settings to the model by connecting to NOSQL or SQL.</p><pre><br>//I am defining the service so that I can use EndpointOptions<br>builder.Services.TryAddSingleton&lt;EndpointOptions&gt;();<br><br><br>builder.Services.AddScoped&lt;SmsOneClientService&gt;();<br>builder.Services.AddScoped&lt;SmsTwoClientService&gt;();<br><br>//When IEngineProviderFactory wants to be used, I specify which provider to continue with.<br>builder.Services.AddScoped&lt;IEngineProviderFactory&gt;(sp =&gt;<br>            {<br>                var endpointOptions = sp.GetService(typeof(IOptions&lt;EndpointOptions&gt;)) as IOptions&lt;EndpointOptions&gt;;<br>                switch ((ProviderType)endpointOptions.Value.providerType)<br>                {<br>                    case ProviderType.SMSONE: return sp.GetRequiredService&lt;SmsOneClientService&gt;();<br>                    case ProviderType.SMSTWO: return sp.GetRequiredService&lt;SmsTwoClientService&gt;();<br>                    default: throw new NotImplementedException($&quot;Provider type is not implemented.&quot;);<br>                }<br><br><br>            });</pre><p>After configuring this section, we will need to define the following service DI services for ServiceCollection.</p><p>When you want to use IEngineProviderFactory, it will direct you to the provider you want to use according to the parameter you want from the IOptions&lt;EndpointOptions&gt; model.</p><blockquote>Note:You can choose which Provider you want to use from Request Heder without using any OptionsModel.</blockquote><h3>See you in my next article …</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*x4gRs3hJPf9eh2eO" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29b6b02783a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Path Manipulation in .Net]]></title>
            <link>https://yucelarts.medium.com/path-manipulation-7aa57d5ef9b0?source=rss-226933b4b93d------2</link>
            <guid isPermaLink="false">https://medium.com/p/7aa57d5ef9b0</guid>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[net-core]]></category>
            <category><![CDATA[path-manipulation]]></category>
            <category><![CDATA[file-attack]]></category>
            <category><![CDATA[file-transfer]]></category>
            <dc:creator><![CDATA[Semih Yücel]]></dc:creator>
            <pubDate>Sun, 07 Jul 2024 19:08:36 GMT</pubDate>
            <atom:updated>2024-07-08T07:49:21.054Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RNMmemTvtWDYUf3MgN5yjw.png" /></figure><p>Path Manipulation vulnerability occurs when file and directory paths are not securely created and validated. User inputs or variables can manipulate file paths, leading to security vulnerabilities. Among the steps we have written below, the most important one is the <strong>CheckSystemFolders </strong>section.</p><p>To resolve this error, you can follow the steps below:</p><ul><li><strong>Path.Combine</strong>: Creating Secure File Paths: When combining file paths, use the Path.Combine method to create secure paths..</li><li><strong>Invalid Character Check</strong>: Check for invalid characters in file and directory paths.</li><li><strong>Path.GetFullPath:</strong> Use Path.GetFullPath to obtain the full file path and ensure that this path is under the expected root directory.</li><li><strong>Whitelisted Directory</strong>:The WhitelistedDirectories list contains directories where write operations are allowed. You can add other permitted directories to this list.</li><li><strong>NormalizePath Method</strong>:This method converts the file path to a full path, gets the local file path, removes directory separator characters, and checks for dangerous paths (..).</li><li><strong>CheckSystemFolders</strong>:Before the WriteAllBytes operation, you can prevent writing to system folders (e.g., the Windows folder) by checking file paths. If the file path matches one of the system folders, you can halt the operation.</li></ul><pre>   private static readonly List&lt;string&gt; WhitelistedDirectories = new List&lt;string&gt;<br>    {<br>        @&quot;C:\AllowedPath1&quot;,<br>        @&quot;C:\AllowedPath2&quot;,<br>        // Add other allowed directories here<br>    };</pre><p><strong>Whitelisted Directory</strong>:</p><ul><li>The WhitelistedDirectories list contains directories where write operations are allowed. You can add other permitted directories to this list.</li></ul><pre> private static string NormalizePath(string path)<br>    {<br>        if (string.IsNullOrWhiteSpace(path))<br>        {<br>            return null;<br>        }<br><br>        string normalizedPath = Path.GetFullPath(new Uri(path).LocalPath)<br>                                 .TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);<br><br>        if (normalizedPath.Contains(&quot;..&quot;))<br>        {<br>            return null;<br>        }<br><br>        return normalizedPath;<br>    }</pre><p><strong>NormalizePath Method</strong>:</p><ul><li>This method converts the file path to a full path, gets the local file path, removes directory separator characters, and checks for dangerous paths (..).</li></ul><pre>    private static bool IsPathWhitelisted(string path)<br>    {<br>        return WhitelistedDirectories.Any(whitelistedDir =&gt;<br>            path.StartsWith(NormalizePath(whitelistedDir), StringComparison.OrdinalIgnoreCase));<br>    }</pre><p><strong>IsPathWhitelisted Method</strong>:</p><ul><li>This method checks whether the given file path points to a system folder. If the file path points to a system folder, it throws an UnauthorizedAccessException.</li></ul><pre>    public static void FileWriteWithWhitelist(string path, byte[] data)<br>    {<br>        if (string.IsNullOrWhiteSpace(path))<br>        {<br>            throw new ArgumentNullException(nameof(path), &quot;File path cannot be null or empty.&quot;);<br>        }<br><br>        if (data == null)<br>        {<br>            throw new ArgumentNullException(nameof(data), &quot;Data cannot be null.&quot;);<br>        }<br><br>        string normalizedPath = NormalizePath(path);<br>        if (normalizedPath == null || !IsPathWhitelisted(normalizedPath))<br>        {<br>            throw new UnauthorizedAccessException(&quot;Attempt to write to a non-whitelisted directory.&quot;);<br>        }<br><br>        File.WriteAllBytes(normalizedPath, data);<br>    }</pre><p><strong>FileWriteWithWhitelist Method</strong>:</p><ul><li>This method takes the file path and data as parameters. It checks if the file path is in the whitelist and performs the write operation only in permitted directories.</li></ul><pre>    private void CheckSystemFolders(string path)<br>    {<br>        string fullPath = Path.GetFullPath(path).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);<br>        string windowsPath = Environment.GetFolderPath(Environment.SpecialFolder.Windows).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);<br>        string systemPath = Environment.GetFolderPath(Environment.SpecialFolder.System).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);<br>        string systemX86Path = Environment.GetFolderPath(Environment.SpecialFolder.SystemX86).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);<br>        string programFilesPath = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);<br>        string programFilesX86Path = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);<br><br>        if (fullPath.StartsWith(windowsPath, StringComparison.OrdinalIgnoreCase) ||<br>            fullPath.StartsWith(systemPath, StringComparison.OrdinalIgnoreCase) ||<br>            fullPath.StartsWith(systemX86Path, StringComparison.OrdinalIgnoreCase) ||<br>            fullPath.StartsWith(programFilesPath, StringComparison.OrdinalIgnoreCase) ||<br>            fullPath.StartsWith(programFilesX86Path, StringComparison.OrdinalIgnoreCase))<br>        {<br>            throw new UnauthorizedAccessException(&quot;Writing to system directories is not allowed.&quot;);<br>        }<br>    }</pre><p><strong>CheckSystemFolders Method</strong>:</p><ul><li>This method checks whether the given file path points to a system folder. If the file path points to a system folder, it throws an UnauthorizedAccessException.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7aa57d5ef9b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Privacy Violation: Heap Inspection]]></title>
            <link>https://yucelarts.medium.com/privacy-violation-heap-inspection-b9ab28c4a8ff?source=rss-226933b4b93d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9ab28c4a8ff</guid>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[penetration-testing]]></category>
            <category><![CDATA[net-core]]></category>
            <category><![CDATA[privacy-violation]]></category>
            <dc:creator><![CDATA[Semih Yücel]]></dc:creator>
            <pubDate>Thu, 27 Jun 2024 12:25:40 GMT</pubDate>
            <atom:updated>2024-07-07T19:16:50.495Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jwGvlIQY_omzR-jlrISeGA.jpeg" /></figure><p>Hassas bilgilerin (örneğin kullanıcı adı, şifre, kişisel kimlik numaraları) bellek yığınında uzun süre saklanmaması gerektiğini ifade eder. Bu tür bilgilerin bellek yığınında uzun süre kalması, potansiyel bellek dökümü ve bellek taraması saldırılarına karşı hassasiyet oluşturabilir.</p><p><strong>Bu sorunu çözmek için aşağıdaki önerileri dikkate alabilirsiniz:</strong></p><ol><li><strong>SecureString Kullanımı</strong>:</li></ol><ul><li>.NET’te hassas bilgileri saklamak için SecureString sınıfını kullanabilirsiniz. SecureString, hassas bilgileri bellek yığınında şifreli olarak saklar ve gerektiğinde bu bilgileri güvenli bir şekilde işleyebilir.</li><li>Ancak, dikkat edilmesi gereken bir nokta, SecureString sınıfının belirli API&#39;ler tarafından desteklenmesi gerektiğidir.</li></ul><p>2. <strong>Hassas Bilgileri Mümkün Olan En Kısa Sürede Temizleme</strong>:</p><ul><li>Hassas bilgileri kullanımdan hemen sonra bellekten temizlemek için gerekli adımları atın.</li></ul><p>Aşağıda, yukarıdaki kod bloğunda önerilen değişiklikler yer almaktadır</p><pre>using System;<br>using System.Runtime.InteropServices;<br>using System.Security;<br><br>public void LoginAndSetCookies()<br>{<br>    login.CookieContainer = new System.Net.CookieContainer();<br>    methods.CookieContainer = login.CookieContainer;<br><br>    SecureString secureUserId = ConvertToSecureString(userName);<br>    SecureString securePassword = ConvertToSecureString(passWord);<br><br>    login.wsLogin(ConvertToUnsecureString(secureUserId), ConvertToUnsecureString(securePassword), &quot;tr&quot;);<br><br>    // Hassas bilgileri kullanımdan hemen sonra temizleme<br>    secureUserId.Dispose();<br>    securePassword.Dispose();<br>}<br><br>private SecureString ConvertToSecureString(string str)<br>{<br>    if (string.IsNullOrEmpty(str))<br>        throw new ArgumentNullException(&quot;str&quot;);<br><br>    SecureString secureStr = new SecureString();<br>    foreach (char c in str)<br>    {<br>        secureStr.AppendChar(c);<br>    }<br>    secureStr.MakeReadOnly();<br>    return secureStr;<br>}<br><br>private string ConvertToUnsecureString(SecureString secureStr)<br>{<br>    if (secureStr == null)<br>        throw new ArgumentNullException(&quot;secureStr&quot;);<br><br>    IntPtr bstr = Marshal.SecureStringToBSTR(secureStr);<br>    try<br>    {<br>        return Marshal.PtrToStringBSTR(bstr);<br>    }<br>    finally<br>    {<br>        Marshal.ZeroFreeBSTR(bstr);<br>    }<br>}</pre><h3>Açıklamalar:</h3><p><strong>ConvertToSecureString ve </strong><strong>ConvertToUnsecureString Metodları</strong>:</p><ul><li>ConvertToSecureString: Bir string ifadesini SecureString ifadesine dönüştürür.</li><li>ConvertToUnsecureString: Bir SecureString ifadesini string ifadesine dönüştürür.</li></ul><p><strong>Hassas Bilgilerin Temizlenmesi</strong>:</p><ul><li>SecureString kullanılarak hassas bilgiler bellek yığınında şifreli bir şekilde saklanır.</li><li>Dispose metodu kullanılarak SecureString nesneleri kullanımdan hemen sonra bellekten temizlenir.</li></ul><p>Bu şekilde, hassas bilgilerin bellek yığınında düz metin olarak saklanmasını engelleyebilir ve bellek tarama saldırılarına karşı korunabilirsiniz.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9ab28c4a8ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handle Multiple Implementations of an Interface Using Delegates]]></title>
            <link>https://yucelarts.medium.com/handle-multiple-implementations-of-an-interface-using-delegates-463863d3a5a4?source=rss-226933b4b93d------2</link>
            <guid isPermaLink="false">https://medium.com/p/463863d3a5a4</guid>
            <category><![CDATA[delegation]]></category>
            <category><![CDATA[multitenancy]]></category>
            <category><![CDATA[net-core]]></category>
            <dc:creator><![CDATA[Semih Yücel]]></dc:creator>
            <pubDate>Thu, 19 Oct 2023 08:13:19 GMT</pubDate>
            <atom:updated>2023-10-19T18:05:45.345Z</atom:updated>
            <content:encoded><![CDATA[<p>This article clearly explains how to handle and manage multiple implementations of an interface in your project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LCen017-e4MXBU2LC98TeQ.png" /></figure><p>In some scenarios, we may need to choose which of our classes managed with the same interface should run.</p><p>I want to bring a different approach to this situation with the .Net Core architecture.</p><p>Sample Scenario;<br>I have an interface that I call <strong>IProviderFactory</strong>.<br>When we inject this interface into the project, we have classes that we want to manage.<br>These classes are my services consisting of <strong>RestApiClient</strong>, <strong>SqlClient</strong>, <strong>SoapClient</strong>.</p><p>So, by what methods can I determine which service my project will use when a request is sent by the user after making the additions?</p><p>One of my methods is to access my class by delegating.</p><p>Let’s add our class named StrategyClientService.cs to our project.</p><pre>    public delegate IProviderFactory StrategyClientService(ProviderType type);<br>   <br>    public enum ProviderType<br>    {<br>        SQL = 1,<br>        REST = 2,<br>        SOAP = 3<br>    }</pre><p>In the section where I add my dependencies in Program.cs, I add my classes to our project with dependency injection.</p><pre>  //IServiceCollection<br><br>  services.AddScoped&lt;SqlClientService&gt;();<br>  services.AddScoped&lt;CSharpClientService&gt;();<br>  services.AddScoped&lt;RestClientService&gt;();</pre><pre>    public interface IProviderFactory : IDisposable<br>    {<br>        Task&lt;object&gt; SendAsync(string prms);<br>        Task&lt;byte[]&gt; GetProviderAsync(string code);<br>        Task SetProviderAsync(byte[] bytes);<br>        void Add(KeyValuePair&lt;string, object&gt; pair);<br><br>    }</pre><p>Now it’s time to choose which provider to use when the request is sent.</p><p>Again, I add my scope for IServiceCollection as follows. This scope will work selectively when there is demand.</p><pre>services.AddScoped&lt;StrategyClientService&gt;(provider =&gt; (type) =&gt;<br>      {<br>          switch (type)<br>            {<br>              case ProviderType.SQL: return provider.GetRequiredService&lt;SqlClientService&gt;();<br>              case ProviderType.SOAP: return provider.GetRequiredService&lt;SoapClientService&gt;();<br>              case ProviderType.REST: return provider.GetRequiredService&lt;RestClientService&gt;();<br>              default: throw new NotImplementedException();<br>             }<br>       });</pre><p>Wonderful !. Now let’s see how we can use this event in our method in the controller.</p><p><em>Note; Usage management is now up to you. I will give a small example. For example, there are more than one provider. SMS provider or Mail provider. You can think of it as Multi Tenancy structures.</em></p><pre>        private readonly StrategyClientService _strategyClient;<br>        private static IProviderFactory _factory;<br>        public ExecuteController(StrategyClientService strategyClient)<br>        {<br>            _strategyClient = strategyClient;<br>        }<br><br>        [HttpGet(&quot;Test&quot;)]<br>        public async Task&lt;IActionResult&gt; Test()<br>        {    <br>            //SQL Client       <br>            _factory = _strategyClientService.Invoke(ProviderType.SQL);<br>            _factory.SendAsync(&quot;&quot;);<br>          <br>            //REST Client       <br>            _factory = _strategyClientService.Invoke(ProviderType.REST);<br>            _factory.SendAsync(&quot;&quot;);<br>        }</pre><p>Specifying which Provider to use is now a situation that can be managed according to your wishes. You can get this pamerte in the API header section here. or you can leave the default parameter.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=463863d3a5a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamic Rest Api Call in .Net Core]]></title>
            <link>https://yucelarts.medium.com/dynamic-rest-api-call-in-net-core-a5e40c234a3e?source=rss-226933b4b93d------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5e40c234a3e</guid>
            <category><![CDATA[dynamic-programming]]></category>
            <category><![CDATA[net-core]]></category>
            <category><![CDATA[http-client]]></category>
            <category><![CDATA[httpclientfactory]]></category>
            <category><![CDATA[rest-api]]></category>
            <dc:creator><![CDATA[Semih Yücel]]></dc:creator>
            <pubDate>Sun, 30 Apr 2023 11:17:39 GMT</pubDate>
            <atom:updated>2024-07-18T12:40:43.617Z</atom:updated>
            <content:encoded><![CDATA[<h3>Dynamic Rest Api Call in .Net Core</h3><p>In .NET Core projects, I have developed a structure that allows us to dynamically call REST services by using the REST API schemas we have defined beforehand and calling REST services according to our needs.</p><p>Let’s assume that we have a definition page where we enter the REST API endpoint information, header information, and body information. For example, the REST API JSON schema is as follows:</p><pre>&quot;{<br>  host: &#39;https://api.xxxxx.com&#39;,<br>  url: &#39;oauth2/token&#39;,                              <br>  method: &#39;Post&#39;,                              <br>  headers: {<br>              Authorization: &#39;Basic Base64_encode({YOUR_CLIENT_ID}:{YOUR_CLIENT_SECRET})&#39;,<br>              Accept: &#39;application/json&#39;,                                            <br>            },<br>              query_parameters: {<br>                                grant_type: &#39;password&#39;,<br>                                scope: &#39;{SCOPES}&#39;,<br>                                username: &#39;{YOUR_SERVICE_ACCOUNT_ID}&#39;,<br>                                password: &#39;{YOUR_SERVICE_ACCOUNT_SECRET}&#39;,<br>                                client_id: &#39;{YOUR_CLIENT_ID}&#39;,<br>                                client_secret: &#39;{YOUR_CLIENT_SECRET}&#39;<br>                                }<br>}&quot;</pre><p>This sample schema allows me to use my parameter information parametrically. However, if you want to change your body information per request, you can also define it here as you wish.</p><p>Moving on to the .NET Core section of my project, we can talk about the following structure and code block to manage HTTP requests more efficiently using the IHttpClientFactory structure:</p><pre>    public class IntegrationParameters:Dictionary&lt;string, string&gt; <br>    {<br><br>    }</pre><pre>    public class IntegrationRestApi<br>    {<br>        public readonly IntegrationParameters Parameters;<br>        private readonly IHttpClientFactory _httpFactory;<br>        private static JObject _json;<br>        private HttpMethod _method { get; set; }<br>        private string _HttpJsonSchema { get; set; }<br>        private string _requestUri { get; set; }<br>        private string _host { get; set; }<br><br>        public IntegrationRestApi(IHttpClientFactory httpClientFactory)<br>        {<br>            _httpFactory = httpClientFactory;<br>            Parameters = new IntegrationParameters();<br>        }<br>        public async Task&lt;T&gt; SendAsync&lt;T&gt;(string HttpJsonSchema)<br>        {<br>            //code block.<br>        }      <br><br>   }</pre><p>To check whether our submitted data is JSON or not, we will prepare our IsValidJson method and use it in our SendAsync method.</p><pre>        private static bool IsValidJson(string strInput)<br>        {<br>            if (string.IsNullOrWhiteSpace(strInput)) { return false; }<br>            strInput = strInput.Trim();<br>            if ((strInput.StartsWith(&quot;{&quot;) &amp;&amp; strInput.EndsWith(&quot;}&quot;)) || //For object<br>                (strInput.StartsWith(&quot;[&quot;) &amp;&amp; strInput.EndsWith(&quot;]&quot;))) //For array<br>            {<br>                try<br>                {<br>                    var obj = JToken.Parse(strInput);<br>                    return true;<br>                }<br>                catch (JsonReaderException jex)<br>                {<br>                    return false;<br>                }<br>                catch (Exception ex) //some other exception<br>                {<br>                    return false;<br>                }<br>            }<br>            else<br>            {<br>                return false;<br>            }<br>        }</pre><p>For now, since we will only use Post and Get functions, I want to give an example in those structures.</p><pre>public class IntegrationRestApi<br>    {<br>        public readonly IntegrationParameters Parameters;<br>        private readonly IHttpClientFactory _httpFactory;<br>        private static JObject _json;<br>        private HttpMethod _method { get; set; }<br>        private string _HttpJsonSchema { get; set; }<br>        private string _requestUri { get; set; }<br>        private string _host { get; set; }<br><br>        public IntegrationRestApi(IHttpClientFactory httpClientFactory)<br>        {<br>            _httpFactory = httpClientFactory;<br>            Parameters = new IntegrationParameters();<br>        }<br>        public async Task&lt;T&gt; SendAsync&lt;T&gt;(string HttpJsonSchema)<br>        {<br>            if (IsValidJson(HttpJsonSchema))<br>            {<br>                _HttpJsonSchema = HttpJsonSchema;<br>            }<br><br>            Parameters.ToList().ForEach(item =&gt;<br>            {<br>                _HttpJsonSchema = _HttpJsonSchema.Replace($&quot;{&quot;{&quot; + item.Key + &quot;}&quot;}&quot;, item.Value);<br>            });<br><br>            _json = JObject.Parse(_HttpJsonSchema);<br><br>            _method = new HttpMethod(_json.Value&lt;string&gt;(&quot;method&quot;).ToString());<br>            _requestUri = _json.Value&lt;string&gt;(&quot;url&quot;).ToString();<br>            _host = _json.Value&lt;string&gt;(&quot;host&quot;);<br><br>            var jsonHeaders = &quot;[&quot; + _json[&quot;headers&quot;].ToString() + &quot;]&quot;;<br>        }      <br><br>   }</pre><p>If our HttpJsonSchema is a json string we need to replace our sent variables with Parameters.<br>After our replace function is finished, we need to parse our json string document as json. Then, after creating my HttpClient class, you can call the post and get method of our project.<br>Finally, our IntegrationRestApi class will be as follows.</p><pre>public class IntegrationRestApi<br>    {<br>        public readonly IntegrationParameters Parameters;<br>        private readonly IHttpClientFactory _httpFactory;<br>        private static JObject _json;<br>        private HttpMethod _method { get; set; }<br>        private string _HttpJsonSchema { get; set; }<br>        private string _requestUri { get; set; }<br>        private string _host { get; set; }<br><br>        public IntegrationRestApi(IHttpClientFactory httpClientFactory)<br>        {<br>            _httpFactory = httpClientFactory;<br>            Parameters = new IntegrationParameters();<br>        }<br>        public async Task&lt;T&gt; SendAsync&lt;T&gt;(string HttpJsonSchema)<br>        {<br>            if (IsValidJson(HttpJsonSchema))<br>            {<br>                _HttpJsonSchema = HttpJsonSchema;<br>            }<br><br>            Parameters.ToList().ForEach(item =&gt;<br>            {<br>                _HttpJsonSchema = _HttpJsonSchema.Replace($&quot;{&quot;{&quot; + item.Key + &quot;}&quot;}&quot;, item.Value);<br>            });<br><br>            _json = JObject.Parse(_HttpJsonSchema);<br><br>            _method = new HttpMethod(_json.Value&lt;string&gt;(&quot;method&quot;).ToString());<br>            _requestUri = _json.Value&lt;string&gt;(&quot;url&quot;).ToString();<br>            _host = _json.Value&lt;string&gt;(&quot;host&quot;);<br><br>            var jsonHeaders = &quot;[&quot; + _json[&quot;headers&quot;].ToString() + &quot;]&quot;;<br>            using (HttpClient client = _httpFactory.CreateClient())<br>            {<br>                foreach (var header in JArray.Parse(jsonHeaders).Children&lt;JObject&gt;())<br>                {<br>                    foreach (JProperty parsedProperty in header.Properties())<br>                    {<br>                        client.DefaultRequestHeaders.Add(parsedProperty.Name, parsedProperty.Value.ToString());<br>                    }<br>                }<br>                client.BaseAddress = new Uri(_host);<br><br>                try<br>                {<br>                    var jsonParameters = &quot;[&quot; + _json[&quot;query_parameters&quot;].ToString() + &quot;]&quot;;<br>                    var prm = JArray.Parse(jsonParameters).Children&lt;JObject&gt;().FirstOrDefault();<br><br>                    if (_method == HttpMethod.Post)<br>                    {<br>                        var replaceContent = (from x in prm.Properties().AsEnumerable()<br>                                              select new KeyValuePair&lt;string, string&gt;(x.Name, x.Value.ToString())<br>                                              ).ToArray();<br>                        return await PostAsync&lt;T&gt;(replaceContent, client);<br><br>                    }<br>                    else if (_method == HttpMethod.Get)<br>                    {<br>                        var replaceContent = (from x in prm.Properties().AsEnumerable()<br>                                              select new string(string.Concat(x.Name, &quot;=&quot;, x.Value.ToString()))<br>                                    ).ToArray();<br>                        var queryString = string.Join(&quot;&amp;&quot;, replaceContent);<br>                        return await GetAsync&lt;T&gt;(queryString, client);<br>                    }<br>                    else<br>                        throw new ArgumentException(&quot;Method.Is.Not.Found&quot;);<br><br>                }<br>                catch (Exception ex)<br>                {<br>                    throw;<br>                }<br>                finally<br>                {<br>                    client.Dispose();<br>                }<br>            }<br>        }      <br><br>   }</pre><p>The Rest API Post and Get Functions are as follows</p><pre>        private async Task&lt;T&gt; PostAsync&lt;T&gt;(KeyValuePair&lt;string, string&gt;[] Content, HttpClient Client)<br>        {<br>            using (HttpResponseMessage responseMessage = Client.PostAsync(_requestUri, new FormUrlEncodedContent(Content)).Result)<br>            {<br>                responseMessage.EnsureSuccessStatusCode();<br>                if (typeof(T).FullName == &quot;System.String&quot;)<br>                {<br>                    return await responseMessage.Content.ReadFromJsonAsync&lt;T&gt;();<br>                }<br>                else<br>                {<br>                    return JsonConvert.DeserializeObject&lt;T&gt;(await responseMessage.Content.ReadAsStringAsync());<br>                }<br>            }<br>        }<br>        private async Task&lt;T&gt; GetAsync&lt;T&gt;(string QueryString, HttpClient Client)<br>        {<br>            _requestUri = $&quot;{_requestUri}/{QueryString}&quot;;<br>            using (HttpResponseMessage responseMessage = Client.GetAsync(_requestUri).Result)<br>            {<br>                responseMessage.EnsureSuccessStatusCode();<br>                if (typeof(T).FullName == &quot;System.String&quot;)<br>                {<br>                    return await responseMessage.Content.ReadFromJsonAsync&lt;T&gt;();<br>                }<br>                else<br>                {<br>                    return JsonConvert.DeserializeObject&lt;T&gt;(await responseMessage.Content.ReadAsStringAsync());<br>                }<br>            }<br>        }</pre><p>The Post and Get Functions are as follows. You can write your own function for the json post.</p><h3>xUnit TEST</h3><p>With xUnit Test you can test our project as follows.</p><pre>        public void IntegrationRest_Test1()<br>        {<br>            // Arrange<br>            var jsonParams = @&quot;{<br>                              host: &#39;https://api.xxxxx.com&#39;,<br>                              url: &#39;oauth2/token&#39;,                              <br>                              method: &#39;Post&#39;,                              <br>                              headers: {<br>                                Authorization: &#39;Basic Base64_encode({YOUR_CLIENT_ID}:{YOUR_CLIENT_SECRET})&#39;,<br>                                Accept: &#39;application/json&#39;,<br>                                //&#39;Content-Type&#39;:&#39;application/x-www-form-urlencoded&#39;,                                <br>                              },<br>                              query_parameters: {<br>                                grant_type: &#39;password&#39;,<br>                                scope: &#39;{SCOPES}&#39;,<br>                                username: &#39;{YOUR_SERVICE_ACCOUNT_ID}&#39;,<br>                                password: &#39;{YOUR_SERVICE_ACCOUNT_SECRET}&#39;,<br>                                client_id: &#39;{YOUR_CLIENT_ID}&#39;,<br>                                client_secret: &#39;{YOUR_CLIENT_SECRET}&#39;<br>                              }<br>                            }&quot;;<br><br><br><br>            // Act<br>            var httpClientFactoryMock = Substitute.For&lt;IHttpClientFactory&gt;();            <br>            var fakeHttpClient = new HttpClient();<br>            httpClientFactoryMock.CreateClient().Returns(fakeHttpClient);<br><br>          <br>            IntegrationRestApi rest = new IntegrationRestApi(httpClientFactoryMock);<br>            rest.Parameters.Add(&quot;YOUR_CLIENT_ID&quot;, &quot;6a9fdad4cf81faf6248d987804958673&quot;);<br>            rest.Parameters.Add(&quot;YOUR_CLIENT_SECRET&quot;, &quot;15867876b99ef6d798e897fa2b6b9d9c&quot;);<br>            rest.Parameters.Add(&quot;SCOPES&quot;, &quot;test&quot;);<br>            rest.Parameters.Add(&quot;YOUR_SERVICE_ACCOUNT_ID&quot;, &quot;9693bfc2-6089-43f5-935a-e91112b78a38&quot;);<br>            rest.Parameters.Add(&quot;YOUR_SERVICE_ACCOUNT_SECRET&quot;, &quot;0F9jihTZfYLb8mz+GtL3q35q4Q4ohijO29HMjifznv3iFs4sXz&quot;);<br><br>            var _res = rest.Send&lt;string&gt;(jsonParams);<br><br><br>            // Assert<br><br><br>        }</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5e40c234a3e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ConfigurationProvider’ı override ederek parametrelerimizi projemize dahil etmek.]]></title>
            <link>https://yucelarts.medium.com/configurationprovider%C4%B1-override-ederek-parametrelerimizi-projemize-dahil-etmek-53bf04e1d2df?source=rss-226933b4b93d------2</link>
            <guid isPermaLink="false">https://medium.com/p/53bf04e1d2df</guid>
            <category><![CDATA[configuration-provider]]></category>
            <category><![CDATA[cores]]></category>
            <category><![CDATA[net-core]]></category>
            <category><![CDATA[nets]]></category>
            <dc:creator><![CDATA[Semih Yücel]]></dc:creator>
            <pubDate>Fri, 18 Nov 2022 17:11:41 GMT</pubDate>
            <atom:updated>2022-11-18T17:25:10.517Z</atom:updated>
            <content:encoded><![CDATA[<h3>ConfigurationProvider’ı override ederek parametrelerimizi projemize dahil etmek. (I<strong>Configuration </strong>override)</h3><p>Bazen öyle ihtiyaçlar oluyor ki projemizde sadece <strong>app.config’</strong>den değil de <strong>veri tabanımızdan</strong> da parametreleri okusun istiyoruz aynı zamanda tüm parametrelerimize <strong>IConfiguration </strong>interface’i ile erişelim istiyoruz.</p><p>Bu gibi durumlarda <strong>ConfigurationProvider </strong>sınıfı bir nevi override ederek istediğimize ulaşabiliriz.</p><p>Bunun için öncelikle projemize <strong>Microsoft.Extensions.Configuration </strong>paketini eklememiz gerekmektedir. Çalışmamızı yapabilmek için de bir de class a ihtiyacımız bulunmaktadır.</p><p><strong>ConfigurationProvider </strong>isminde bir sınıf oluşturup <strong>Microsoft.Extensions.Configuration.ConfigurationProvider </strong>sınıfından <em>(Miras Alma / Kalıtım (Inheritance))</em> miras alıyoruz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*ho9btBYZswQtobe42-3RXQ.png" /><figcaption><em>Inheritance</em></figcaption></figure><p>Oluşturduğumuz sınıf içinde override edeceğimiz methodumu ekliyoruz</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/1*IAYmDsrOPfjzE1CQ2TXRlw.png" /><figcaption>override</figcaption></figure><p>Parametreleri veri tabanından çekeceğim için connectionString, tablo/view ismi ve where koşumu kullanabileceğim modelimi ekliyorum. (<em>Parametre tablomuzda çok fazla veri olduğu için her proje kendisine ait parametreleri alması için koşul ekledim.) </em>Bu Modelimin ismini <strong>ConfigurationOptions </strong>olarak belirledim. İkinci bir Model daha ekleyerek bunu <strong>IConfigurationSource </strong>Interface’inden miras alıyoruz. Parametrelerimiz yine aynı ancak <strong>construction </strong>içinde <strong>ConfigurationOptions </strong>modelinden gelen parametrelerle <strong>ConfigurationSource </strong>modelimi doldurmamız ve <strong>ConfigurationProvider </strong>build etmemiz gerekiyor.</p><p>Son eklediğimiz çalışmalara ne durumda bir bakalım.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*eprJaoxKJ9HCd2JP3r8sfQ.png" /><figcaption><strong>ConfigurationProvider.build</strong></figcaption></figure><p>Yapılandırma çalışmamıza yeni bir class daha ekleyerek <strong>ConfigurationExtensions </strong>oluşturuyoruz daha sonra <strong>AddConfiguration </strong>methodumuzu ekliyoruz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*WGXISc04H7dei__OHdv0vg.png" /><figcaption><strong>ConfigurationExtensions class</strong></figcaption></figure><p>Artık <strong>override</strong> ettiğimiz <strong>load()</strong> methodumuzu doldurabiliriz. Bu bir dll kütüphanesi olacağı için <strong>System.Data.SqlClient </strong>kullanarak veri tabanından parametrelerimizi alıp, set methodu ile parametrelerimize ekliyoruz. ihtiyacınıza göre load() mehtodunu düzenleyebilirsiniz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*jwdQNdmZ-2oe6ZGJ_Efv4w.png" /></figure><h3><strong>Oluşturulduğumuz yapılandırma sınıfını projemizde kullanımı</strong></h3><p>.net6.0 ve üstü versiyonlar için kullanımı ve .net 5.0 ve küçük versiyonlar için kullanımı aşağıdaki gibidir.</p><p>.net 5.0 ve küçük ve versiyonlarda</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*NqZ8-2yt5tQsOgj4mYCqyQ.png" /><figcaption>Startup.cs</figcaption></figure><p>.Net 6.0 ve büyük versiyonlarda</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*7oLdxsY4tmqtNzRHF2bPzw.png" /><figcaption>Program.cs</figcaption></figure><p>İyi Çalışmalar.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53bf04e1d2df" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[react-i18next ‘i Component Class ve Funciton Class da kullanımı]]></title>
            <link>https://yucelarts.medium.com/react-i18next-i-component-class-ve-funciton-class-da-kullan%C4%B1m%C4%B1-82beea872231?source=rss-226933b4b93d------2</link>
            <guid isPermaLink="false">https://medium.com/p/82beea872231</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[usetranslation]]></category>
            <category><![CDATA[i18next]]></category>
            <category><![CDATA[withtranslation]]></category>
            <category><![CDATA[i18n]]></category>
            <dc:creator><![CDATA[Semih Yücel]]></dc:creator>
            <pubDate>Tue, 21 Sep 2021 15:59:52 GMT</pubDate>
            <atom:updated>2023-11-19T11:16:15.535Z</atom:updated>
            <content:encoded><![CDATA[<p>Merhabalar, Eğer bir uygulama yazdıysak ve bu uygulama çoklu dil seçeneğini destekleyecekse burada işimizi kolaylaştıracak bazı kütüphaneler bulunmaktadır.</p><p>Bu yazımda sizlere <strong>react-i18next ‘i </strong>tanıtmaya çalışacağım.</p><p>bahsettiğimiz kütüphanemiz bu işi en iyi yapan kütüphanelerden birisidir ve son zamanlarda projelerimde sürekli kullanmaya başladım. <strong>i18next’i </strong>projemize <strong>npm install react-i18next </strong>kodu ile ekliyoruz. Sonra <strong>i18n.js </strong>adı ile index sayfamızı hazırlamamız gerekmektedir. Ben src klasörü altına <strong>i18n.js</strong> adı ile yeni bir js belgesi açarak için aşağıdaki kod ile doldurdum.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*hrqDnDzwutnhOVrMUMmbGQ.png" /><figcaption>i18n.js</figcaption></figure><p>kod bloğunun içindeki <strong>resource </strong>kısmını zaten görmüş olmalısınız. Ben çalışmamı o kısmında yaptım ancak bu dosya üzerinde uygulamamız yüklenirken herhangi bir api veya js dosyasını da referans gösterebilirsiniz. <strong>resource </strong>kod bloğumu aşağıdaki gibi değiştirdim.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*8Ls1G1vsRrAXhodE1U9N9A.png" /><figcaption>resource json</figcaption></figure><p>Genel olarak nesnelerimin ID’leri ve alacakları değerleri resimdeki gibi tutmayı seviyorum, burada isimlendirilmemiş bir nesne olursa FrontEnd tarafında hangisi olduğunu isim olarak bulması kolay oluyor ve daha kullanışlı olduğunu düşünüyorum.</p><p>Gelelim hazırlamış olduğumuz bu yapılı projemizde nasıl kullanacağımıza.</p><p>Projemizde <strong>Class Component </strong>ve <strong>Function Component</strong> olan bölümlerimiz olduğunu düşünelim ve öncelikle <strong>function component</strong> üzerinden ilerleyelim</p><h3>useTranslation (hook)</h3><p><strong>i18n’in </strong>bize sunmuş olduğunu yapıyı(useTranslation (hook)) kullanmamız gerekmektedir ve kullanımı bir o kadar basittir.</p><p>öncelikle class’ı <strong>useTranslation </strong>fonksiyonunu import etmemiz gerekmektedir. Daha sonra useTranslation’a erişebilmemiz için <strong>const { t} = useTranslation();</strong> tanımlamamızı yapmamız gerekmektedir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*BNok85R_xYTibjdnGXDVYA.png" /></figure><p>varsayılan olarak <strong>en </strong>dilini bıraktığımız sayfamız açıldığı zaman resource de ki <strong>sign_in_desc </strong>bilgisinin karşılığını verecektir. yani <strong>Enter your username and password</strong></p><p><strong>Function Component’lerde </strong>Kullanımı bu şekilde idi. birde <strong>Class Component’</strong>lerde ki kullanımına kısaca bakalım.</p><h3>withTranslation (HOC)</h3><p><strong>i18n’in </strong>bize sunmuş olduğunu bir diğer yapı ise (withTranslation (HOC)) dur. bu yapı ile Class Component’lerimiz de çoklu dil seçeneğini nasıl kullanabilir ona bakacağız.</p><p>Önlikle componentimize withTranslation yapınısı import etmemiz gerekmektedir. bunu için import { withTranslation } from ‘react-i18next’; yazmamız yeterlidir.</p><p>Daha sonra render bloğunun içinde <strong>const {t}=this.props;</strong> yardımı ile withTranslation a erişiyoruz ve kullanımı tıp function classda ki gibi. son olarak componentimizi erken <strong>withTranslation()(MyComponent); </strong>şeklinde export ediyoruz</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*ss_KDf0xqgHf5kIZhV9edg.png" /></figure><p>Dil seçeneğinde change işlemi yapmak için props tan aldığımız i18n fonksiyonunu bir arrow function içinde kullanarak bunu yapabilirsiniz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*r8ADz7tdZlaa52RGA1WvIw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*fkm5ffFQfe8pIKCCYuimGA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*fm9LFMrI3W7_gOg1rTenCg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82beea872231" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[.Net Core’da Kod Derleme ve Yürütme(Roslyn) Çalışması]]></title>
            <link>https://yucelarts.medium.com/net-coreda-kod-derleme-ve-y%C3%BCr%C3%BCtme-roslyn-%C3%A7al%C4%B1%C5%9Fmas%C4%B1-310f763e129f?source=rss-226933b4b93d------2</link>
            <guid isPermaLink="false">https://medium.com/p/310f763e129f</guid>
            <category><![CDATA[roslyn]]></category>
            <category><![CDATA[net-core-3]]></category>
            <category><![CDATA[compilers]]></category>
            <category><![CDATA[execute]]></category>
            <category><![CDATA[invoke]]></category>
            <dc:creator><![CDATA[Semih Yücel]]></dc:creator>
            <pubDate>Sun, 27 Dec 2020 09:17:18 GMT</pubDate>
            <atom:updated>2020-12-27T09:17:18.205Z</atom:updated>
            <content:encoded><![CDATA[<p>Merhabalar; Harici kod dosyalarını yazdığımız projelerde derleyebilme imkanı sunan <strong>CSharpCodeProvider</strong> .Net Core ile birlikte yerini <strong>Roslyn’</strong>ye bırakmaktadır.</p><p>Sistem alt yapısında bu kadar ciddi bir değişikliğe microsoft neden gitti bunun bir çok açılaması tabi ki bulunmaktadır. Bu açıklamalara girmeyeceğim(çok fazla makale zaten mevcut) sizleri .Net Fremwork ve .Net Core da code belgelerini nasıl derlersin bunlardan bahsedeceğim.</p><p>Klasik olarak .Net Fremwork 4.7.2 ile harici bir kod belgesini nasıl derleriz bir örnek vereceğim.</p><p><strong>CSharpCodeProvider </strong>ve <strong>CompilerParameters </strong>sınıflarından bir nesne türetmemiz gerekiyor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/1*yzSpC5khUeTlsjALbmURHA.png" /></figure><p>Burada öncelikle CSharpCodeProvider nesnesinden bahsetmek istiyorum. Microsoft.CSharp sınıfından türemektedir ancak bu hala geçerli olmakla beraber Microsoft.CodeDom.Providers.DotNetCompilerPlatform sınıfında da türeyebilmektedir. İkinci seçenek .Net Core 3.0&#39;a kadar da geçerli olduğu kaynaklarda bahsedilmiş ancak herhangi bir geçerliliği artık kalmamıştır.</p><p>İkinci olarak derlemek ve çalıştırmak istediğimiz kod belgesinde kullandığımız referansları ReferencedAssemblies ile add etmemiz gerekiyor ki proje içine yazdığımız nesneler sınıflarını bulabilsin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3n6LGhnhNDAIoRisUQJanA.png" /></figure><p>İhtiyacımız olan dll dosyalarını cp.ReferencedAssemblies.Add ile compiler’ımıza dahil ettik.</p><p>tekrar in memori ve compiler option seçeneklerimizi belirtmek istiyorum ve hata olması durumda bunları kullanıcıya gösterim derim.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2bTfZ_C3VGcShc87XLQ05A.png" /></figure><p>Son olarak hata olmaması durumda kod belgesindeki SetCS namespace altındaki SetCS clası içindeki metotlardan birisni çalıştırmayı ve sonu return etmeye bakalım.</p><p>Yukarıda verdiğim kodların sonuna aşağıdaki kodu eklediğiniz zaman Semih isimli metodun çalıştığı ve sonu <strong>s object </strong>nesnesine bastığını görebilirsiniz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*vZSCioI8qviHSMF3_hGKgA.png" /></figure><p>Şimdide bunu <strong>.Net Core </strong>da nasıl yaparız yine kabaca basit bir örnek vereceğim. yine aynı kod belgemizi kullanacak.(kod belgesini en aşağıda paylaşacağım.)</p><p>.Net core ile <strong>Roslyn </strong>hayatımıza girmiş bulunmaktadır. aynı kodları .Net core yazamaz mıyız diyeceksiniz evet yazabilirsiniz. ama kodları run etme kısmına geldiğiniz zaman <strong>platform için geçersiz çalıştırma/desteklenmeyen nesne </strong>gibi<strong> </strong>hata alacaksınız</p><p>projemize nuget olarak Roslyn ile hazırlanmış Microsoft.CodeAnalysis kütüphanesini eklememiz gerekmektedir.</p><p>ek olarak CSharpCompilation clasını incelemenizi tavsiye ediyorum,</p><p>burada dahili dll dosyarını MetadataReference.CreateFromFile ile projemize add etmemiz gerekiyor.</p><p>kodlarımızı .Net Core da kısaca aşağıdaki gibi</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uzxYoiCZ4L_TT9wpYuFj_w.png" /></figure><p>Son olarak taslak olarak kullandığım kod belgemi paylaşıyorum.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*BWRh3u5Y7n6Bh2nz-878Bg.png" /><figcaption>Sonuçları DataTable olarak dönen bir cs belgesi</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=310f763e129f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>