<?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 Yasin İlkalp Arabacı on Medium]]></title>
        <description><![CDATA[Stories by Yasin İlkalp Arabacı on Medium]]></description>
        <link>https://medium.com/@yasinilkalp?source=rss-f14ab38ac50d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*mFjTVKJe3gU42Biq8hT--w.jpeg</url>
            <title>Stories by Yasin İlkalp Arabacı on Medium</title>
            <link>https://medium.com/@yasinilkalp?source=rss-f14ab38ac50d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 03:02:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yasinilkalp/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[NodeJs, Playwright ve Upstash Redis ile Data Scraping]]></title>
            <link>https://yasinilkalp.medium.com/nodejs-playwright-ve-upstash-redis-ile-data-scraping-b7c00b57f2e?source=rss-f14ab38ac50d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7c00b57f2e</guid>
            <category><![CDATA[data-scraping]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[upstash]]></category>
            <category><![CDATA[playwrights]]></category>
            <category><![CDATA[redis]]></category>
            <dc:creator><![CDATA[Yasin İlkalp Arabacı]]></dc:creator>
            <pubDate>Mon, 13 Mar 2023 13:57:58 GMT</pubDate>
            <atom:updated>2023-03-13T13:57:58.866Z</atom:updated>
            <content:encoded><![CDATA[<p>Selamlar,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KpBpwXo1bpb1ck3g8KLgCg.png" /></figure><p>Konumuz her ne kadar <strong>Data Scraping</strong> de olsa bu yazıyı yazma motivasyonum aslında <strong>Upstash</strong> ile bişeyler yapmaktı. <strong>Upstash</strong> ile tanışmam <a href="https://www.youtube.com/watch?v=jciV3F8S3r0"><strong>şu</strong></a> video aracılığıyla oldu. Video çok güzel özetlediği için burada <strong>Upstash</strong>’den bahsetmeyeceğim. Benim hangi noktada ihtiyacım oldu ve nasıl bir sorunumu çözdü ondan konuşacağız.</p><p>Bu hafta üzerinde çalıştığım projede <strong>Trendyol</strong> <strong>kategori</strong> <strong>komisyon</strong> oranlarını almamız gerekti. <strong>Trendyol API</strong> bu bilgiyi bize vermediği için <strong>Satıcı paneli</strong>ndeki listeden bunları almak istedik. Bunun için <strong>e2e</strong> testlerimizi yazdığımız <strong>Playwright</strong> kütüphanesini kullanmaya karar verdik.</p><p>Daha önce <strong>Puppeteer</strong> ile benzer bir örnek yapmıştık. <a href="https://yasinilkalp.medium.com/puppeteer-ile-web-scraping-6f1dd5bc546c"><strong>Buradan</strong></a> o yazıyı da inceleyebilirsiniz.</p><p>Başlamadan önce neler yapacağımızı bir özetleyelim sonra da hangi dilleri ve toolları kullanacağımızdan bahsedelim.</p><p><strong>Trendyol Satıcı paneli</strong>nde <strong>3318</strong> Alt Kategorinin <strong>Komisyon</strong> oranlarına ihtiyacımız var. Bunun için siteyi <strong>tarayıp</strong> bu kategori oranlarının olduğu tabloyu <strong>json</strong> formatında kaydedeceğiz. Daha sonra bu veriyi kullanabilmek için bir <strong>API</strong> yapıp <strong>deploy</strong> edeceğiz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v-vjjB9t7uVcCilO1DxszA.png" /><figcaption>Trendyol Kategori Komisyonlarının olduğu Tablo</figcaption></figure><p><strong>Data Scraping</strong> için <strong>Playwright</strong> kütüphanesini kullanıp, bunu da <strong>Nodejs</strong> ile yazacağız. Çektiğimiz datayı <strong>Redis</strong>’e atıp, <strong>Nextjs</strong> ile basit bir <strong>API</strong> yapıp bitireceğiz. <strong>Data Scraping</strong> ve <strong>Nextjs</strong> projelerimizi <strong>github</strong> üzerinde tutup <strong>vercel</strong> <strong>deploy</strong> edeceğiz.</p><p>Hadi Başlayalım…</p><p>Bir komut satırı açalım ve <strong>nodejs</strong> projemizi aşağıdaki şekilde oluşturmaya başlayalım.</p><pre>mkdir trendyol-category-commission-scraper<br>cd trendyol-category-commission-scraper<br>npm init</pre><p>Projemizi oluşturduk bir ide ile açalım. <strong>VsCode</strong> kullanarak devam ediyorum ben. Projemizde kullanacağımız paketleri de yükleyelim.</p><pre>npm install playwright dotenv ioredis</pre><p><strong>index.js</strong> dosyası oluşturup yazmaya başlayalım. Öncelikle kullanacağımız kütüphaneleri <strong>import</strong> edip, kodlarımızı yazacağımız <strong>init</strong> function oluşturalım.</p><pre>require(&quot;dotenv&quot;).config();<br>const playwright = require(&quot;playwright&quot;);<br>const Redis = require(&quot;ioredis&quot;);<br><br>(async() =&gt; { <br>  // buraya kodlarımızı yazalım<br>})();</pre><p>İlk olarak <strong>partner.trendyol.com</strong> adresine giriş yapıp <strong>login</strong> olmamız gerekiyor. Bunun için <strong>onLogin</strong> adında bir fonksiyon yapıyoruz. Burada kullanacağımız <strong>Kullanıcı Email</strong> ve <strong>Şifre</strong>yi <strong>environment</strong> dosyasından alacağız. Sonraki aşamalarda bunu nasıl yapacağımızı göreceğiz.</p><pre>const onLogin = async (page) =&gt; {<br>  await page.goto(&quot;https://partner.trendyol.com/account/login&quot;, {<br>    waitUntil: &quot;domcontentloaded&quot;,<br>  });<br><br>  console.log(&quot;------------ E-posta adresini giriyoruz.&quot;);<br>  let emailInput = page.locator(&quot;div.email-phone input&quot;);<br>  await emailInput.fill(process.env.TRENDYOL_USERNAME);<br><br>  console.log(&quot;------------ Şifreyi giriyoruz.&quot;);<br>  let pwdInput = page.locator(&quot;div.password input&quot;);<br>  await pwdInput.fill(process.env.TRENDYOL_PASSWORD);<br><br>  console.log(&quot;------------ Giriş butonuna bastık.&quot;);<br>  let loginBtn = page.locator(&quot;button[type=submit]&quot;);<br>  await loginBtn.click();<br><br>  await delay(5000);<br>};</pre><p><strong>Login</strong> olduktan sonra <strong>partner.trendyol.com/incentive</strong> sayfasındaki kategori tablosundan <strong>komisyon oranları</strong>nı okuyacağız. Bunun içinde <strong>readTable</strong> adındaki fonksiyonumuzu oluşturuyoruz.</p><pre>const readTable = async (page, tableData, pageCount) =&gt; {<br>  let rowCount = await page<br>    .locator(&quot;div.g-table table tbody&quot;)<br>    .locator(&quot;tr&quot;)<br>    .count();<br>  for (let i = 0; i &lt; rowCount; i++) {<br>    let td = await page<br>      .locator(&quot;div.g-table table tbody&quot;)<br>      .locator(&quot;tr&quot;)<br>      .nth(i)<br>      .locator(&quot;td&quot;);<br>    tableData.push({<br>      mainCategory: await td.nth(0).innerText(),<br>      subCategory: await td.nth(1).innerText(),<br>      commission: await (await td.nth(2).innerText()).replace(&quot;% &quot;, &quot;&quot;),<br>    });<br>    console.log(`------------ ${pageCount}.sayfadan ${((pageCount - 1) * 50) + (i + 1)}. veriyi kaydettik.`);<br>  }<br>};</pre><p>Tablodaki <strong>pageSize</strong> <strong>50</strong> olarak <strong>set</strong> ettikten sonra <strong>67</strong> sayfaya bölüyor veriyi. Biz tabloyu her okuduktan sonra diğer sayfaya geçip orayı da okumamız lazım. Ta ki son sayfaya kadar. Bunun için <strong>nextPage</strong> adında bir fonksiyon oluşturuyoruz.</p><pre>const nextPage = async (page) =&gt; {<br>  let currentPage = await page<br>    .locator(&quot;div.pagination&quot;)<br>    .locator(&quot;div.g-button-group&quot;)<br>    .locator(&quot;button.-secondary&quot;)<br>    .innerText();<br>  const nextButton = await page.getByRole(&quot;button&quot;, {<br>    name: (parseInt(currentPage) + 1).toString(),<br>  });<br><br>  try {<br>    await nextButton.click();<br>    await delay(100);<br>    return true;<br>  } catch (error) {<br>    `enter code here`;<br>    return false;<br>  }<br>};</pre><p><strong>onLogin</strong>, <strong>readTable</strong> ve <strong>nextPage</strong> fonksiyonlarını oluşturduk. Bunları <strong>init</strong> fonksiyonu içinde aşağıdaki şekilde kullanıp bitiriyoruz artık.</p><pre>(async () =&gt; {<br>  const browser = await playwright.chromium.launch({<br>    headless: false,<br>  });<br>  const page = await browser.newPage();<br><br>  var isLogin = false;<br>  let tryLoginCount = 0;<br>  while (!isLogin) {<br>    console.log(&quot;------------ Login olmaya çalışıyoruz.&quot;);<br>    await onLogin(page);<br><br>    let url = await page.url();<br>    console.log(&quot;------------ Girdik mi?&quot;, url);<br>    isLogin = url == &quot;https://partner.trendyol.com/dashboard&quot;;<br>    tryLoginCount++;<br>    if (tryLoginCount === 4) return;<br>  }<br>  console.log(&quot;------------ Login olduk devam ediyoruz.&quot;);<br><br>  await page.goto(&quot;https://partner.trendyol.com/incentive&quot;);<br><br>  console.log(&quot;------------ Sayfalama 50lik datalara çekiyoruz..&quot;);<br>  await page.selectOption(&quot;div.change-size select&quot;, &quot;50&quot;);<br><br>  await delay(1000);<br><br>  var dataControl = true;<br>  var tableData = [];<br>  var pageCount = 1;<br>  while (dataControl) {<br>    await readTable(page, tableData, pageCount);<br>    dataControl = await nextPage(page);<br>    pageCount++;<br>  }<br><br>  console.log(&quot;------------ Verileri aldık. Redise kaydediyoruz.&quot;);<br><br>  let client = connectRedis();<br>  client.del(&quot;categories&quot;);<br>  client.set(&quot;categories&quot;, JSON.stringify(tableData));<br>  console.log(&quot;------------ Redise kaydettik.&quot;);<br><br>  await page.close();<br>  await browser.close();<br>})();</pre><p>Okuduğumuz verileri <strong>Redis’</strong>e aktaracağımız için <strong>connectRedis</strong> adında bir function oluşturuyoruz. <strong>Upstash</strong> üzerinden connection bilgilerini alabilirsiniz.</p><pre>const connectRedis = () =&gt; {<br>  let redisConfig = {<br>    uName: process.env.UPSTASH_REDIS_USERNAME,<br>    pwd: process.env.UPSTASH_REDIS_PASSWORD,<br>    host: process.env.UPSTASH_REDIS_HOST,<br>    port: process.env.UPSTASH_REDIS_PORT,<br>  };<br>  let client = new Redis(<br>    `rediss://${redisConfig.uName}:${redisConfig.pwd}@${redisConfig.host}:${redisConfig.port}/0`<br>  );<br>  return client;<br>};</pre><p>Unutmadan bir de yardımcı bir fonksiyonumuz olan delay fonksiyonu var. Bu da bazı işlemlerden sonra beklememize yardımcı oluyor. Onu da şöyle tanımlıyoruz.</p><pre>const delay = (ms) =&gt; new Promise((resolve) =&gt; setTimeout(resolve, ms));</pre><p>Evet artık komisyon oranlarını alacağımız projemizi bitirdik. Tüm her şeyi doğru yaptıysak kodumuzun son hali aşağıdaki gibi görünecektir.</p><pre>require(&quot;dotenv&quot;).config();<br>const playwright = require(&quot;playwright&quot;);<br>const Redis = require(&quot;ioredis&quot;);<br><br>const connectRedis = () =&gt; {<br>  let redisConfig = {<br>    uName: process.env.UPSTASH_REDIS_USERNAME,<br>    pwd: process.env.UPSTASH_REDIS_PASSWORD,<br>    host: process.env.UPSTASH_REDIS_HOST,<br>    port: process.env.UPSTASH_REDIS_PORT,<br>  };<br>  let client = new Redis(<br>    `rediss://${redisConfig.uName}:${redisConfig.pwd}@${redisConfig.host}:${redisConfig.port}/0`<br>  );<br>  return client;<br>};<br><br>(async () =&gt; {<br>  const browser = await playwright.chromium.launch({<br>    headless: false,<br>  });<br>  const page = await browser.newPage();<br><br>  var isLogin = false;<br>  let tryLoginCount = 0;<br>  while (!isLogin) {<br>    console.log(&quot;------------ Login olmaya çalışıyoruz.&quot;);<br>    await onLogin(page);<br><br>    let url = await page.url();<br>    console.log(&quot;------------ Girdik mi?&quot;, url);<br>    isLogin = url == &quot;https://partner.trendyol.com/dashboard&quot;;<br>    tryLoginCount++;<br>    if (tryLoginCount === 4) return;<br>  }<br>  console.log(&quot;------------ Login olduk devam ediyoruz.&quot;);<br><br>  await page.goto(&quot;https://partner.trendyol.com/incentive&quot;);<br><br>  console.log(&quot;------------ Sayfalama 50lik datalara çekiyoruz..&quot;);<br>  await page.selectOption(&quot;div.change-size select&quot;, &quot;50&quot;);<br><br>  await delay(1000);<br><br>  var dataControl = true;<br>  var tableData = [];<br>  var pageCount = 1;<br>  while (dataControl) {<br>    await readTable(page, tableData, pageCount);<br>    dataControl = await nextPage(page);<br>    pageCount++;<br>  }<br><br>  console.log(&quot;------------ Verileri aldık. Redise kaydediyoruz.&quot;);<br><br>  let client = connectRedis();<br>  client.del(&quot;categories&quot;);<br>  client.set(&quot;categories&quot;, JSON.stringify(tableData));<br>  console.log(&quot;------------ Redise kaydettik.&quot;);<br><br><br>  await page.close();<br>  await browser.close();<br>})();<br><br>const delay = (ms) =&gt; new Promise((resolve) =&gt; setTimeout(resolve, ms));<br><br>const onLogin = async (page) =&gt; {<br>  await page.goto(&quot;https://partner.trendyol.com/account/login&quot;, {<br>    waitUntil: &quot;domcontentloaded&quot;,<br>  });<br><br>  console.log(&quot;------------ E-posta adresini giriyoruz.&quot;);<br>  let emailInput = page.locator(&quot;div.email-phone input&quot;);<br>  await emailInput.fill(process.env.TRENDYOL_USERNAME);<br><br>  console.log(&quot;------------ Şifreyi giriyoruz.&quot;);<br>  let pwdInput = page.locator(&quot;div.password input&quot;);<br>  await pwdInput.fill(process.env.TRENDYOL_PASSWORD);<br><br>  console.log(&quot;------------ Giriş butonuna bastık.&quot;);<br>  let loginBtn = page.locator(&quot;button[type=submit]&quot;);<br>  await loginBtn.click();<br><br>  await delay(5000);<br>};<br><br>const readTable = async (page, tableData, pageCount) =&gt; {<br>  let rowCount = await page<br>    .locator(&quot;div.g-table table tbody&quot;)<br>    .locator(&quot;tr&quot;)<br>    .count();<br>  for (let i = 0; i &lt; rowCount; i++) {<br>    let td = await page<br>      .locator(&quot;div.g-table table tbody&quot;)<br>      .locator(&quot;tr&quot;)<br>      .nth(i)<br>      .locator(&quot;td&quot;);<br>    tableData.push({<br>      mainCategory: await td.nth(0).innerText(),<br>      subCategory: await td.nth(1).innerText(),<br>      commission: await (await td.nth(2).innerText()).replace(&quot;% &quot;, &quot;&quot;),<br>    });<br>    console.log(`------------ ${pageCount}.sayfadan ${((pageCount - 1) * 50) + (i + 1)}. veriyi kaydettik.`);<br>  }<br>};<br><br>const nextPage = async (page) =&gt; {<br>  let currentPage = await page<br>    .locator(&quot;div.pagination&quot;)<br>    .locator(&quot;div.g-button-group&quot;)<br>    .locator(&quot;button.-secondary&quot;)<br>    .innerText();<br>  const nextButton = await page.getByRole(&quot;button&quot;, {<br>    name: (parseInt(currentPage) + 1).toString(),<br>  });<br><br>  try {<br>    await nextButton.click();<br>    await delay(100);<br>    return true;<br>  } catch (error) {<br>    `enter code here`;<br>    return false;<br>  }<br>};</pre><p>Daha sonra projemize <strong>.env</strong> adında bir <strong>environment</strong> dosyası ekleyip aşağıdaki şekilde dolduruyoruz.</p><pre>TRENDYOL_USERNAME=xxxxxxxxxxx<br>TRENDYOL_PASSWORD=xxxxxxxxx<br><br>UPSTASH_REDIS_USERNAME=xxxxxxx<br>UPSTASH_REDIS_PASSWORD=xxxxxxxxxxxxxx<br>UPSTASH_REDIS_HOST=xxxxxxxxx<br>UPSTASH_REDIS_PORT=xxxx</pre><p>Geldik <strong>Upstash</strong> üzerinde <strong>Redis Db </strong>oluşturup, projemizdeki ayarlarımızı yapmaya…</p><p><strong>Upstash</strong>’e hala kayıt olmadıysanız <a href="https://console.upstash.com/login"><strong>buradan</strong></a> kaydınızı oluşturup <strong>console</strong> giriş yapalım. <strong>Free tier</strong> da <strong>1</strong> <strong>Redis</strong> <strong>db</strong> oluşturmamıza izin veriyor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nni0iXr0oQ3Ws2b-Gi772Q.png" /></figure><p><strong>Redis Db</strong> oluşturulduktan sonra sizi çok güzel bir <strong>dashboard</strong> ekranı karşılıyor. Bu ekranda <strong>connection</strong> bilgilerinizle beraber kullandığınız dillere göre kullanabileceğiniz kütüphaneleri de görebilirsiniz. Mesela biz <strong>nodejs</strong> tarafında <strong>ioredis</strong> kütüphanesini buradan görüp kullandık.</p><p>Yine <strong>Upstash CLI</strong> ile redis komutlarını da bu ekrandan çalıştırabiliyoruz. Ama benim en çok sevdiğim <strong>Data Browser </strong>ekranı oldu. Çok hızlı projemize bağlayıp buradan monitör edebiliyoruz.</p><p>Yeterince <strong>Upstash</strong> övdüğümüze göre artık projemizi çalıştırıp dataların <strong>Redis’</strong>e aktarıldığını görebiliriz.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplayer.vimeo.com%2Fvideo%2F807129161%3Fh%3D7105e73657%26app_id%3D122963&amp;dntp=1&amp;display_name=Vimeo&amp;url=https%3A%2F%2Fvimeo.com%2F807129161&amp;image=https%3A%2F%2Fi.vimeocdn.com%2Fvideo%2F1629979440-5295b5ca5387ea23cae64260894397474da988d27068cfe775477000c0dc0a13-d_1280&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=vimeo" width="1920" height="1200" frameborder="0" scrolling="no"><a href="https://medium.com/media/df39ba2cb6a9c0f8484a81224364ab10/href">https://medium.com/media/df39ba2cb6a9c0f8484a81224364ab10/href</a></iframe><p>Süper artık datalarımızı <strong>Redis</strong>’e kaydettik.</p><p>Şimdi bir <strong>Nextjs</strong> projesi yapıp buradaki verileri çekelim. Bunun için de <strong>Upstash</strong> bize çok yardımcı oluyor. <strong>Quickstarts</strong> menüsü altında hangi platformlarda nasıl kullanacağımızı adım adım tarif ediyor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E0x0Wbd1-_LT66T2TaV4fQ.png" /></figure><p>Burada anlatılanları tekrar yazmaya gerek yok. Github linklerini aşağıya bırakıyorum. Her iki projeyi de inceleyebilirsiniz.</p><p>Özetleyecek olursak; <strong>Web scraping</strong> ile ihtiyacımız olan veriyi alıp <strong>Redis’</strong>e kaydettik ve <strong>Redis</strong>ten datayı çekip bir <a href="https://trendyol-commission-api.vercel.app/api/category"><strong>API</strong></a> ile servis ettik. <strong>Upstash</strong> bu tür projelerde müthiş bir sadelik ve hız kazandırıyor.</p><ul><li><a href="https://github.com/yasinilkalp/trendyol-category-commission">GitHub - yasinilkalp/trendyol-category-commission</a></li><li><a href="https://github.com/yasinilkalp/trendyol-commission-api">GitHub - yasinilkalp/trendyol-commission-api</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7c00b57f2e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[C# Specification Pattern Nasıl Uygulanır?]]></title>
            <link>https://yasinilkalp.medium.com/c-specification-pattern-nas%C4%B1l-uygulan%C4%B1r-573cb6c0c77e?source=rss-f14ab38ac50d------2</link>
            <guid isPermaLink="false">https://medium.com/p/573cb6c0c77e</guid>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[specification-pattern]]></category>
            <category><![CDATA[net-core]]></category>
            <dc:creator><![CDATA[Yasin İlkalp Arabacı]]></dc:creator>
            <pubDate>Wed, 15 Jun 2022 11:03:01 GMT</pubDate>
            <atom:updated>2022-06-15T11:03:01.309Z</atom:updated>
            <content:encoded><![CDATA[<p>Selamlar,</p><p>En zorlandığım şey mevcut iş yoğunluğundan sıyrılıp kendime vakit ayırmak oluyor. Bu yüzden öğrendiğim her yeni bilgi için bir şeyler yazmaya çalışıyorum. Hem dönüp bakabilecek bir notum oluyor hem de motivasyonumu arttırıyor.</p><p>Şu an çalıştığım yerde her hafta bir konu hakkında sunum hazırlayıp bu vakti kendimize tanıyabiliyoruz. Bu da ekibin güncel teknolojiyi takip edebilmesini ve iş temposunda biraz nefes almasını sağlıyor.</p><p>Bu hafta <strong>Specification Pattern</strong> ile ilgili sunum hazırlamak ve bunu bir yazıya dökmek istedim. Bu aralar vakit buldukça <strong>go </strong>öğrenmeye çalışıyorum. Hem bu <strong>patterni </strong>daha iyi kavrayabilmek hem de <strong>go </strong>ile bir şeyler yapabilmek için bu yazıyı <strong>c#</strong> ve <strong>go </strong>için ayırmaya karar verdim. Ekip olarak .Net kullandığımız için bu yazıda <strong>Specification Patterni</strong> <strong>c#</strong> da nasıl uygularız buna bakacağız. Haydi başlayalım!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*s8uYzqSNytrwWlInwtZVAw.png" /></figure><h3><strong>Specification Pattern Nedir?</strong></h3><p><strong>Specification Pattern</strong> bir iş kuralının soyutlanıp tekrar tekrar kullanmamıza ve farklı iş kurallarıyla birleştirebilmemizi sağlayan bir yapıdır. Solid prensiplerinden <strong>Single responsibility (</strong>Tek sorumluluk<strong>) </strong>ilkesinin uygulanmasına yardımcı olur.</p><h4>Örnek Senaryomuz</h4><p><strong>Patterni </strong>bir örnek ile daha iyi kavrayabileceğimizi düşünüyorum. O yüzden basit bir senaryo üzerinde uygulamaya çalışalım. Senaryomuz şöyle;</p><p>Bizden<strong>; Nivea </strong>markalı, <strong>kritik stokta (5) olan</strong> ve 4<strong>0 TL altındaki</strong> ürünlerin listesi isteniyor.</p><p>Bu senaryoda <strong>Marka</strong>, <strong>stok </strong>ve <strong>fiyat filtresi</strong> uygulamamız gerekiyor. <strong>3 farklı iş kuralı</strong> tanımlayıp bunları birlikte nasıl kullanacağımıza bakalım.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ecb3f7a889a748a31351760a999ca04/href">https://medium.com/media/1ecb3f7a889a748a31351760a999ca04/href</a></iframe><p>Öncelikle <strong>ISpecification </strong>adında bir <strong>interface </strong>oluşturduk.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c64c97c43a8f2401da8d4e6def6faeb1/href">https://medium.com/media/c64c97c43a8f2401da8d4e6def6faeb1/href</a></iframe><p>Şimdi de <strong>interface </strong>kullanan bir <strong>abstract class </strong>oluşturduk. <strong>IsSatisfied</strong> metodu iş kuralımızın uygunluğunu kontrol ediyor. <strong>Expression</strong> metodu ise iş kuralını soyutlamamızı sağlıyor.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/89871958344ffd2fe7778050137b8424/href">https://medium.com/media/89871958344ffd2fe7778050137b8424/href</a></iframe><p><strong>ISpecificationOperator </strong>adında bir <strong>interface </strong>oluşturduk. Bu bizim <strong>specification</strong>ları birleştirmemize yarayacak operatorlerin <strong>arayüzüdür</strong>.</p><p>Örneğimizde kullanmak üzere <strong>AndOperator </strong>oluşturduk. Aynı şekilde <strong>Or</strong>, <strong>OrNot </strong>ve <strong>AndNot </strong>gibi operatorleri de yazıp kullanabiliriz.</p><p><strong>Operatorleri </strong>kolay kullanabilelim diye <strong>extension </strong>yapıp kullanıyoruz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8203c6b6712c1f5191aa3039b1192599/href">https://medium.com/media/8203c6b6712c1f5191aa3039b1192599/href</a></iframe><p>Yukarıda senaryomuza uygun <strong>3</strong> farklı <strong>specification </strong>görüyorsunuz. <strong>ProductBrandSpecification </strong>ile Marka filtreleyeceğiz. <strong>UnderCriticalStockSpecification </strong>ile Kritik stok altında kalanları filtreleyeceğiz. <strong>UnderSalePriceSpecification </strong>ile Belirli bir fiyat altında kalanları filtreleyeceğiz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c51d5abbf4e3bc43cca8d094600df2cb/href">https://medium.com/media/c51d5abbf4e3bc43cca8d094600df2cb/href</a></iframe><p><strong>ProductService </strong>oluşturduk. <strong>10 </strong>tane dummy data oluşturup bunları filtreleyeceğiz. <strong>GetProducts </strong>adında <strong>2 </strong>methodumuz var. Biri tüm datayı getiren diğeri de <strong>specification </strong>parametresi alan.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/16aa50141c1439cbecb061b52551cb1a/href">https://medium.com/media/16aa50141c1439cbecb061b52551cb1a/href</a></iframe><p>Artık <strong>Controller </strong>tarafında istediğimiz <strong>specificationları </strong>birleştirip bu servis aracılığıyla ürünlerimizi filtreleyebiliriz. Controller tarafı da yukarıdaki gibi görünecektir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*NCLQGQlMqMvL4aal6e1xRg.png" /></figure><p>Projemizi çalıştırdığımızda <strong>10 </strong>üründen bize <strong>Nivea </strong>markalı, <strong>5 adet</strong>in altında ve <strong>40 TL</strong> altındaki ürünleri getiren bir liste dönecektir.</p><p><strong>Specification Pattern</strong> ile iş kurallarını <strong>encapsulate </strong>ederek tekrar kullanılabilir kod blokları haline getirebiliriz. <strong>DRY </strong>(<a href="https://ceaksan.com/tr/dry-prensibi">Don’t Repeat Yourself</a>)<strong> </strong>prensibine uygun ve <strong>loosely coupled</strong> (gevşek bağlı) kod yazmamızı sağlar.</p><p>Uygulamanın kodlarını aşağıdaki <strong>github </strong>reposundan indirip inceleyebilirsiniz.</p><p><a href="https://github.com/yasinilkalp/SpecificationCode">GitHub - yasinilkalp/SpecificationCode</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=573cb6c0c77e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker Üzerine Jenkins Kurulumu]]></title>
            <link>https://yasinilkalp.medium.com/docker-%C3%BCzerine-jenkins-kurulumu-10ffd200b5e9?source=rss-f14ab38ac50d------2</link>
            <guid isPermaLink="false">https://medium.com/p/10ffd200b5e9</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[jenkins]]></category>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[docker-in-docker]]></category>
            <dc:creator><![CDATA[Yasin İlkalp Arabacı]]></dc:creator>
            <pubDate>Wed, 08 Jun 2022 08:47:18 GMT</pubDate>
            <atom:updated>2022-06-08T08:48:48.137Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*5uYrEF_ijR35cXXxSumSwg.png" /></figure><p>Bu yazıda <strong>Docker </strong>üzerine <strong>Jenkins </strong>kurulumundan bahsederken, <strong>Jenkinsi </strong>kurduğumuz <strong>container </strong>içinde <strong>docker </strong>işlemlerimizi nasıl yapacağız onlara değineceğiz.</p><p><strong>Jenkins Nedir?</strong></p><p><strong>Jenkins </strong>bir <strong>continous integration</strong> aracıdır. Yazılım geliştirme süreçlerimizi <strong>otomatize </strong>etmemize yardımcı olur. Daha hızlı ve güvenilir bir geliştirme süreci yaşamamızı sağlar diyebiliriz.</p><p><strong>Docker Nedir?</strong></p><p><strong>Docker </strong>en basit haliyle bir <strong>container </strong>teknolojisidir. Aynı işletim sistemi üzerinde birbirinden izole ve bağımsız <strong>container </strong>oluşturarak <strong>sanallaştırma </strong>sağlayan bir teknolojidir.</p><p><em>Docker’ın kurulu olduğunu varsayarak kurulum aşamalarını geçiyorum.</em></p><p><strong>Docker Compose</strong> yüklü değilse önce bunu yükleyerek başlayalım. Aşağıdaki adımları sırasıyla çalıştıralım.</p><pre>1- sudo curl -L &quot;https://github.com/docker/compose/releases/download/1.29.1/docker-compose-$(uname -s)-$(uname -m)&quot; -o /usr/local/bin/docker-compose<br>2- sudo chmod +x /usr/local/bin/docker-compose<br>3- sudo ln -s /usr/local/bin/docker-compose /usr/bin/docker-compose<br>4 - docker-compose --version</pre><p>Her şeyi doğru yaptıysak son adımda <strong>docker compose</strong> versiyonumuz yazacaktır.</p><p><strong>Jenkins </strong>Image indiriyoruz.</p><pre>docker pull jenkins/jenkins:lts</pre><p>Sırasıyla <strong>jenkins-home</strong> dizini oluşturuyoruz. <strong>jenkins </strong>dizine giriyoruz. ve bir <strong>docker-compose.yml</strong> dosyası oluşturuyoruz.</p><pre>mkdir ~/jenkins/home<br>cd ~/jenkins<br>nano docker-compose.yml</pre><p><strong>docker-compose.yml</strong> dosyamız aşağıdaki şekilde olmalıdır.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/41b1bb1a9a8947fa4474a539060a3c4c/href">https://medium.com/media/41b1bb1a9a8947fa4474a539060a3c4c/href</a></iframe><p>Buradaki yml üzerinde biraz duralım.</p><p><strong>Jenkinsi </strong>biz <strong>Docker </strong>üzerine kurucağız. Fakat <strong>Jenkins </strong>içinde de <strong>Docker </strong>komutlarını çalıştırmak istiyoruz. Peki Bunu nasıl yapacağız?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NAxd4aVG2O0KpKCRJX-Dtg.png" /></figure><p><strong>Deamon </strong>olarak çalışan bütün servisler <strong>Unix Socket</strong> arayüzü sunmaktadır. Bir <strong>Containerın daemon </strong>dinlemesini sağlayabilirsek <strong>Docker </strong>komutlarımızı bu <strong>Container </strong>içinde de çalıştırabiliriz. Bunu <strong>docker.sock </strong>ile yapabiliyoruz. <strong>Deamon </strong>yapacağı işleri <strong>docker.sock</strong> üzerinden alır. Biz yukarıdaki <strong>compose </strong>dosyamızda <strong>docker.sock</strong> mount ederek bu <strong>container </strong>içinde <strong>deamon </strong>dinlenmesini sağladık.</p><p>Aşağıdaki komutla <strong>compose </strong>dosyamızı çalıştırıyoruz.</p><pre>docker-compose up -d</pre><p>Ve Artık <strong>Jenkins Container</strong> oluştu. Tarayıcı açıp Ip ve Portumuzu girerek <strong>Jenkins </strong>ekranını görüyor olmamız lazım. <a href="http://192.168.10.14:8080/"><strong>http://192.168.10.14:8080</strong></a><strong> gibi…</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D_tXulRIJfZJqaQ1uA530A.png" /></figure><p><strong>/var/jenkins_home/secrets/initialAdminPassword</strong> bu dizin içerisindeki şifreyi ekrandaki alana girmemiz gerekiyor.</p><p>Dizine erişebilmemiz için öncelikle container içerisine girmemiz gerekiyor. Aşağıdaki komutları sırasıyla çalıştırınız.</p><pre>docker exec --user root -it jenkins /bin/bash<br>cat /var/jenkins_home/secrets/initialAdminPassword</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*98o7pjTvI2PSIu_j-P6OuA.png" /></figure><p>Şifremizi <strong>Jenkins </strong>ekranına girerek devam ediyoruz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KAhycMcFB8ORCDdD0sQ4oQ.png" /></figure><p>Önerilen eklentilerle devam edelim. <strong>Install suggested plugins</strong> butonuna tıklıyoruz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dfSC4wV63ZrVm5dKl2uYLw.png" /></figure><p>Eklentiler yüklenene kadar kısa bir süre bekliyoruz. Eklentiler yüklenmiyorsa büyük ihtimalle şifreyi yanlış yazdınız. Adımları tekrar kontrol edebilirsiniz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*IBObqgDrvESSbGhYzStQAQ.png" /></figure><p>Admin User oluşturup devam ediyoruz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kzAhz3wnQCXQ8HO5_IZf2A.png" /></figure><p><strong>Jenkins </strong>URL’mizi de olduğu gibi bırakıp <strong>Save And Finish</strong> butonuna basıyoruz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kb0HdBy1nYAF93GtmWeDjQ.png" /></figure><p><strong>Jenkins </strong>artık kullanıma hazır. Ve <strong>Jenkins </strong>container içinde <strong>Docker</strong> komutlarımızı çalıştırabiliyoruz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*Dw0rDx3Yt_6W4mzByLdehg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10ffd200b5e9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Nuget paketi hazırlama ve yayınlama]]></title>
            <link>https://yasinilkalp.medium.com/nuget-paketi-haz%C4%B1rlama-ve-yay%C4%B1nlama-c46fd418acd?source=rss-f14ab38ac50d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c46fd418acd</guid>
            <category><![CDATA[nuget-package]]></category>
            <category><![CDATA[c]]></category>
            <category><![CDATA[net-core]]></category>
            <category><![CDATA[package-management]]></category>
            <dc:creator><![CDATA[Yasin İlkalp Arabacı]]></dc:creator>
            <pubDate>Mon, 09 May 2022 18:32:28 GMT</pubDate>
            <atom:updated>2022-05-10T15:01:32.907Z</atom:updated>
            <content:encoded><![CDATA[<p>Projelerimizde benzer işleri sürekli yaptığımızda ve her projede tekrar tekrar aynı kodu yazdığımızda içimize düşen o sıkıntıyı hatırlayın. “<strong>Ben bunu her seferinde neden baştan yazıyorum?</strong>” ya da sürekli bir önceki projeden kodumuzu kopyaladığınızda <strong>“bir şeyi yanlış yapıyorum”</strong> hissini hatırlayın.</p><p>İşte bu durumlarda kodumuzu paketleyip tekrar tekrar kullanabilmemiz gerekiyor. Peki bunu nasıl yapacağız? İhtiyacımıza ve projemize göre paketimizi nasıl versiyonlarız ve kullanırız? Bu tür soruların cevaplarını anlatmaya çalışacağım.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*-eJVs4x5spQFngUUoBT8CQ.png" /><figcaption><a href="https://docs.microsoft.com/tr-tr/nuget/what-is-nuget">https://docs.microsoft.com/tr-tr/nuget/what-is-nuget</a></figcaption></figure><p><strong>.Net</strong> Projelerimizde sık sık kullandığımız <strong>Nuget Paket Yöneticisi</strong>ne kendi paketimizi nasıl oluşturup yayınlayacağımızı bir örnek üzerinden görelim.</p><h4><strong>Örnek Paket Senaryomuz</strong></h4><p><strong>.Net Framework 4.5</strong> ile yazılmış eski bir projemizin ve <strong>.Net Standart 2.0</strong> ile yazılmış başka bir projemizin olduğunu düşünelim. Şimdi öyle bir paket hazırlayalım ki her 2 projeye de ekleyebilelim ve kullanabilelim.</p><p>Paketimiz basitçe gelen <strong>T</strong> tipindeki modelimizi <strong>Serialize, Deserialize </strong>işlemlerini yapsın.</p><h4>Projemizi Yazmaya Başlayalım.</h4><p><strong>Dotnet Cli</strong> ile hızlıca bir <strong>Class library</strong> projesi oluşturup kodlamaya başlayalım.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fec429b967f09feada2cbae1ca38e0fb/href">https://medium.com/media/fec429b967f09feada2cbae1ca38e0fb/href</a></iframe><p><strong>SeriDeseri</strong> adında bir <strong>Class Library</strong> projesi oluşturduk. Sonra klasörün içine girip ihtiyacımız olacak <strong><em>Newtonsoft.Json</em></strong> NuGet paketini de projemize dahil ettik.</p><p>Projemizi açıp kodlamaya başlayalım.</p><p>Extensions adında bir class oluşturup aşağıdaki kodları yazalım.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d01fed00761a61d1358c7c9cb53d5ee/href">https://medium.com/media/8d01fed00761a61d1358c7c9cb53d5ee/href</a></iframe><p>Projemiz hazır artık paket ayarlarımızı yapabiliriz.</p><h4>NuGet Paketi Oluşturma</h4><p>Nuget paketimizi <strong>Dotnet Cli</strong>, <strong>Nuget.exe Cli</strong> ve ya <strong>MsBuild</strong> ile oluşturabiliriz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/342/1*Y6rBa3gicAy_BdhYZ8J4Ig.png" /></figure><p>Projeye çift tıklayıp <strong>csproj</strong> dosyasını editleyeceğiz. Aşağıdaki alanları kendinize göre doldurabilirsiniz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*CFuQMKHnKnFzxvSis8mdvA.png" /></figure><ul><li>Paketimizin hem <strong>netstandart2.0</strong> hem de <strong>net45</strong> frameworklerinde çalışmasını istiyoruz. <strong>TargetFrameworks</strong> kısmında bunu belirtiyoruz.</li><li><strong>PackageId</strong> alanına paketimizin adını yazıyoruz. <em>Unique</em> bir değer olmalıdır.</li><li>Paketimizin versiyonunu <strong>Version</strong> alanına yazıyoruz.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/549/1*o-nemr_KCSmODQVzhYAEeA.png" /></figure><ul><li>Projeyi oluşturduğunuzda Visual Studio’yu <strong>NuGet</strong> paketini otomatik olarak oluşturacak şekilde yapılandırabilirsiniz. (<strong>GeneratePackageOnBuild</strong>)</li></ul><p>Diğer tanımlamalar için <a href="https://docs.microsoft.com/tr-tr/nuget/create-packages/creating-a-package-msbuild">buraya</a> göz atabilirsiniz.</p><p>Paketimizi <strong>Dotnet CLI</strong> komutları ile oluşturacağız fakat <strong>Visual Studio</strong>’nun <strong><em>dotnet pack</em></strong> komutunu daha basit ve kullanışlı hale getirdiği context menüsündeki “<strong>Pack</strong>” komutuyla yapacağız.</p><blockquote><strong>Pack </strong>komutunu görmüyorsanız, projeniz büyük olasılıkla <strong>SDK </strong>stilinde bir proje değildir.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*-xq0v_LEaxyKFkASBFH8Aw.png" /></figure><p>Projemize sağ tıklayıp açılan menüden <strong>Pack</strong> sekmesini tıklıyoruz. Burada dikkat etmemiz gereken kısım projenin derleme işlemini hangi modda yaptığımız. <strong>Debug </strong>ve ya<strong> Release </strong>modda derlediğimiz projemizin paketlenmiş hali bin klasörünün içindeki <strong>Debug</strong> veya <strong>Release</strong> klasörü içinde oluşacaktır. <strong>NuGet</strong> paketleri <strong>.nupkg</strong> uzantılı bir <strong>ZIP</strong> dosyasıdır.</p><p>Artık elimizde yüklenmeye hazır bir <strong>NuGet</strong> Paketimiz var.</p><h4>NuGet Paketi Yükleme</h4><p>Paketimizi <strong>nuget.org</strong> sitesine üye olup yükleyeceğiz. Üyeliğiniz yoksa oluşturup giriş yapıyoruz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*qMJwv0ubJizM0-SuAR2InA.png" /></figure><p>Sağ üst menüden kullanıcı adımıza tıklayıp <strong>Upload Package </strong>diyoruz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Aj9RirSipBMZr4WsSZPt8Q.png" /></figure><p><strong>Browse </strong>tıklayıp <strong>.nupkg</strong> uzantılı paketimizi seçiyoruz. Yaptığımız ayarları burada görebiliriz. Eğer eksik ve ya hatalı bir şey yoksa en alttaki <strong>Submit </strong>butonuna tıklayarak paketimizi upload edebiliriz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZMr-CIv3IPfeb_B_D9THbg.png" /></figure><p>Paketimizin status kısmında <strong>Validating </strong>yazacaktır ilk yüklediğimizde. <strong>NuGet </strong>paketimizi bazı <strong>validasyon </strong>işlemlerinden geçirerek 5 -10 dk içinde yayına alacaktır. Paketimiz yayına alındığında status kısmında <strong>Listed </strong>yazacaktır.</p><blockquote>Paketin tüm doğrulama işlemlerinden geçmesi, arama sonuçlarına yansıması biraz zaman alabilir. Bu işlemlerden sonra<strong> e-posta</strong> adresinize bilgilendirme maili gelecektir.</blockquote><p>Artık Paketimizi <strong>NuGet Package Manager</strong>dan arayarak projelerimizde kullanabiliriz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/1*PrE5rNRlz6iorqsC1nulWg.png" /></figure><p>En basit ve yalın haliyle <strong>NuGet </strong>üzerinden paket oluşturma ve yayınlama işlemlerini anlatmaya çalıştım.</p><p>Bir sonraki yazımızda Paket versiyon yükseltme ve <strong>NuGet </strong>paketini <strong>Github </strong>üzerinden publish etmeyi göreceğiz.</p><p>Faydalı olması umuduyla…</p><p>Github üzerinden örneğimizi inceleyebilirsiniz.</p><p><a href="https://github.com/yasinilkalp/SeriDeseri">GitHub - yasinilkalp/SeriDeseri</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c46fd418acd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Puppeteer ile Web Scraping]]></title>
            <link>https://yasinilkalp.medium.com/puppeteer-ile-web-scraping-6f1dd5bc546c?source=rss-f14ab38ac50d------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f1dd5bc546c</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[puppeteer]]></category>
            <category><![CDATA[mongo]]></category>
            <dc:creator><![CDATA[Yasin İlkalp Arabacı]]></dc:creator>
            <pubDate>Sun, 26 Dec 2021 13:30:34 GMT</pubDate>
            <atom:updated>2021-12-26T17:03:48.466Z</atom:updated>
            <content:encoded><![CDATA[<h4>Puppeteer Nedir?</h4><p><strong>Puppeteer</strong>, Google tarafından geliştirilen bir <strong>node.js</strong> kütüphanesidir. <strong>Puppeteer, Chrome</strong> ile yapabildiğimiz tüm işlemleri taklit etmemize yarayan bir araçtır. <strong>Firefox</strong> için <a href="https://hacks.mozilla.org/2021/01/improving-cross-browser-testing-part-2-new-automation-features-in-firefox-nightly/#:~:text=To%20use%20Puppeteer%20with%20Firefox,to%20get%20up%20and%20running.">buraya</a>…</p><p><strong>Headless mode</strong> sayesinde arayüzü görmeden de tarayıcıdaki işlemleri taklit edebiliyor, daha az kaynak tüketerek daha hızlı testler koşabiliyoruz.</p><h4><strong>Neler Yapılabilir?</strong></h4><ul><li>Web uygulamalarımızın testlerini otomatikleştirebiliriz.</li><li>Web uygulamalarımızın ekran görüntülerini alabilir, bunları <strong>PDF</strong> ve <strong>JPG</strong> olarak kaydedebiliriz.</li><li>Web sitelerinden ihtiyacımız olan dataları çekebilir, formları otomatik doldurabiliriz.</li></ul><h4>Web Scraping İşlemi Nedir?</h4><p>Web sitelerinden bilgi toplama olarak tanımlayabiliriz. Bir çok dilde bu işlemle ilgili çeşitli kütüphaneler vardır.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*lzRF62aeT2oqOPpGHVWNEw@2x.jpeg" /></figure><p>Dolar kurunun çok oynak olduğu bugünlerde kurun karşılık geldiği yılda neler olmuş acaba diye merak ettim ve bunu bir hafta sonu projesine çevirdim.</p><p><strong>Peki bu proje için nelere ihtiyacım vardı.</strong></p><ul><li>Anlık Kur bilgisini çekecek bir servise</li><li>Tarihte bugün bilgisini veren bir servise</li><li>Bu iki servisi birleştirip sunan bir arayüze</li></ul><p>Kur bilgisini <strong>Merkez bankası</strong>ndan çekmek istemedim. Anlık alıp sürekli değişmesi projeyi daha canlı ve eğlenceli yapacaktı. Bu yüzden kur için <a href="https://openexchangerates.org/"><strong>Open Exchange Rates API</strong></a> servisini kullandım.</p><p>Tarihte bugün datasını çekebileceğim free bir <strong>API</strong> bulamadım. Bu araştırmalar en sonunda bu yazının konusu olan <strong>Puppeteer</strong> kütüphanesine yönlendirdi beni.</p><p><a href="https://tr.m.wikipedia.org/wiki/Vikipedi:Tarihte_bug%C3%BCn"><strong>Wikipedia Tarihte Bugün</strong></a> sayfasında yılın tüm günleri için <strong>Ölüm</strong>, <strong>Doğum</strong> ve <strong>Olay</strong> başlığı altında <strong>48 bin</strong>e yakın data vardı.</p><p>İşte biz bu yazıda datayı <strong>Wikipedia</strong>dan (ç)alıp bir <strong>API</strong> yazacağız.</p><p>Öncelikle bu proje için hangi teknolojileri ve kütüphaneleri kullandık, Nasıl bir yol izleyeceğiz bunlara bakalım.</p><p>2 <strong>Node.js</strong> uygulaması yazacağız. İlk uygulamamız <strong>Wikipedia</strong>dan dataları <strong>Puppeteer</strong> yardımıyla okuyacak ve <strong>Mongo</strong>’ya kaydedecek. Diğer uygulamamızda <strong>Mongo</strong>dan datayı alıp servis edecek.</p><p>Bu yazıda ilk uygulamamızı Nasıl yapacağımızı göreceğiz. Diğer uygulamayı da incelemek isterseniz diye yazının sonuna <strong>Github</strong> reposunu bırakıyorum.</p><p>Projeyi anladığımıza göre biraz kod yazalım.</p><p>Bir konsol açıp sırayla aşağıdaki işlemleri yapalım.</p><p><strong>mkdir</strong> puppeteer-example</p><p><strong>cd</strong> puppeteer-example</p><p>npm init</p><p>Boş bir proje oluşturduk. Veritabanımız için bir modele ihtiyacımız var. Bunun için <strong>models/history.js </strong>dosyamızı oluşturup, aşağıdaki şekilde düzenliyoruz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4bf6a2c2ce3430cd389259557913b7aa/href">https://medium.com/media/4bf6a2c2ce3430cd389259557913b7aa/href</a></iframe><p><strong>Mongo</strong> için <strong>mongoose</strong> kütüphanesini kullanacağız. <strong>Schema</strong> oluşturup modeli export ediyoruz.</p><p><strong>Veritabanı</strong> bağlantımız için de ana dizine <strong>db.js</strong> dosyamızı oluşturuyoruz. <strong>Url</strong> kısmı için kendi <strong>Mongo</strong> connection bilgilerimizi yazıyoruz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0769a030800f0ef78e8a371d9023d4c8/href">https://medium.com/media/0769a030800f0ef78e8a371d9023d4c8/href</a></iframe><p>Geldik şimdi <strong>Puppeteer</strong> kurulumuna. Kullandığınız paket yöneticiniz ile <strong>puppeteer</strong> ve <strong>puppeteer-core</strong> kütüphanelerini yüklüyoruz.</p><p><strong>npm</strong> i --save-dev <strong>puppeteer puppeteer-core</strong></p><p>Şimdi anadizine <strong>puppeteer.js</strong> adında bir dosya oluşturup aşağıdaki kodları yazalım.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/874e61352e51713562dbb77c579df689/href">https://medium.com/media/874e61352e51713562dbb77c579df689/href</a></iframe><p><strong>Puppeteer</strong> kütüphanesini, <strong>db.js</strong> ve<strong> history.js</strong> import ediyoruz.</p><p><strong><em>puppeteer.launch()</em></strong> ile <strong>browser</strong>ımızı tanımlıyoruz. Buradaki <strong>headless</strong> modu <strong>false</strong> yaptım ki işlemleri görebilelim. Çalıştığına emin olduktan sonra burayı <strong>true</strong> çekebiliriz.</p><p><strong><em>const</em></strong><em> page = </em><strong><em>await</em></strong><em> browser.newPage();</em> satırıyla yeni bir sekme açıyoruz. İşlemlerimiz bu sekmede yapacağız.</p><p><strong>Wikipedia</strong>da datalarımızı çekeceğimiz url <a href="https://tr.wikipedia.org/wiki/$%7Burl%7D#Olaylar">https://tr.wikipedia.org/wiki/<strong>1_Ocak</strong>#Olaylar</a> şeklinde olduğundan bizim <strong>Gün</strong> ve <strong>Ay</strong> yazan yeri dinamik değiştirip sayfayı <strong>scrape</strong> etmemiz lazım.</p><p>Bu yüzden yılın tüm günlerini bir for döngüsü içinde dönüyoruz.</p><p><strong><em>await</em></strong><em> page.goto(url); </em>satırıyla her dönüşte değiştirdiğimiz url gidiyoruz. Sayfadaki Dom’a direkt erişebiliyor olmamız lazım.</p><p><em>page.evaluate() </em>ile doğrudan <strong>Dom</strong>a erişim sağlayabiliriz. Şimdi artık Dom üzerinde gezinip ihtiyacımız olan dataları okuyabiliriz. Burada <strong>jQuery</strong> kullandım. <strong>Pure Javascript</strong> ile de yazılabilir.</p><p>Her <strong>Günün</strong> datasını listeye kaydettikten sonra Listeyi <strong>Mongo</strong>daki Dbmize <strong>Insert</strong> ediyoruz.</p><p>En son işimiz bittiğinde <strong><em>browser.close()</em> </strong>diyerek <strong>browser</strong> kapatıyoruz. <strong>Headless</strong> mode kapalı olduğundan bu işlemlerin hepsini görebileceğiz.</p><p>Artık çalıştırıp test edebiliriz. Konsola <strong><em>node ./puppeteer.js</em></strong><em> </em>yazıp çalıştırıyoruz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*Vuz7kT_0HTqId_ebjhYM0Q.gif" /></figure><p>Şimdi gidip Veritabanımıza bakıyoruz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z-wUxvzrASgs3DB9NENTeg.png" /></figure><p>Ve işte <strong>47.013 </strong>data veritabanımızda…</p><p>Sonuç olarak; <strong>Wikipedia</strong>dan yılın tüm günlerindeki dataları <strong>puppeteer</strong> ile okuyup Veritabanımıza kaydettik.</p><p>Github üzerinden örneklerimizi inceleyebilirsiniz.</p><ul><li><a href="https://github.com/yasinilkalp/puppeteer-data-scraping">GitHub - yasinilkalp/puppeteer-data-scraping</a></li><li><a href="https://github.com/yasinilkalp/express-to-vercel">GitHub - yasinilkalp/express-to-vercel</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f1dd5bc546c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hangfire & .Net Core ile Binance Api CryptoReporter]]></title>
            <link>https://yasinilkalp.medium.com/hangfire-net-core-ile-binance-api-cryptoreporter-df293548a9e5?source=rss-f14ab38ac50d------2</link>
            <guid isPermaLink="false">https://medium.com/p/df293548a9e5</guid>
            <category><![CDATA[crypto-report]]></category>
            <category><![CDATA[net-core]]></category>
            <category><![CDATA[hangfire]]></category>
            <category><![CDATA[binance-api]]></category>
            <dc:creator><![CDATA[Yasin İlkalp Arabacı]]></dc:creator>
            <pubDate>Sun, 28 Nov 2021 13:49:34 GMT</pubDate>
            <atom:updated>2021-12-03T06:33:50.630Z</atom:updated>
            <content:encoded><![CDATA[<h3>Hangfire &amp; .Net Core ile Binance Api CryptoReporter</h3><p>Uygulamalarımızda mutlaka bir işi yaptırırken mevcut işi kesmeden paralelinde (asenkron) bir iş yaptırmak istemişizdir. Ya da uygulamamızdaki kullanıcılarımıza zamanlanmış görevler oluşturup haftalık, günlük bildirim atma ihtiyacımız olmuştur. Bu tür durumlar için <strong>background task</strong>lar üretebilmemizi sağlayan, <strong>open source</strong> bir kütüphane olan <strong>Hangfire </strong>inceleyip, küçük bir örnek yapacağız.</p><p>Örneğimize geçmeden önce <strong>Hangfire </strong>Nedir, Nasıl kullanılır bir bakalım.</p><p><strong>Hangfire</strong>, arkaplanda çalışacak olan işleri yönetmemizi sağlayan açık kaynak bir kütüphanedir. <strong>Dashboard </strong>desteği ile bu işleri kolayca monitör edebilir, <strong>Database </strong>desteğiyle görevlerimizi saklayabiliriz. Projemiz ya da sunucumuz kapandığında görevlerimiz kaybolmamakta ve kalıcılık (<strong>persistent) </strong>sağlanmakta.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/1*O1NeyxLmcNAFmel9kti9Mg.png" /></figure><p>Yukarıdaki şekilde <strong>Hangfire </strong>Nasıl çalıştığını görüyoruz. <strong>Client </strong>tarafından oluşturulan görevler çalıştırılmak üzere depolanır. Bu depolama için <strong>Sql Server, Redis, PostgreSQL, Mongo, Memory Storage</strong> gibi bir çok seçenekten birini seçebilirsiniz. Örnekte ben kullanmadım fakat projelerinizde Db bağlantısını yapıp kullanmanızı öneririm.</p><h4><strong>Oluşturabileceğimiz Job Türlerine bakalım;</strong></h4><p><strong>1- Fire-and-Forget Jobs — </strong>yalnızca bir kez ve oluşturulduktan hemen sonra çalıştırılır.</p><p><strong>2- Delayed jobs</strong> — belirli bir zaman aralığından sonra hemen değil, yalnızca bir kez çalıştırılır.</p><p><strong>3- Recurring jobs</strong> — belirtilen CRON programına göre çalıştırılır. (Günlük, Haftalık, Saatlik vb.)</p><p><strong>4- Continuation jobs</strong> — Parent-child ilişkisinin olduğu job türüdür. Ana görev bittikten sonra başka bir job çalıştırmak istediğimizde kullanabiliriz.</p><h3>Crypto Reporter</h3><p>Hadi şimdi <strong>Binance Api</strong> ile Kripto fiyat bilgilerini belirli aralıklarla <strong>E-posta </strong>gönderen bir <strong>Console</strong> uygulaması yazalım.</p><h4>Binance Api Key ve Secret Key Nasıl Alınır?</h4><p><strong>Binance </strong>üyeliğinizin olduğunu varsayarak devam ediyorum. Eğer yok ise <a href="https://accounts.binance.com/tr/register?ref=19729591"><strong>buradan </strong></a>üye olabilirsiniz.</p><p>Hesap menüsünden <strong>API Yönetim</strong>i kısmına giriş yapıyoruz. Oluşturacağınız API Anahtarına bir isim vererek <strong>Oluştur </strong>diyoruz.</p><p>Her şeyi doğru yaptıysak aşağıdaki gibi bir <strong>API Key</strong> ve <strong>Secret Key</strong> oluşacaktır. Altındaki kısıtlamaları kendinize göre ayarlayabilirsiniz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IsPu8O0skCVSgjO_ioIW4A.png" /></figure><p>Binance Api bilgilerimizi aldığımıza göre artık projeyi oluşturup yazmaya başlayalım.</p><p>.<strong>Net Core </strong>ile bir <strong>Console </strong>uygulaması oluşturuyoruz.</p><p>İlk iş olarak bir kaç paket yüklememiz gerekiyor. <strong>AutoMapper, Binance.Net, Hangfire, Hangfire.MemoryStorage, Microsoft.Owin </strong>paketlerini hızlıca yükleyip devam edelim.</p><p>Projemiz <strong>4 </strong>servisten oluşacak. Ana dizinimize <strong>Service </strong>adında bir klasör açıp Servislerimizi oluşturmaya başlayalım.</p><h4>1- Service/Concrete/BinanceService.cs</h4><p><strong>Binance Api</strong> kullacağımız Servisimizdir. Örnek olsun diye 2 method oluşturdum. Bunu <strong>Binance.Net</strong> kütüphanesini kullanarak ihtiyacınıza göre arttırabilirsiniz. Market fiyatlarını çekeceğimiz bir methodumuz ve belirli bir coin fiyatını çekeceğimiz diğer methodumuzu aşağıda görebilirsiniz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f38d3b263d46abbd43b65ca52a73099/href">https://medium.com/media/6f38d3b263d46abbd43b65ca52a73099/href</a></iframe><h4>2- Service/Concrete/EmailService.cs</h4><p>Kripto fiyatını bize E-posta gönderecek servisimizdir. Servise <strong>MessageContent </strong>adında bir model gönderiyoruz. Modeli yazının sonundaki <strong>Github </strong>reposundan inceleyebilirsiniz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2bbe90c553d7b887e3c06c7f25db65e4/href">https://medium.com/media/2bbe90c553d7b887e3c06c7f25db65e4/href</a></iframe><h4>3- Service/Concrete/TemplateService.cs</h4><p>Bu servisi projelerinize fikir olsun diye sonradan ekledim. <strong>Reflection </strong>ile <strong>T</strong> tipindeki modelimizin <strong>property name</strong> alanlarını Mail şablonumuzdaki ilgili yerlere eklememizi sağlıyor.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d296f63d911aa5f2a851f4b5138ada2a/href">https://medium.com/media/d296f63d911aa5f2a851f4b5138ada2a/href</a></iframe><h4>4- Service/Concrete/CrytpoReportService.cs</h4><p><strong>Hangfire </strong>joblarına vereceğimiz servisimize geldik. <strong>Coin Symbol</strong> parametresi verdiğimiz bu servis önce <strong>BinanceService </strong>üzerinden fiyat bilgisini alıyor. Mail şablonunu <strong>Stream </strong>ederek string’e çeviriyor. <strong>TemplateService </strong>de bu html stringi <strong>CryptoPrice </strong>modelini <strong>Reflection </strong>ederek bir <strong>MessageContent </strong>modeline <strong>Map </strong>ediyor. <strong>EmailService </strong>de <strong>MessageContent </strong>Modelini alarak kullanıcıya E-posta atıyor.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d5a52bc5580e211b77b8fe702e920fc7/href">https://medium.com/media/d5a52bc5580e211b77b8fe702e920fc7/href</a></iframe><p><strong>Binance Api</strong> bilgilerini ve <strong>E-posta </strong>göndereceğimiz Servisin bilgilerini bir <strong>json </strong>dosyasında tutup, kullanacağımız servislere kolay <strong>inject </strong>edebilmek için <strong>Options Patterns</strong>’ten yararlanacağız.</p><p>Bunun için ana dizinimize bir <strong>appsettings.json</strong> dosyası oluşturup içini aşağıdaki şekilde düzenleyelim. Alanları kendinize göre editleyip, kaydedin.</p><blockquote>Not: <strong>appsettings.json</strong> dosyasına sağ tıklayıp <strong>Properties </strong>sekmesi altındaki <strong>Copy to Output Directory</strong> alanını <strong>Copy always</strong> olarak seçiyoruz.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/faf7192ee14e85decc27b499d7762d97/href">https://medium.com/media/faf7192ee14e85decc27b499d7762d97/href</a></iframe><p>Oluşturduğumuz <strong>appsettings.json</strong> dosyasını tanımlayacağımız, <strong>Options Pattern</strong>i kullanacağımız ve servislerimizi tanıtacağımız <strong>Startup.cs</strong> dosyamızda aşağıdaki gibi olacaktır.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5582c18b3e291f5f518729ea691a8d52/href">https://medium.com/media/5582c18b3e291f5f518729ea691a8d52/href</a></iframe><p>Ek olarak <strong>AutoMapper </strong>kütüphanesini kullandık. <strong>BinanceApi</strong>’den gelen <strong>BinancePrice </strong>Modelini kendi oluşturduğumuz <strong>CryptoPrice </strong>modeline <strong>Map </strong>edelim diye kullandık. <strong>Mapping </strong>işlemleri için oldukça hızlı ve kullanışlı bir kütüphanedir. Ana dizine <strong>Mappers </strong>adında bir klasör oluşturup <strong>MappingProfile.cs </strong>dosyamızı aşağıdaki şekilde oluşturuyoruz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6edd6edb0f6766ab6b6117e125ec1d81/href">https://medium.com/media/6edd6edb0f6766ab6b6117e125ec1d81/href</a></iframe><p>Projemiz hazır durumda. Çalıştırmadan önce <strong>Hangfire </strong>ile oluşturduğumuz görevlerimize bir göz atalım.</p><p>recurringJobManager.AddOrUpdate(&quot;BNBUSDT Reporter&quot;, ()=&gt; currencyReporterService.SendReport(&quot;BNBUSDT&quot;), Cron.Minutely);</p><p>recurringJobManager.AddOrUpdate(&quot;BTCUSDT Reporter&quot;, ()=&gt; currencyReporterService.SendReport(&quot;BTCUSDT&quot;), Cron.Hourly);</p><p>Sıkı bir <strong>BNB </strong>Takipçisi olarak Dakikalık fiyat bilgisi almak, Saatlik de <strong>BTC </strong>fiyatından haberdar olmak istediğimi belirttim.</p><p>İşte bu kadar basit. Hadi çalıştırıp Dashboarda bakalım.</p><p>Oluşturduğumuz görevleri <strong>Reccurring Jobs</strong> sekmesinden görebiliriz. Ne zaman oluşturulduğunu, bir sonraki çalışma zamanını ve en son çalıştığı zamanı takip edebiliriz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uk1Xu5FPefF6tMOJKf2Z4A.png" /></figure><p>Herhangi bir hata durumunda ise <strong>Retries </strong>sekmesinden takip edebilir, hata sebebini ve tekrar ne zaman tetikleneceğini görebiliriz. Buradaki Retry durumu çok büyük bir nimet. Zira anlık kesintilerde oluşan hatalardan sonra tekrar tetiklendiğinde görevimiz başarıyla çalışacaktır. Retry Count sayısını belirtmezsek Default değeri 10&#39;dur.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q4NyblJgDfDdv3m0O1pLUw.png" /></figure><p>Son olarak bir görevin detay bilgilerine de Id kısmına tıklayarak ulaşabilirsiniz. Aşağıdaki şekilde bir ekran çıkacaktır karşınıza.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VgTrR-3smFsRpzQXcT2-4w.png" /></figure><p>Her şey doğru çalışıyor ise E-posta kutumuzu kontrol ediyoruz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xJph3EzuhNYtI5CsYneoQw.png" /></figure><p>Sonuç olarak;<strong> Binance Api</strong> ile çektiğimiz Coin Fiyatını <strong>Hangfire </strong>kullanarak belirli zaman aralıklarıyla e-posta olarak gönderdik. Umarım faydalı olmuştur.</p><p>Github üzerinden örneğimizi inceleyebilirsiniz.</p><p><a href="https://github.com/yasinilkalp/CryptoReporter">GitHub - yasinilkalp/CryptoReporter: Hangfire &amp; .Net Core ile Binance Api CryptoReporter</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df293548a9e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[EF Core ile SQL Server HierarchyId Kullanımı]]></title>
            <link>https://yasinilkalp.medium.com/ef-core-ile-sql-server-hierarchyid-kullan%C4%B1m%C4%B1-32afff212123?source=rss-f14ab38ac50d------2</link>
            <guid isPermaLink="false">https://medium.com/p/32afff212123</guid>
            <category><![CDATA[hierarchyid]]></category>
            <category><![CDATA[ef-core]]></category>
            <category><![CDATA[sql-server]]></category>
            <dc:creator><![CDATA[Yasin İlkalp Arabacı]]></dc:creator>
            <pubDate>Sun, 09 May 2021 20:28:01 GMT</pubDate>
            <atom:updated>2021-05-10T12:54:26.973Z</atom:updated>
            <content:encoded><![CDATA[<p>Hiyerarşik yapıları sıklıkla bir <strong>ParentID</strong> yardımıyla kullanırız. <strong>Parent/Child</strong> ilişkisi hemen hemen tüm projelerimde ihtiyaç duyduğum ve her seferinde <strong>refactor </strong>ederek yeniden yazdığım bir yapıdır. <strong>HierarchyId</strong> veri tipiyle tanışana kadar böyleydi. Bu yazı da sizlere <strong>HierarchyId</strong> veri tipini <strong>EF Core</strong> ile kullanımından bahsedeceğim.</p><p><strong>HierarchyId </strong>veri tipi hiyerarşik verileri saklamak için kullanılır. Bu yazımızda da örnek olarak kullanacağımız kategori ağacını ele alalım.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*OrO3VwZHLiRGlcTOHQeGiw.png" /></figure><p>Şekildeki örneği incelediğimizde <strong>Kozmetik</strong> Ana kategorisinin altında 3 alt kategori ve her alt kategorinin altında da 2 alt kategori daha görüyoruz. Bunları veritabanımızdaki ilgili tabloya bir <strong>ParentId</strong> alanı açıp, her bir alt kategorinin <strong>ParentId</strong> alanına kendisine bağlı kategorinin <strong>Id</strong> alanını verebilirdik.</p><p>Bu Kategori ağacının <strong>HierarchyId </strong>ile Nasıl göründüğüne bakalım.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/1*txsBpy7Yyirsrauyo0QEPg.png" /></figure><p><strong>Örneğin</strong>; Kozmetik Kategorisinin Id alanını 1 kabul edersek, Makyaj kategorisinin <strong>ParentId</strong> alanını 1 olarak girmemiz yeterliydi. Bu şekilde <strong>Parent/Child </strong>ilişkisiyle tüm kategori ağacımızı kolaylıkla oluşturabilirdik.</p><h3>Neden <strong>HierarchyId</strong>?</h3><p>Bir hiyerarşiyi temsil etmek için <strong>ParentId</strong> sütunu kullanmak yaygın bir yöntemdir. Bunu oluşturmak kolay olsa da, hiyerarşi üzerindeki bazı işlemler <strong>HierarchyId</strong> kullanmaya kıyasla daha zor ve bazen daha yavaş olabilir. Sanırım diğer yöntemlere göre tek dezavantajı öğrenme süreci diyebilirim.</p><h3>Nasıl Kullanırız?</h3><p>Örnek olarak verdiğimiz kategori ağacındaki gibi bir yapıyı oluşturabilmek için bilmemiz gereken bir kaç fonksiyonumuz vardır. Bunları tek tek inceleyelim.</p><p><strong>ToString():</strong> Hiyerarşiyi ”/” işaretleri ile gösterir. Okunabilirlik sağlar.<br> <strong>GetRoot(): </strong>Hiyerarşi ağacının kökünü döndürür. <br> <strong>GetDescendant():</strong> Node altında başka bir node olup olmadığını gösterir.<br> <strong>GetAncestor():</strong> Alttan üste doğru bir node gitmemizi sağlar. <br> <strong>GetLevel():</strong> Derinlik seviyesini verir.</p><p>Bu fonksiyonlar yapıya hakim olabilmemiz için yeterlidir. Gelin şimdi örneğimizi EF Core üzerinde nasıl yapacağımıza bakalım.</p><h3>EF Core ile Kullanımı</h3><p>Dotnet Cli ile bir webapi projesini hızlıca oluşturup kodlamaya başlayalım.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/56a629b42448d119f8bbce71f63c60df/href">https://medium.com/media/56a629b42448d119f8bbce71f63c60df/href</a></iframe><p><strong>HierarchyIdWithEfCore</strong> adında bir solution oluşturduk. Yine aynı isimle bir webapi projesi oluşturup solutiona ekledik.</p><p>Daha sonra, ihtiyacımız olacak 2 <strong>NuGet paketi</strong>ni de projemize dahil ettik.</p><ul><li>Microsoft.EntityFrameworkCore.SqlServer</li><li>EntityFrameworkCore.SqlServer.HierarchyId</li></ul><p>Projemizi açıp kodlamaya başlayalım. Ben bu örnek için <strong>VsCode</strong> kullacağım.</p><ul><li><strong>Category</strong> adında bir Model oluşturuyoruz.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b21e8ae65462e025d62f4e4409200df/href">https://medium.com/media/7b21e8ae65462e025d62f4e4409200df/href</a></iframe><ul><li><strong>DbContextimizi</strong> de aşağıdaki şekilde oluşturuyoruz.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2343445eecf3c39d18c1dc131c85e583/href">https://medium.com/media/2343445eecf3c39d18c1dc131c85e583/href</a></iframe><ul><li>Veritabanımızı aşağıdaki şekilde oluşturuyoruz. Migration ile de yapabilirsiniz.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6efa2c84061473551c633c3062470489/href">https://medium.com/media/6efa2c84061473551c633c3062470489/href</a></iframe><p>Neler yaptığımızı bir özetleyelim. Projemizi oluşturduktan sonra Kategori Ağacımız için <strong>Category</strong> Modelimizi oluşturduk. Dikkat ederseniz buradaki <strong>HierarchyId </strong>sütunumuzun türünü <strong>HierarchyId</strong> olarak belirttik. Bunu projeyi oluştururken kurduğumuz EntityFrameworkCore.SqlServer.HierarchyId nuget paketi sayesinde yapabildik.</p><p>DbContextimizi oluştururken <strong>UseHierarchyId()</strong> ayarını yapıyoruz. Ve Migration ile tablomuzu oluşturuyoruz.</p><p>Örnekteki datalarımızı Veritabanımıza ekleyip örneklerle devam edelim.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/50db9858867043fa53cf4b8cbf3a4e46/href">https://medium.com/media/50db9858867043fa53cf4b8cbf3a4e46/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/276/1*WuAu7_9d6Bbw37OOhErbqQ.jpeg" /></figure><p>Örnekteki datalarımızı eklediğimiz de yandaki şekilde görülecektir. Buradaki <strong>HierarchyId </strong>alanımızı okunabilir şekilde<strong> “/”</strong> ile gösterebilmek için <strong>ToString()</strong> fonksiyonunu kullanacağız.</p><h3>Yeni Kategori Ekleme</h3><p>Kategori ağacımıza yeni bir kategori eklemek için GetDescendant(child1, child2) metodunu kullanacağız. Fonksiyon 2 parametre alıyor. <strong>Child1</strong>&#39;den büyük, <strong>Child2</strong>&#39;den küçük bir <strong>HierarchyId </strong>üretir.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e8c8f6d916583340ac89911b1feef5b/href">https://medium.com/media/9e8c8f6d916583340ac89911b1feef5b/href</a></iframe><h3>HierarchyId göre Sıralama</h3><p>Sıralama işlemini Linq yardımıyla yapabilirsiniz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8fb901a496039ad69d8ca52cde67f9f0/href">https://medium.com/media/8fb901a496039ad69d8ca52cde67f9f0/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/328/1*3_CCH2LPEXFC1vEs0dozvQ.jpeg" /></figure><h3>Derinlik Seviyesini Alma</h3><p>Kategori ağacımızdaki bir kategorinin derinlik seviyesine ihtiyaç duyabiliriz. Ya da belirli bir derinlikteki kategorileri listelemek isteyebiliriz. Bunun için GetLevel()fonksiyonunu kullanacağız.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/160ef8a3de3ed35092b5226283db57db/href">https://medium.com/media/160ef8a3de3ed35092b5226283db57db/href</a></iframe><p>Yukarıdaki örnekte bir Kategorinin Derinlik seviyesini aldık. Şimdi de 2 derinlik seviyesinde kaç kategorimiz varmış ona bakalım.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/07157a9c649d7e4491cdcedc077fd388/href">https://medium.com/media/07157a9c649d7e4491cdcedc077fd388/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/285/1*D4kezXIrxmzhewCr5f_HCA.jpeg" /></figure><h3>Üst Kategorilere Erişmek</h3><p>GetAncestor(n) fonksiyonu alttan üste doğru gitmemize yardımcı olur. Buradaki n bulunduğumuz basamaktan kaç adım üste doğru gideceğimizi belirtir.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d01196a52cc577276bb0cf50c1cc5a56/href">https://medium.com/media/d01196a52cc577276bb0cf50c1cc5a56/href</a></iframe><p>Bu örnekte bir üst adımı görebildik. Peki tüm üst kategorileri listelemek istersek ne yapmalıyız? IsDescendantOf() fonksiyonunu kullanarak Kategori <strong>Breadcrumb </strong>oluşturabiliriz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f236e9892f8938a782639c24a9ed48f/href">https://medium.com/media/7f236e9892f8938a782639c24a9ed48f/href</a></iframe><h3>Alt Kategorilere Erişmek</h3><p>GetAncestor(n) fonksiyonu ile bir kategorinin doğrudan alt kategorilerini de sorgulayabilirsiniz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d08cae7adde700420eb18a81314c109f/href">https://medium.com/media/d08cae7adde700420eb18a81314c109f/href</a></iframe><p>Sonuç olarak hiyerarşik yapımızı nasıl kurgulayacağımızı ve nasıl kullanacağımızı görmüş olduk. Umarım faydalı bir yazı olmuştur.</p><p>Github üzerinden örnek projeyi inceleyebilirsiniz.</p><p><a href="https://github.com/yasinilkalp/HierarchyIdWithEfCore">yasinilkalp/HierarchyIdWithEfCore</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=32afff212123" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>