<?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 Selcuk Köse on Medium]]></title>
        <description><![CDATA[Stories by Selcuk Köse on Medium]]></description>
        <link>https://medium.com/@selcukmuh?source=rss-b22c67a51ab9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*hg_r_Rsfgc18_eu5w4Dgiw.jpeg</url>
            <title>Stories by Selcuk Köse on Medium</title>
            <link>https://medium.com/@selcukmuh?source=rss-b22c67a51ab9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 03:14:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@selcukmuh/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[Faster .Net With Concurrency]]></title>
            <link>https://medium.com/hepsiburadatech/faster-net-with-concurrency-63784bb51cba?source=rss-b22c67a51ab9------2</link>
            <guid isPermaLink="false">https://medium.com/p/63784bb51cba</guid>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Selcuk Köse]]></dc:creator>
            <pubDate>Sat, 13 Apr 2024 17:51:39 GMT</pubDate>
            <atom:updated>2024-04-18T15:27:10.867Z</atom:updated>
            <content:encoded><![CDATA[<h3>Faster .Net With Concurrency</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*58tmKnAfRda5kyiIgxmC_g.jpeg" /></figure><p>Have you ever struggle with your app’s performance? You tried to optimize your Database queries etc. but still the same problem? Maybe you are not using the full power your resources on your machine.</p><p>There is a full of resources on your machine like a treasury that is waiting to be fund somewhere. The key to unleash that power is “Concurrency and Asynchronous Programming”. My purpose by this article is showing you how you can boost your .Net apps by applying them.</p><p>.Net provide rich set of functions under <a href="https://learn.microsoft.com/en-us/dotnet/api/system.threading">System.Threading</a> and <a href="https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks">System.Threading.Tasks</a> namespaces, these namespace gives you ability to apply concurrency in your application.</p><p>For this article I have prepared a sample project and you can inspect that project for concrete examples:</p><p><a href="https://github.com/selcukkose/multithreading"><strong><em>https://github.com/selcukkose/multithreading</em></strong></a></p><h4>Different Paths To Create Threads</h4><p>The simplest way of creating a thread is creating an instance of Thread class like the following code:</p><pre>var t = new Thread(() =&gt;<br>{<br>    for (var i = 0; i &lt; 1000; i++)<br>    {<br>        Console.Write(&quot;x&quot;);<br>    }<br>});<br>t.Start();</pre><p>By creating an instance of Thread class we make sure a thread is created on the operating system and the given method is ran.</p><p>Creating a thread is a good way to make sure the program is not blocked until the operation is completed, but do you think it is the best way for this?Can we do it in a better way?</p><p>The problem with creating thread is the thread creation operation itself is a time consuming event and for the operation that is not complex enough it is even slower than synchronous version. If you don’t want to waste time by creating a new thread for your computation .Net has ThreadPool structure. ThreadPool has pre-created threads in it and when a new thread creation request received it uses one of the idle threads instead of creating a new one. By this way the program doesn’t spend time for creating a thread in the system.</p><p>A ThreadPool thread can be used in the following way:</p><pre>Task.Factory.StartNew(() =&gt;<br>{<br>    for (var i = 0; i &lt; 1000; i++)<br>    {<br>        Console.Write(&quot;x&quot;);<br>    }<br>});</pre><p>This way it is much more better but if the thread operation takes too much time then you would block one of the ThreadPool thread for a long time which is not good. At this case specifying TaskCreationOptions.LongRunning option as parameter in Task.Factory.Startnew method or using a new Thread would be better.</p><h4>Synchronization Between Threads</h4><p>When our code run on multiple threads and those threads try to update a value it might end up with wrong calculation result because the threads are not applying changes in order. To make all the running threads sync we need to use one of the Synchronization structure in .Net. We will inspect them one by one.</p><p>The first and the most known option is <strong>lock</strong><em>. </em>The lock mechanism is good enough for short locking operations but it needs to be used carefully with long operations because it uses loop to make other threads wait until the lock is released. You might also consider using <em>SpinLock </em>too if you have a few instructions to block.</p><p>Another option is using <strong>Mutex</strong><em> </em>for<em> </em>synchronization, the best property of Mutex it works in Operating System level and it also works even between processes. If more than one process use the same resource concurrently you have to use Mutex but problem with the Mutex is it is much more slower than other options. Because it is working in OS level and acquiring it requires more time.</p><p>I also want to mention <strong>Interlocked</strong> class here, it can be thought as syntactic sugar but it is more than that, because it handles variable volatility and locking mechanism for you and do what you ever want to do easily. It doesn’t provide interprocess locking so it’s not powerful as Mutex and you can think Interlocked class like lock.</p><h4>More Advanced Synchronization Options</h4><p>More than basic synchronization options .Net offers some more advanced structures to make complex synchronization operations easier and even possible. These options are working by signaling each other in various ways.</p><p>The first option is <strong>EventWaitHandle, </strong>this class provide signaling mechanism between threads to wait each other on certain point.</p><p>The <em>WaitOne </em>method of the EventWaitHandle class makes sure the current thread wait on the line until another thread realases the lock by calling <em>Set</em> method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/164/1*9kx0MsvxrrRWwsqB2cOqIA.png" /></figure><p>EventWaitHandle can be used in two different modes: ManualReset and AutoReset, the difference between those modes is AutoReset mode sets the value to the default when WaitOne method exectuted which is ManualReset doesn’t. For each modes seperate classes named <strong>AutoResetEvent</strong> and <strong>ManualResetEvent</strong> are available and they can be usable instead of providing modes as parameter.</p><p>EventWaitHandle is a good to make threads synchronized one by one, it is like making threads play ping pong together, do some job wait until another one do something and then continue etc. But you may also want them all do the work together and wait each other to make it done. To achieve this behaivour you can <strong>Barrier.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/309/1*SL_j4Ng_tNkpeWjzPz8gLg.png" /></figure><p>Similar behaviour can be done by using <strong>CountDownEvent </strong>but it gives more controls than Barrier. You can specify where to make the thread wait by using <em>Wait </em>method in CountDownEvent class when Barrier’s <em>SignalAndWait</em> method only signals and waits at the same line.</p><h4>Asynchronous Programming</h4><p>So far we have used creating new threads to make computing faster, do we always have to create a new thread or use another thread from thread pool divide our calculation and make it faster? Can we do something in the thread that we are already running on? Yes, we can, almost every program has some I/O bound calculations in it and we have to wait until the I/O operations are done in synchronous way.</p><p>To solve this problem <strong>Asynchronous Programming </strong>can be used, by this way when the .Net compiler see an operation that might take long time it doesn’t wait for it to be completed. It just starts it and continues to other operation that can be done without waiting.</p><p>To understand how async programming works exatcly let’s imagine you are preparing a table for dinner and you order a pizza, would you just sit and wait until the pizza comes? No, you can do other things like go to shop and by a coke and maybe prepare a salad etc. You would do other things instead of just waiting but be careful you are still one person there is no other person to help you with your job.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WcwADZp5WuEiWeLp5jnFWg.png" /></figure><p>.Net handles this ability by using state machine, it doesn’t create any thread for it.</p><h4>Task Parallel Library (TPL)</h4><p>Task Parallel Library (TPL) makes our life easier while working with multithreading in .Net. It provides 3 methods for that purpose:</p><p>Parallel.Invoke();</p><p>Runs given actions in parallel.</p><p>Parallel.ForEach(); and Parallel.For();</p><p>Runs actions given for the loop in parallel. We can easily think those loop work always faster than for and foreach loops but unfortunately it doesn’t work that way. If the operations in loop is not complex enough to use TPL it will be faster to use normal for and foreach loop otherwise using TPL methods would be even slower.</p><p>I’ve tried to make a overlook about .Net concurrency abilities and I hope it will be helpful to you, thanks for reading it :).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63784bb51cba" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hepsiburadatech/faster-net-with-concurrency-63784bb51cba">Faster .Net With Concurrency</a> was originally published in <a href="https://medium.com/hepsiburadatech">hepsiburadatech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying Container Images With Azure Container Registry(ACR)]]></title>
            <link>https://medium.com/@selcukmuh/deploying-container-images-with-azure-container-registry-acr-13b1768d28d7?source=rss-b22c67a51ab9------2</link>
            <guid isPermaLink="false">https://medium.com/p/13b1768d28d7</guid>
            <dc:creator><![CDATA[Selcuk Köse]]></dc:creator>
            <pubDate>Sat, 03 Jun 2023 12:06:36 GMT</pubDate>
            <atom:updated>2023-06-03T12:06:36.692Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m1eJjYUmfUE8LHD9cAl9DA.png" /></figure><p>Azure Container Registry allows us to store, build and deploy images on Azure. The main benefit of using ACR comparing to Docker Hub is storing images private and Azure integration, it allows us to publish our images easily with Azure Web Apps.</p><p>In this article I will share my experience with ACR. I assume you created a basic example app like and ASP.Net Core MVC app and you already created an Docker image for this app.x</p><p><strong>Build Your Image Locally</strong></p><p>To test your image locally first, you need to change your directory in the terminal to the directory that contains your Dockerfile and use following commands:</p><pre>docker build -t &lt;local_image_name&gt; .<br><br>docker run -d -p 8000:80 &lt;local_image_name&gt;</pre><p>By using “-p 8000:80” parameter in the commad, you specify inner and outer ports for the docker image. Docker deamon connects the app running inside the Docker container which is using port 80 to outside requests that comes for port 8000.</p><p>After running your Docker image you can test it on your localhost port 8000, your app should be running on the browser.</p><p><strong>Create Azure Container Registry</strong></p><p>We can create our Container Registry by using Azure Portal, Azure CLI or Azure Powershell, in this article we will use Azure CLI. In the Azure CLI we need to use the following command in our terminal.</p><pre>az acr create --resource-group &lt;resource_group_name&gt; --name &lt;container_registry_name&gt; --sku Basic</pre><p><strong>Push Your Image To Container Registry</strong></p><p>After creating Container Registry we need to login to it.</p><pre>az acr login --name &lt;container_registry_name&gt;</pre><p>Now we have a Container Registry available on the Azure and you can check it on the Azure Portal too. Now we need to push our image to our Registry. To achieve this we need to get “LoginServer” url of the Registry. We can get this URL from overview page of the Registry on the Azure Portal or we can use the following command on the terminal.</p><pre>az acr show --name &lt;container_registry_name&gt; --query &quot;loginServer&quot; </pre><p>Your Container Registry basicly have the following form on the Cloud:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PNb3tQ_NVau5H-moGXoZGA.png" /></figure><p>You have your newly created Registry and your Registry can container one or more Repositories which is Docker Images actually. Your Repositories can have one or more Artifacts too, you can think Artifatcs as versions of Repository.For our image we will have the following form:</p><p>&lt;login_server_url&gt;/&lt;repository_name&gt;:&lt;artifact&gt;</p><p>I will use artifact value as “v1” here, you can use repository_name as you want for example you can use “myapprepo”. To push our local image to Registry we need to connect our local image to Registry for this purpose we will use the following command:</p><pre>docker tag &lt;local_image_name&gt; &lt;login_server_url&gt;/&lt;repository_name&gt;:&lt;artifact&gt;</pre><p>Now we are ready to push our image to Registry:</p><pre>docker push &lt;loginservername&gt;/&lt;repositoryname&gt;:&lt;artifact&gt;</pre><p>After push operation is completed you can open “Repositories” under your Registry on Azure Portal, you will see a Repository with &lt;repository_name&gt; is created and when you click on the Repository, you will see the Artifact with &lt;artifact&gt; is created too. Now you successfully pushed your image to Container Reigstry.</p><p><strong>Deploy Your Image In The Container Registry</strong></p><p>To be able to deploy your image you need to enable “Admin User” feature on the Container Registry. To do this you need to navigate to “Overview” page on the Registry and click on “Update” button at the top. You will see “Admin User” property, enable it and click save.</p><p>After that go back to your Artifact under your Repository. When you right click on your Artifact you will see “Deploy to web app” option is enabled.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YDdrKYLPDxLemG4dgOnTTw.png" /></figure><p>Click on it to debloy your image on Azure Web App, you can fill required properties and publish your app easily.</p><p><strong>Updating And RePublishing Your Image</strong></p><p>When you publish your image with Web App in your Resources page you will see WebHook resource is created as well with your Web App resource.Webhook basicly connects Container Registry to Web App. When your Repository in the Container Registry is updated Webhook republish the image with Web App. By this way your change on the image will be automaticly deployed.</p><p>To update your image on the Container Registry do the following steps:</p><p>Make a change on your code for example change title in your home page.</p><p>Build your image locally:</p><pre>docker build -t &lt;local_image_name&gt; .</pre><p>Retag your local image to Registry Repository with docker tag (If you don’t apply this step Container Registry will not detect your change):</p><pre>docker tag &lt;local_image_name&gt; &lt;login_server_url&gt;/&lt;repository_name&gt;:&lt;artifact&gt;</pre><p>Push your changes again with docker push:</p><pre>docker push &lt;loginservername&gt;/&lt;repositoryname&gt;:&lt;artifact&gt;</pre><p>After pushing your image you can check your Artifact’s last update date and when you open your Webhook you will see new “push” action is created and your image will be updated on the Web App.</p><p>Happy Coding :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13b1768d28d7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Node.js TS Application Deployment with Docker Compose]]></title>
            <link>https://medium.com/@selcukmuh/node-js-ts-application-deployment-with-docker-compose-a49ae2312ae?source=rss-b22c67a51ab9------2</link>
            <guid isPermaLink="false">https://medium.com/p/a49ae2312ae</guid>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[node-js-tutorial]]></category>
            <dc:creator><![CDATA[Selcuk Köse]]></dc:creator>
            <pubDate>Thu, 14 Jul 2022 12:37:17 GMT</pubDate>
            <atom:updated>2022-07-17T07:47:40.848Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WweZfnHpBcdf2DTLryFBsQ.jpeg" /></figure><p>Today using Microservices artitechture spreading exponentionally and we are using different technologies for different services in a single application. With this development style our deployment effort getting higher, to make development easy one of the most useful tool is Docker Compose. So I will explain how to us it with Node.js app developed with Typescript.</p><p>Our application using MongoDB as database and its folder structure illustrated below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/286/1*TeHKN-a2whApYu-KAM_egg.png" /></figure><p>I assume you already installed required npm packages like mogoose, typescript and ts-node etc. to the project.</p><p>First we start with adding scripts that requiried to run our app with typescript to package.json file.</p><pre>&quot;scripts&quot;: {</pre><pre>&quot;buildts&quot;: &quot;npx tsc&quot;,</pre><pre>&quot;dev&quot;: &quot;npm run buildts &amp;&amp; node dist/app.js&quot;<br>}</pre><p>“buildts” command will build our typescript code to native javascript code and place them under ./dist folder, you can update the folder path or order setting in the tsconfig.json file in your app root folder. You can run “npm run dev” command to locally start up your app.</p><p>After checking your app is running correctly you can go on with creating “Dockerfile” file, this file is requiered to deploy your app with docker. The under this file will look like below</p><pre>FROM node:16</pre><pre>WORKDIR .</pre><pre>COPY package*.json ./<br>COPY tsconfig*.json ./</pre><pre>RUN npm config set unsafe-perm true<br>RUN npm install -g typescript<br>RUN npm install -g ts-node<br>RUN npm install<br>COPY --chown=node:node . .</pre><pre>RUN npm run buildts</pre><pre>COPY /dist .</pre><pre>EXPOSE 3000<br>CMD [ &quot;node&quot;, &quot;./dist/app.js&quot; ]</pre><p>“RUN npm config set unsafe-perm true” this line allows npm run other user’s previligies like “root” user and this required to run “tsc” command. Briefly installs requeired npm packages on the docker machine and run our “buildts” command so ./dist folder will be updated wild build javascript code and we can copy this code to the docker machine and then run it on port 3000. So easy right?</p><p>Now, you can run your app with docker using following commands:</p><pre>docker build -t your_app_name .</pre><pre>docker run -d your_app_name</pre><p>“your_app_name” is up to you can give any name to your app here.</p><p>If your app start running on docker properly then you are ready to create docker-compose.yml file under the Backend folder. This file be the upper path because multiple services will be inserted it. After creating the file will add docker-compose.override.yml file too. This file will be required to configure services that defined in the docker-compose.yml file.</p><p>Scripts in the docker-compose.yml file will look like below:</p><pre>version: &#39;3.4&#39;</pre><pre>services:<br> authenticationdb:<br>  image: mongo</pre><pre> service.authentication:<br>  image: service_authentication<br>  build:<br>   context: Services/Service.Authentication<br>   dockerfile: Dockerfile</pre><pre>volumes:<br> authentication_data:</pre><p>We defined a mongodb service with volume because our application need a mongodb database and we will make our service connected with this database.</p><p>Also docker-compose.override.yml file will look like below:</p><pre>version: &#39;3.4&#39;</pre><pre>services:<br> authenticationdb:<br>  container_name: authenticationdb<br>  restart: always<br>  ports:<br>   - &quot;27017:27017&quot;<br>  volumes:<br>   - authentication_data:/data/db</pre><pre> service.authentication:<br>  container_name: &quot;service.authentication&quot;<br>  restart: always<br>  environment:<br>   - MONGO_DB=authenticationdb<br>  depends_on:<br>   - authenticationdb<br>  ports:<br>   - &quot;3000:3000&quot;</pre><p>“restart: always” files ensure recreate a service when it is stopped.</p><p>“ports” indicate wich port will be used to run the application(left side of the colon indicates the port number that accessable from the out world to the app, right side indicates inner port used in the docker container.)</p><p>“enviroment” indicates enviroment variables will be given to the application while starting it we set MONGO_DB enviroment variable to authenticationdb because authenticationdb indicates ip adress of our mongodb database.</p><p>OK, we set our docker compose config and now we need to get our mongodb database’s ip address in the application to connect to it.</p><pre>import mongoose from &#39;mongoose&#39;;<br>import { logger } from &#39;../app.js&#39;;</pre><pre>const {<br>MONGO_DB<br>} = process.env;</pre><pre>export default new Promise((resolve, reject) =&gt; {</pre><pre> mongoose.connect(`mongodb://${MONGO_DB}:27017/Authentication`)<br> .then(() =&gt; {<br>  logger.info(&#39;Connected to mongodb successfully&#39;);<br>  resolve(true);<br> }).catch((err) =&gt; {<br>  logger.error(`Could not connect to mongodb, ${err}`);<br>  resolve(false);<br> })</pre><pre>})</pre><p>When we set “enviroment” variable in the docker-compose.override.yml file docker compose assign this variables to process.env in node.js app while starting it. So you can use this value in your mongodb connection string.</p><p>So we completed the article, I hope you liked this. 😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a49ae2312ae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Is Event Sourcing?]]></title>
            <link>https://medium.com/@selcukmuh/what-is-event-sourcing-f1a52ad376?source=rss-b22c67a51ab9------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1a52ad376</guid>
            <category><![CDATA[microservices-pattern]]></category>
            <category><![CDATA[event-sourcing]]></category>
            <category><![CDATA[microservice-architecture]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Selcuk Köse]]></dc:creator>
            <pubDate>Sun, 16 Jan 2022 13:25:29 GMT</pubDate>
            <atom:updated>2022-01-22T08:45:34.048Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XyfsXvlZgYVmLj_cRfAsXw.png" /></figure><p>In this article I will explain Event Sourcing Pattern which is a widely used pattern for microservice artitechtured applications nowadays. In otherside I think it will change your look to development and give you a new vision. I will endeavor to explain this topic to you in two steps.</p><p><strong>What is the problem?🤨</strong></p><p>Every pattern have born from a problem. Actually we use patterns because they are accepted solutions for specific problems and they will help us not to stuck on same problems again when we encounter. Then let’s try to understand what is the problem behind the Event Sourcing Pattern.</p><p>Let’s think about you are developing a food ordering app that customers order food from restaurants and rasturants prepare these orders in the kitchen and deliver to the customers.</p><p>How you would handle orders? You need to deliver these orders from customer to the restaruant’s kitchen and cookers will see these orders eventually and start making them. On the other hand orders may not stay same like when they first made, customers might add new food or might change ingrediants.</p><p>When we look from microservice perspective you would create a OrderService and a RestaurantService. You would create the order in the OrderService and send it to the RestaurantService in some way for example by using event queue. The best way handling changes on the orders would be using events, for example when order created OrderCreated event will be created and artitechture would look like below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jWWV3bLd8FC5AMGRDWO6VA.png" /></figure><p>Ok, now think that you are creating RestaurantService and you consume events from the OrderService via event queue and you wonder how to keep that data? In the traditional way you would directly create a table in the database and insert an record for each order, right?</p><p>But what about previous changes on the order? Because you are saving just current state of the order so you don’t know what was the previous state of the order. You can say what I would do with the previous state? Think about this, while you are doing some operation on the order some thing went wrong on the RestaurantService or another service then you need to drawback the order to the previous state. What you would do?</p><p>On the other hand you would have concurrency problem because you just updating one record and the order of multiple commands can affect the result of the record’s data.</p><p>Also you need to log the change to see what is happing. I know you can create an log table and write your logs to the table but actually there is better solution with Event Sourcing.</p><p>Ok, then let’s see the solution.</p><p><strong>What is the solution?🤔</strong></p><p>What if I say you don’t have to always keep one record for an order in the table? Well I know you need to have an order object to deal with it but actually you don’t need keep directly.</p><p>Think about what do you get when you consume the event queue? You get events right? Then what about you keep then directly not to keep as single object in the database. So you would have event stack not just an item so you can create your Order object by applying these events to the Order object in the constructor then you will get the Order object in the code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*5eKK2DmNX2TbHXp8ee2m0g.png" /></figure><p>In the programming perspective you need to write code like blove when ever you want to get the Order object.</p><pre>Order GetOrder(int orderID)<br>{</pre><pre>var order = new Order();</pre><pre>var eventList = GetOrderEvents(orderId);</pre><pre><em>foreach</em> (var event <em>in</em> eventList)<br>{<br>  order.ApplyEvent(event);<br>}</pre><pre><em>return</em> order;<br>}</pre><p>Isn’t this make some performance issues? Because whenever I want to get the Order object I might need to apply too much events to Order object. Of course there is solution for this. You can take snapshots of the events at sometimes then you will not apply the events before than this snapshot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*LFjKV5hXM3ly6O8pJMV8Bw.png" /></figure><p>I hope this article help you to understand this consept and thank you for reading.😊</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fel83s2IAkz8%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Del83s2IAkz8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fel83s2IAkz8%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/df7af1a1f6b53d248199745f34f27da8/href">https://medium.com/media/df7af1a1f6b53d248199745f34f27da8/href</a></iframe><figure><a href="https://www.buymeacoffee.com/selcukkose"><img alt="" src="https://cdn-images-1.medium.com/max/150/1*MUzuDsR6R3xmMTIBkX5ZPg.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1a52ad376" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[C# ref vs out vs in]]></title>
            <link>https://medium.com/@selcukmuh/c-ref-vs-out-vs-in-9ac8bc5aaa83?source=rss-b22c67a51ab9------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ac8bc5aaa83</guid>
            <category><![CDATA[c-sharp-programming]]></category>
            <dc:creator><![CDATA[Selcuk Köse]]></dc:creator>
            <pubDate>Thu, 30 Dec 2021 11:26:04 GMT</pubDate>
            <atom:updated>2022-01-16T14:03:34.155Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*heF3BHdrYHhhsCDp9SoMAw.jpeg" /></figure><p>In this artical I will explain differences between ref, out and in keywords in C#.</p><p>These keywords are used to pass paramters to methods as reference type. Then first of all we should know what is the refence type and value type. When we say “value type” we mean value of an object not itself, for example when pass an variable as a paramater to a method we just pass value of it not object itself. By using“reference types” as we pass a reference to method object’s reference not just value, so we have fully access to the object.</p><p>To see differences between “value” and “reference” types more obviously let’s see first example below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/1*8kFeGDQwL7QsYqxALPbv1A.png" /></figure><p>In this example the result will be 1 even if we set the value to 2 in the method because we are passing value as “value” type which the default behaviour ic C#.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/1*NkcE36f559dzuaOwcZSI1w.png" /></figure><p>But in this example the result will be 2 because we are passing value with “ref” keyword which is pass variable as reference to actual object not just value and then any change to the “a” variable in the method will effect the actual value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*nlXvuHkJ2PCK8tuuG_sLEQ.png" /></figure><p>output: 2</p><p>In this example, we are using “out” keyword instead of “ref” the result will same with “ref” keyword but there is little difference. As you can see we didn’t initilized vairable when we declare it and passed it directly to the method. <strong>This is the main difference between “ref” and “out” keywords that “ref” says this variable will be initilized to the compiler and the “out” will say this variable will be initilized in the method. You can think “out” as way of returning a value from a method. </strong>So you must initlize when you want to use “ref” otherwise you will recieve an error.</p><p>And you should notice<strong> “out will be faster than ref”.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/1*VaTmuScQYupzd-Ew6THzpA.png" /></figure><p>So what about “in”? Well “in” says okey I am passing parameter as a reference type but it is readonly and you can not change it. <strong>You can think it as “ref readonly”</strong></p><p>For summary these are all keywords to pass parameters as reference to methods. And you can use then to manage variable but for good programmic practice it is not a good to manupulate a variables value. If you want to do this right a method should return a value variable should be setted by this returned value.</p><p>Happy coding :)</p><figure><a href="https://www.buymeacoffee.com/selcukkose"><img alt="" src="https://cdn-images-1.medium.com/max/150/1*MUzuDsR6R3xmMTIBkX5ZPg.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ac8bc5aaa83" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Covariance and Contravariance in C# Delegates]]></title>
            <link>https://medium.com/@selcukmuh/covariance-and-contravariance-in-c-71f4482b036e?source=rss-b22c67a51ab9------2</link>
            <guid isPermaLink="false">https://medium.com/p/71f4482b036e</guid>
            <dc:creator><![CDATA[Selcuk Köse]]></dc:creator>
            <pubDate>Tue, 17 Aug 2021 18:23:51 GMT</pubDate>
            <atom:updated>2021-08-17T18:29:33.058Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yYqeVDkg8KHF8_zajSQUdA.jpeg" /></figure><p>Covariance and Contravariance are not generally concepts in programming but for Delegate types it makes your life much more comfortable.</p><p>First of all, if we want to explain what is that delegate in c#, it references methods. So we can assign an method to a method by defining an delegate which has same structure with the method.</p><p>Yes, delegate needs to be used with methods that should have same structure and this rule relative to both parameters and return types. But what if we want to assign an method to delegate like this:</p><pre>String ExampleMethod(FileStream s);</pre><p>to this:</p><pre>delegate Object ExampleDelegate(Stream s);</pre><p>In this example both parameters and return values does not have same type but as you can see Stream type in delegate’s parameter is parent class of FileStream class so this stuation valid for C# and we call this situation <strong>Contravariance</strong>.</p><p>On the other hand, delegate’s return type and assigned method’s return type does not match but Object is parent of String so this sutiuation valid too and it is called as <strong>Covariance.</strong></p><p>So we can do this:</p><pre>ExampleDelegate exDelegate = ExampleMethod;</pre><pre>exDelegate();</pre><p><em>But this kind of operations only available for reference types.</em></p><p>For example if our “ExampleMethod” would not be assign to “ExampleDelegate“ delegate if it has that signature:</p><pre>Int32 ExampleMethod(FileStream s);</pre><p>Because even if Int32 is an subclass of Object class it is an value type not reference type in C#.</p><p>I think this is an really important and useful information for all of us.</p><p>Happy coding :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71f4482b036e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flag Argument Nedir?]]></title>
            <link>https://medium.com/@selcukmuh/flag-argument-nedir-d98cb537e94?source=rss-b22c67a51ab9------2</link>
            <guid isPermaLink="false">https://medium.com/p/d98cb537e94</guid>
            <dc:creator><![CDATA[Selcuk Köse]]></dc:creator>
            <pubDate>Sun, 13 Sep 2020 09:45:05 GMT</pubDate>
            <atom:updated>2020-09-13T09:45:05.600Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RUGoE1RQGaxoSSmQC30_og.jpeg" /></figure><p>Flag Argument(Bayrak parametre) kod akışını yönlendirmek için kullanılan bir fonksiyon parametresidir. Genelde boolean tipte kullanılır. Mesela bilet alma işlemini uygulamak için çağırılan fonksiyonda iki seçenek olduğunu düşünelim biri Premium biri de normal. Bu seçeneklere göre farklı işlemler yapmak için fonksiyonunuzu yönlendirme amacıyla <strong>isPremium</strong> adında parametre gönderdiniz. Bu ilk başta sizin için gayet normal görünse de ikinci bir kişi bir kişi veya siz daha sonra dönüp koda baktığınızda bu parametrenin ne için olduğunu hatırlamayabilirsiniz. örneğin:</p><p>book(person, true)</p><p>bookPremium(person)</p><p>Sizce yukarıdaki fonksiyonlarda hangisi daha açık? İkinci kullanıma baktığınızda fonksiyonun işlevinin ne oldupu açıkca belli edilmiş ilk kullanımda ise true olarak verilen parametre ne amaçla verildiği açık değil. Bazı dillerde (örn. Python) parametreler isimleriyle birlikte kullanılabilir örneğin:</p><p>book(person, isPremium=true)</p><p>Bu tür bir kullanım daha açık ve biraz önce verdiğim örnekte fonksiyonu bookPremium ismiyle kullanmakla aynı işlevi görebilir.</p><h4>Karışık kodlama durumları</h4><p>Bazı durumlarda ise kodunuzu ayırmak pekte mümkün olmaz ve kod akışını bir “flag argument” ile ayırmak zorunda kalırsınız. Mesela aşağıdaki örneği ele alalım. aşağıdaki gibi iç içe girmiş kullanımlar bulunduran bir kodu farklı fonksiyonlara ayırmak kod tekrarı gibi istenmeyen sonuçlar doğurabileceğinden farklı fonksiyonlara bölmek akıllıca olmayacaktır.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/1*y6WaJXbDkJcZoQgcFMWLMQ.png" /></figure><p>Bu durumda kodumuzu basitleştirmek için aşağıdaki gibi asıl fonksiyonun uygulamasını soyutlaştıran fonksiyonlar kullanabiliriz. Bu fonksiyonlar normalde fonksiyonun bir boolean parametre ile çağırılması zorunluluğunu kaldırıp fonksiyonun kullanıcısı rahat bir arayüz sunuyor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*7m8Fmla1UnwDPow3asLSEg.png" /></figure><p>Bu tip uygulamalarla kodumuzun okunurluğunu arttırarak hem kodun tekrar kullanılabilirliğini (reusability) hemde sürdürülebilirliğini (maintainability) arttırabilirsiniz.</p><p>Zevkli kodlamalar dileğiyle :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d98cb537e94" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>