<?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 Anna on Medium]]></title>
        <description><![CDATA[Stories by Anna on Medium]]></description>
        <link>https://medium.com/@an.karenina?source=rss-a0d3c2d73eef------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*qdQOMi7VNJuzi9-n4H-i8g@2x.jpeg</url>
            <title>Stories by Anna on Medium</title>
            <link>https://medium.com/@an.karenina?source=rss-a0d3c2d73eef------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 10:03:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@an.karenina/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[Whose fault and who to blame?]]></title>
            <link>https://medium.com/@an.karenina/whose-fault-and-who-to-blame-c433e45ca21a?source=rss-a0d3c2d73eef------2</link>
            <guid isPermaLink="false">https://medium.com/p/c433e45ca21a</guid>
            <category><![CDATA[afterwork]]></category>
            <category><![CDATA[life]]></category>
            <category><![CDATA[destiny]]></category>
            <dc:creator><![CDATA[Anna]]></dc:creator>
            <pubDate>Thu, 19 Nov 2026 15:31:27 GMT</pubDate>
            <atom:updated>2026-11-19T15:31:27.109Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Source : unsplash" src="https://cdn-images-1.medium.com/max/1024/0*NXC_0jc_Ma8ndCvX" /><figcaption>Photo by <a href="https://unsplash.com/@ranggcahya">Rangga Cahya Nugraha</a> on unsplash</figcaption></figure><p>Another normal Tuesday of taking bus after work, it was raining so i gotta get ready for a long wait for the bus to come with a super packed situation inside it while wishing there would be enough space for me to squeeze in, and thank god when the bus arrived there is enough space for me to stand near the door, right with people who wished for the same thing.</p><p>I have quite a few stop before i got off to my destination, the first stop 3 people come in, second stop another 3 people consist of a man, a mother and her 7 years old daughter i guess, and then its packed like crazy, cannot add another people inside cause that man already stand face to face with the bus door, at a point where he could just kiss the door glass, the young girl and her mother stand right in front of me, then we arrived at the third stop.. the driver opened the bus door and then i hear the girl cries and everyone is screaming <em>“Pak tutup pintu nya pak, ada anak kecil kepala nya kejepit”</em> i wasn’t pay attention until everyone scream, and that was happened right in front of me, in front of my eyes, then i looked at her head being stuck and squeezed by an automatic door, i was froze and thinking “what should i do?” i obviously don’t want to scream and add more panic noise which already super loud, and i can’t do anything, cause it could only be resolved if the door closed so i’m just watching.. until the door closed right after everyone scream, i think it took around a minute or two for the automatic bus door to closed cause there were latency from when the close door button is trigger until the door actually closed.</p><p>The girl cries..so loud, and her mom.. idk maybe kinda panic, and then a kind passenger gave a seat to the girl to calm her down, and thank god she is physically okay.</p><blockquote>At that particular moment, my first thought of judgement was “if only her parents were financially in a better situation, maybe they could have just book a Taxi instead, so she doesn’t have to experience that traumatic moment which i believe she will remember for the rest of her life” yes, i blame her parents and its their fault.</blockquote><p>Along the way home, i kept thinking about it, about how traumatizing it must be for her, about who to blame and whose fault, and how to prevent that kind of accident, and i have a few thoughts.</p><p>If we look at it with a capitalism pov, it is her parents fault for not giving a worthy, safe and secure life to their children, which totally one of the parents responsibility and something to think about before they decide to have children. I mean, it’s raining, the bus is packed, booking an online taxi for both of you and your children should not be a problem.</p><p>If we look at it with a political pov, its absolutely government fault for not providing reliable public transport for a raining situation cause they should have think about that case and how to make it even more reliable and available while the demand and traffic is that high. Which also lead to economical problem and i’m not gonna talk about it here.</p><p>If we look at it with a society pov, maybe its my fault for only looking at the road and minding my own business instead of scream for priority seat to give to her, or maybe its also the rest of the bus fault for not doing the same as i should be.</p><p>If we look at it with a religious pov, maybe the accident meant as her <em>destiny</em> to get her head squeezed which maybe gonna teach her and her mother a lesson, something like a blessing in disguise. But this is where i found it <em>interesting</em> and open my mind, let’s say her mom could afford to book a Taxi, which is an impossible case to get her head squeezed by the door, <em>but what if the other accident happen to her? </em>like her finger getting caught in the door? or maybe a crash? and the other possible scenario of her getting hurts. No one could guarantee.</p><p>That also leads me to another thoughts, if only my parents were rich enough so that i don’t have to work so hard to afford life, if only i live in a country where the public transport is better in any condition so that i don’t have to be in a pack of whatever that was, if only, if only..if only.</p><p>Destiny is something that will necessarily happen to a particular person or thing in the future, no matter what. It is something we cannot escape and we cannot control no matter what financial condition we were having, what country or society we were living.</p><p>Its funny how we, as a human could plan things, work on things, and do whatever to control things the way we wanted but there will always be one particular parameter that is remains uncontrolled, God’s will.</p><p>Destiny doesn’t care about your financial condition or who you are, it will happened to you cause its written that way, it meant to be that way, God’s wants it to be that way and you can’t escape something that is meant for you.</p><p>And that doesn’t necessarily means you should just give up your life on whatever it throws at you. Her parents could do better, the gov and society obviously could do better, i mean.. shoot your best shot and let God do the rest.</p><p>Good or bad, there will always be reason behind what happened to you, it could be a blessing or a lesson.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gBhYhvZmSQNPzX_VdWOqXw.png" /><figcaption>a beautiful reminder</figcaption></figure><p>And maybe it was my destiny to witnessed it so that i learn a bit more about destiny.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c433e45ca21a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[️ Building AI-Powered Autonomous Strategy & Compliance Agents for McLaren F1 ]]></title>
            <link>https://medium.com/@an.karenina/%EF%B8%8F-building-ai-powered-autonomous-strategy-compliance-agents-for-mclaren-f1-3f6d3f2c2879?source=rss-a0d3c2d73eef------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f6d3f2c2879</guid>
            <category><![CDATA[gemini]]></category>
            <category><![CDATA[mclaren-racing]]></category>
            <category><![CDATA[formula-1]]></category>
            <category><![CDATA[race]]></category>
            <category><![CDATA[f1]]></category>
            <dc:creator><![CDATA[Anna]]></dc:creator>
            <pubDate>Sun, 23 Aug 2026 10:02:04 GMT</pubDate>
            <atom:updated>2026-08-23T10:02:04.731Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Formula 1 is a sport won and lost in milliseconds. At 200+ mph, strategy walls must process thousands of telemetry signals per second — ranging from tire degradation curves and sector deltas to fluctuating weather forecasts.</p><p>However, speed without compliance is meaningless. A brilliant race strategy can be wiped out in seconds by a time penalty or a technical disqualification resulting from a miss-interpretation of complex FIA regulations, or even choosing the wrong tire to start a race.</p><p>To solve this dual challenge of real-time performance prediction and instant regulatory compliance, I built an autonomous multi-agent system designed for the McLaren F1 Team. Powered by custom Data Connectors, Machine Learning predictive models, and an Agent Development Kit (ADK), this system acts as a virtual strategy and compliance assistant.</p><p>Below is a deep dive into the architecture, execution, and proof of concept of this project.</p><h3>🏗️ System Architecture &amp; Workflow</h3><p>The system is built on a modular multi-agent architecture where specialized agents collaborate synchronously under a centralized data foundation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xKRjZk1eYDeGgDYB" /></figure><h3>🔑 Key Components Built</h3><h3>1. Strategy Team — FIA Regulation Parser &amp; Decision Engine</h3><p>Using the Gemini Enterprise app for the FIA Rules &amp; Compliance combine with drivers profile data :</p><ul><li>Rulebook Ingestion: Continuously monitors and indexes the latest FIA Sporting and Technical Regulations, allowing instant retrieval of specific rules during fast-moving race scenarios.</li><li>Incident &amp; Precedent Cross-Referencing: When race control issues a steward notice or incident flag (e.g., track limits violation, unsafe release, yellow flag infraction), the agent instantly retrieves relevant clauses and past precedents.</li><li>Real-Time Compliant Decision Making: Evaluates proposed strategy shifts (e.g., serving penalties under Safety Car/VSC, tire compound mandates, pit lane releases) to guarantee every pit-wall decision is 100% compliant before execution.</li></ul><p><a href="https://drive.google.com/file/d/1xbTmFkJbdYttvxCTb3vI2CmYghirejHW/view?usp=sharing">Strategy Team.mov</a></p><h3>2. Race Engineer Agent — Pre-Race Driver Briefing &amp; Telemetry Integration</h3><p>The primary role of the Race Engineer Agent is to formulate data-driven Pre-Race Driver Briefings and operational game plans by ingesting driver-specific data, team telemetry, and circuit characteristics before lights out:</p><ul><li>Automated Pre-Race Driver Briefings: Synthesizes track layout nuances, recommended braking points, DRS zone strategies, and turn-by-turn line optimizations tailored specifically to the driver’s driving style and historical performance.</li><li>Setup &amp; Telemetry Optimization: Ingests baseline setup telemetry, tire compound characteristics, fuel load calculations, and expected degradation rates to establish ideal initial car configuration and stint targets.</li><li>Track &amp; Weather Dynamics: Live radar forecasts, track evolution indices, and safety car / virtual safety car (VSC) probabilities.</li></ul><p><a href="https://drive.google.com/file/d/1VHhFm85kz4_cbwXwCIFbCT6YeVjxnJiQ/view?usp=sharing">Race Engineer Agent.mov</a></p><h3>3. Machine Learning Podium &amp; Strategy Prediction Engine</h3><p>Using historical race data and real-time telemetry inputs, the predictive core forecasts key race outcomes:</p><ul><li>Podium Probability Index: Calculates real-time win/podium odds based on current race position, remaining stints, and competitor pace.</li></ul><h3>4. Multi-Agent Orchestration (Agent Development Kit)</h3><p>The Data Science Team provides the core AI infrastructure powering the entire system, built using the Agent Development Kit (ADK):</p><ul><li>ADK Multi-Agent Architecture: Builds and orchestrates specialized sub-agents with custom tools, prompt structures, and memory capabilities.</li><li>Data Pipelines &amp; Connectors: Integrates live telemetry streams, historical race databases, and document retrieval systems into the agent ecosystem.</li><li>ML Podium Prediction Core: Trains and deploys predictive models (via BigQuery ML) to forecast podium odds.</li></ul><p><a href="https://drive.google.com/file/d/1T7zfqf_14zw1Jx-pQXTxOhe6dgXFs6tm/view?usp=sharing">ADK for Data Science .mov</a></p><h3>🎯 Conclusion &amp; What’s Next</h3><p>Building this proof-of-concept for McLaren F1 demonstrated how agentic AI workflows can transform raw data into instant, compliant, high-stakes decisions.</p><p>I think it will be amazing to build a pit window prediction to handle the undercut and overcut, especially when the weather is inconvenient, which is one of the big part of the strategy.</p><p>Agentic AI workflows could help a lot in making data driven decisions, but I think in F1, we also need to check for the real-world facts, such as the capability of the current car build, as well as the driver’s strength and experience. Combining all of these will create a winning team in F1.</p><p>Note : this article mostly generated with Gemini, i only adds a few correction and personal opinion based on my experience with the Google Cloud Labs on Air. It was a super fun lab, i love it, its also my first time hands on the actual F1 data on tables rather than on my TV screen☺️</p><p>Sources : <a href="https://go.cloudplatformonline.com/dc/H5v1VWmnrAFLqt38-dr4Kudko96t_OSLhD9dJYV60iE0pLgKEgHL0IKrNIrF9dzB-8i4MBhIEpr388mEgM-ejqP7uwfisUMPI4CXhhz_HGc=/ODA4LUdKVy0zMTQAAAGjl-8x2zXKZh4GxL0iUlWIcV5lyRYqlsWoxmNK6ey3nHYsBKAt-2ytx1Jnmn8ChIs-07SKVj4=">https://cloudonair.withgoogle.com/events/aug2026-loa-agent-mclaren?mkt_tok=ODA4LUdKVy0zMTQAAAGjl-8x2_ZLPphwRlQDYbxT0sktzjUWXqdEdZyKEa_phIqnWFUvMTotrqnG7pabyw58g7hvxG2eUVu7hFLEcBbniU2oWX_BsSJGBCpnAI08Snrm1LhcUZSI</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f6d3f2c2879" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Gratitude is also a blessing]]></title>
            <link>https://medium.com/@an.karenina/gratitude-is-also-a-blessing-9f88de69bf2d?source=rss-a0d3c2d73eef------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f88de69bf2d</guid>
            <category><![CDATA[gratitude]]></category>
            <category><![CDATA[life]]></category>
            <dc:creator><![CDATA[Anna]]></dc:creator>
            <pubDate>Fri, 10 Jul 2026 15:46:52 GMT</pubDate>
            <atom:updated>2026-07-10T15:53:27.623Z</atom:updated>
            <content:encoded><![CDATA[<p>As a human being, i think everyone have something they wish to have, things to achieve, experiences to feel, which is normal because how do you live without wanting to do anything? personally speaking, human need to have target to live, maybe that’s sounds like a big thing if we are talking about target but thanks to human right, you can set your own target in your own life, with your own timeline, and that could be as simple as survive the day, say “hi, good morning” to your surrounding, have a 10 minutes walk by yourself, finish a task, even finding a target to live.</p><p>but it also could be a big target like buy a new house, travel around the world, own a company, buy a designer bag and clothes, and some other shinny things in the world.</p><p>As a live by, i realized human keep wanting more and more once they got what they want, what they wish for, the scary part of having target is that some people will do everything to get what they want, everything.. and that’s where some people crossed the line, that’s where Allah tests you by giving you all you want until you reach the point where you have what you wanted and wished for, it still isn’t enough. Then you start wanting everything.</p><p>That’s where i think gratitude is a blessing, it isn’t something everyone can have, gratitude made me realized not everything i want or wish for is good for me, i’m grateful for what i have and what i’ve worked for, i’m grateful i don’t always get what i want, cause i’m just a human being who makes a prayer without knowing if its “actually” good for me, but instead Allah gives me something so much better, because nothing in this world would matter once you are dead except for your goodness and faith.</p><figure><img alt="3:14" src="https://cdn-images-1.medium.com/max/737/1*Fc8R_gLHXBU2S1zFzysFtA.png" /><figcaption>Ali imran 3:14</figcaption></figure><p>I really like that verse, as well as Al-an’am 6:32</p><p>And i read this from Rima Edbouche : “Sometimes we forget that rizq is not limited to money or material possessions. Everything Allah grants us is rizq: faith, inner peace, health, a loving family, a door that opens at the right time, or even a trial that brings us closer to Him.</p><p>We sometimes wonder how some people got such a thing, to the point of feeding our hearts with envy. Yet their rizq was decreed for them by Allah, just as ours was long before we came to this earth.</p><p>The people we meet, the opportunities that come our way and even the trials we go through are only reasons Allah puts in our path to lead us to what He has already destined for us.</p><p>Instead of looking at what Allah has granted others, let’s take the time to acknowledge the immense benefits He has already bestowed upon us. May Allah grant us hearts that are satisfied, grateful and fully confident in His decree 🤍”</p><p>Soo whatever target you have in this life, do your best, appreciate what you have and make sure to be always grateful and not crossing the line or do bad thing to achieve it, because life is a game and nothing is permanent in this world.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f88de69bf2d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When things don’t go your way]]></title>
            <link>https://medium.com/@an.karenina/when-things-dont-go-your-way-e4b04e69df51?source=rss-a0d3c2d73eef------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4b04e69df51</guid>
            <category><![CDATA[acceptance]]></category>
            <category><![CDATA[disappointment]]></category>
            <category><![CDATA[life]]></category>
            <category><![CDATA[self-awareness]]></category>
            <dc:creator><![CDATA[Anna]]></dc:creator>
            <pubDate>Sat, 14 Jun 2025 10:50:05 GMT</pubDate>
            <atom:updated>2025-06-14T10:50:05.360Z</atom:updated>
            <content:encoded><![CDATA[<p>Life has not been very kind to me this year, every battle leads to lose, every effort leads to nothing, everything just don’t go the way i want, the way i expected it to be, the way it should be — technically.</p><p>I failed in a lots of things lately, i failed at some meaningful test that might changed my life, i failed to convince people that might changed my financial cost, i failed to make sure some important things, i failed to get my career shortcut which i totally deserve, i even failed at love..again.</p><p>I am someone who believe that you will get the same result as your effort, and turns out it doesn’t work that way especially with life where there are so many random and uncontrolled parameters in it, also..human. There are so many parameters to makes things works, but the most uncontrolled one is human or maybe i could say destiny? honestly i’m not sure.. or maybe we should not control it at all? maybe just let it happen what ever the result would be.</p><p>But honestly i can’t, i can’t accept if the result i got is not direct proportional to the effort that i have made, it’s unacceptable and its unfair.</p><p>Maybe that is how life works, you don’t always get what you want and somehow there is nothing you can do but accept that life is unfair.</p><p>Maybe i will learn something from this, i don’t know.. it’s all just disappointing and confusing lately, i don’t know what i did wrong, i don’t know why is this happening, does people experience this in their 20s? mid 20s? what about late 20s? 30s? will it get better or get worse? again, i don’t know.. all i did is show up and do my best.</p><p>Despite all of the things i faced lately, i need to keep remind myself to be grateful, thankful and happy about how i been through all of these.. the experience, the people in my life.</p><p>I was at the airport and found this book while i was waiting for my flight, and found this quotes that helps me relax about what happend with my current situation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*If6X25Ppg9B0ocm44JvtrA@2x.jpeg" /><figcaption>from When Things Don’t Go Your Way by Haemin Sunim</figcaption></figure><p>And maybe it wasn’t my time, maybe my time will come.. and once it is, <br>i will get back here and read this article back and i’m looking forward to know how i might be feeling by then.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4b04e69df51" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Basics of Keeping Your Users’ Data Safe and Sound With AES and RSA]]></title>
            <link>https://medium.com/@an.karenina/the-basics-of-keeping-your-users-data-safe-and-sound-9457a1ae25dc?source=rss-a0d3c2d73eef------2</link>
            <guid isPermaLink="false">https://medium.com/p/9457a1ae25dc</guid>
            <category><![CDATA[cryptography]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[encryption]]></category>
            <dc:creator><![CDATA[Anna]]></dc:creator>
            <pubDate>Sat, 14 Dec 2024 11:14:35 GMT</pubDate>
            <atom:updated>2024-12-15T04:17:55.580Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-k-eSFGIYhKtTevO" /><figcaption><a href="https://unsplash.com/photos/a-close-up-of-a-computer-screen-with-numbers-on-it-YYUM2sNvnvU">Unsplash.com</a></figcaption></figure><p>Have you store your sensitive user data like email, phone number, address, etc, in a safe way? if yes.. good, if no.. well (scarryy, why!? 😭) but maybe what i am about to write here would give you some insight and helps you store it in a safe way.</p><p>Let’s start with Cryptography, this is the way to secure the communication and data from unauthorized access by transforming it into something unreadable. Imagine you have a <strong>secret message</strong> you want to send to your friend, but you don’t want anyone else to read it. Cryptography is like making that message into a <strong>special code</strong> that only you and your friend know how to unlock.</p><ul><li><strong>Encryption</strong>: It’s like putting your message into a magic box and locking it with a special key. Now, even if someone finds the box, they can’t open it because they don’t have the key.</li><li><strong>Decryption</strong>: When your friend gets the magic box, they use the same key (or sometimes a matching one) to open it and see your secret message.</li></ul><p>It’s like playing spies but with computers! This way, even if a bad guy tries to peek, all they see is jumbled-up letters that don’t make sense. 🎉</p><p><strong>Encryption:</strong> Converting plain text into unreadable format (ciphertext).</p><p><strong>Decryption</strong>: Reverting ciphertext back to its original readable form using a key.</p><p>There are two type of encryption :<br>1. Symmetric : uses the same key to do encryption and decryption</p><figure><img alt="Source : cisco.com" src="https://cdn-images-1.medium.com/max/861/1*9XM8RV9CUC3_YmOV_G4vZA.png" /><figcaption>Source : Cisco.com</figcaption></figure><p>2. Asymmetric : uses different key to do encryption and decryption</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*YRFrazkIAIlDN4_5p4XNYw.png" /><figcaption>Source : Cisco.com</figcaption></figure><h4>1. Symmetric encryption and decryption using C# with AES (Advanced Encryption Standard) algorithm :</h4><pre>[HttpPost]<br>[Route(&quot;[controller]/encryptWithAES&quot;)]<br>public string encryptWithAES([FromBody] string stringRequest)<br>{<br>    string stringKeyEncrypt = &quot;QWERTYUIOPASDFGHQWERTYUILKJHGFDS&quot;;<br>    string stringKeyIV = &quot;ZXCVBNMLKJHGFDSA&quot;;<br>    <br>    string stringEncrypted = Encryption.EncryptWithAES(stringRequest,stringKeyEncrypt,stringKeyIV);<br><br>    return stringEncrypted;<br>}</pre><blockquote><strong>stringKeyEncrypt : </strong>The secret key that we use to encrypt and decrypt, which should contain the size of 16, 24, or 32 byte (or equals to 128, 192 or 256 bits), each ASCII character typically takes 1 byte.</blockquote><blockquote><strong>stringKeyIV : </strong>IV(Initialization Vector) is the random value that we used to make sure the same plain text is encrypted with different result while using the same encryption key. The size of IV key is always 16 bytes regardless of the AES key size</blockquote><pre>public class Encryption<br>{<br>  //WRAPPER<br>  public static string EncryptWithAES(string plainText, string keyString, string ivString)<br>  {<br>      // Convert key and IV strings to byte arrays (assuming UTF-8 encoding for simplicity)<br>      byte[] key = Encoding.UTF8.GetBytes(keyString);<br>      byte[] iv = Encoding.UTF8.GetBytes(ivString);<br>      byte[] bytesPlainText = Encoding.UTF8.GetBytes(plainText);<br>  <br>      // Encrypt the string to an array of bytes.<br>      byte[] encryptedBytes = EncryptWithAES(bytesPlainText, key, iv);<br>  <br>      // Convert the encrypted byte array to a base64-encoded string.<br>      return Convert.ToBase64String(encryptedBytes);<br>  }<br>}</pre><pre>public class Encryption<br>{<br>  private static byte[] EncryptWithAES(byte[] bytesPlainText, byte[] key, byte[] iv)<br>  {<br>      // Check arguments.<br>      if (bytesPlainText == null || bytesPlainText.Length &lt;= 0)<br>          throw new ArgumentNullException(&quot;plainText&quot;);<br>      if (key == null || key.Length &lt;= 0)<br>          throw new ArgumentNullException(&quot;key&quot;);<br>      if (iv == null || iv.Length &lt;= 0)<br>          throw new ArgumentNullException(&quot;iv&quot;);<br>  <br>      // Create aes<br>      using (Aes aesAlg = Aes.Create())<br>      {<br>          aesAlg.Key = key;<br>          aesAlg.IV = iv;<br>  <br>          // Create an encryptor to perform the stream transform.<br>          using (ICryptoTransform cryptoTransformEncryptor = aesAlg.CreateEncryptor(aesAlg.Key,aesAlg.IV))<br>          {<br>              // Create the streams used for encryption.<br>              using (MemoryStream memoryStream = new MemoryStream())<br>              {<br>                  using (CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoTransformEncryptor, CryptoStreamMode.Write))<br>                  {                        <br>                      cryptoStream.Write(bytesPlainText, 0, bytesPlainText.Length);<br>                  }<br>  <br>                  return memoryStream.ToArray();<br>              }                <br>          }<br>      }<br>  }<br>}</pre><p>the result : <br>plaint text : “hello world”<br>encrypted to : jgYQFA+RJ35MS4CWOu/21Q==<br>decrypted back to : “hello world”</p><pre>[HttpPost]<br>[Route(&quot;[controller]/decryptWithAES&quot;)]<br>public string decryptWithAES([FromBody] string stringRequest)<br>{<br>    string stringKeyEncrypt = &quot;QWERTYUIOPASDFGHQWERTYUILKJHGFDS&quot;;<br>    string stringKeyIV = &quot;ZXCVBNMLKJHGFDSA&quot;;     <br><br>    var stringDecrypted = Decryption.DecryptWithAES(stringRequest,stringKeyEncrypt,stringKeyIV);<br>    <br>    return stringDecrypted;<br>}</pre><pre>public class Decryption<br>{<br>//WRAPPER<br>  public static string DecryptWithAES(string cipherText, string keyString, string ivString)<br>  {<br>      // Convert key and IV strings to byte arrays (assuming UTF-8 encoding for simplicity)<br>      byte[] key = Encoding.UTF8.GetBytes(keyString);<br>      byte[] iv = Encoding.UTF8.GetBytes(ivString);<br><br>      // Convert the base64-encoded string to a byte array<br>      byte[] cipherBytes = Convert.FromBase64String(cipherText);<br><br>      // Decrypt the byte array to a string.<br>      string decryptedString = DecryptWithAES(cipherBytes, key, iv);<br><br>      return decryptedString;<br>  }<br>}</pre><pre>public class Decryption<br>{<br>  private static string DecryptWithAES(byte[] cipherText, byte[] key, byte[] iv)<br>  {<br>      // Check arguments.<br>      if (cipherText == null || cipherText.Length &lt;= 0)<br>          throw new ArgumentNullException(&quot;cipherText&quot;);<br>      if (key == null || key.Length &lt;= 0)<br>          throw new ArgumentNullException(&quot;key&quot;);<br>      if (iv == null || iv.Length &lt;= 0)<br>          throw new ArgumentNullException(&quot;iv&quot;);<br><br>      // Create an Aes object with the specified key and IV.<br>      using (Aes aesAlg = Aes.Create())<br>      {<br>          aesAlg.Key = key;<br>          aesAlg.IV = iv;<br><br>          // Create a decryptor to perform the stream transform.<br>          using (ICryptoTransform cryptoTransformDecryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV))<br>          {<br>              // Create the streams used for decryption.<br>              using (MemoryStream memoryStream = new MemoryStream(cipherText))<br>              {<br>                  using (CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoTransformDecryptor, CryptoStreamMode.Read))<br>                  {<br>                      using (StreamReader streamReader = new StreamReader(cryptoStream))<br>                      {<br>                          // Read the decrypted bytes from the decrypting stream and place them in a string.<br>                          return streamReader.ReadToEnd();<br>                      }<br>                  }<br>              } <br>          }   <br>      }<br>  }<br>}</pre><p>AES algorithm only works for symmetric encryption.</p><h4>2. Asymmetric encryption and decryption using C# with RSA algorithm :</h4><pre>[HttpPost]<br>[Route(&quot;[controller]/encryptWithRSA&quot;)]<br>public string encryptWithRSA([FromBody] string stringRequest)<br>{<br>    string stringAuthKey = Request.Headers[&quot;AuthorizedKey&quot;];<br>    string stringPublicKey = stringAuthKey<br>    .Replace(&quot;-----BEGIN RSA PUBLIC KEY-----&quot;, &quot;&quot;)<br>    .Replace(&quot;-----END RSA PUBLIC KEY-----&quot;, &quot;&quot;)<br>    .Replace(&quot;\\n&quot;, &quot;&quot;)<br>    .Replace(&quot;\r&quot;, &quot;&quot;);<br><br>    string stringEncrypted = Encryption.EncryptWithRSA(stringRequest,stringPublicKey);<br>    <br>    return  stringEncrypted;<br>}</pre><blockquote><strong>stringPublicKey : </strong>We need to have the public (to encrypt) and private key (to decrypt), there are many ways where you can get a pair of RSA public and private key, you can use your favorite genAI to generate it, online website, cmd or even the build in function on your code. I put the public key on the request header for simplicity, and please be mindful where you store your public and private key.</blockquote><pre>public class Encryption<br>{<br>  //WRAPPER<br>  public static string EncryptWithRSA(string plainText, string publibKey)<br>  {<br>      <br>      byte[] bytesPlainText = Encoding.UTF8.GetBytes(plainText);<br>      <br>      // Encrypt the string to an array of bytes.<br>      byte[] encryptedBytes = EncryptWithRSA(bytesPlainText,publibKey);<br><br>      // Convert the encrypted byte array to a base64-encoded string.<br>      return Convert.ToBase64String(encryptedBytes);<br>  }<br>}</pre><pre>public class Encryption<br>{<br>  private static byte[] EncryptWithRSA(byte[] bytePlainText, string stringPublickey)<br>  {<br>      using(RSA rsa = RSA.Create())<br>      {<br>          rsa.ImportRSAPublicKey(Convert.FromBase64String(stringPublickey),out _);<br><br>          return rsa.Encrypt(bytePlainText,RSAEncryptionPadding.Pkcs1);<br>      }<br>  }<br>}</pre><p>here is the curl for clarity :</p><pre>curl --request POST \<br>--url http://localhost:5120/User/encryptWithRSA \<br>--header &#39;AuthorizedKey: -----BEGIN RSA PUBLIC KEY-----\nMIIBCgKCAQEAvh4dnEytfFf9yzw6He/fw8hximVkB28Rc0uBhDGU33cW+DXPGkwS\nFbNa8KGyODOtX7GwuG5/ZWFtM4LtH8hzxEEm4wnvRCCqFiHvsLC6T17R9iKuN7+u\nOAthm5xa+z+Egicymyzw9P4FsGqABtttdNc5wv8xokr31lbBsKkF7RsPGzqmMJxQ\nwzzCLRGCGaXxvi4L2RvmSNQ8JK26X+E9G6W5MZ/zHIgJ9CMmqWdhgj3SsPZiKpb+\njWQTvi+0m0lSRxzDHJcG70VXkdYAAjbArN1E6Z+wotNdXku3wx8z+Po4xZyj03RT\nhMVPqWcD/GmlWJ1lYQhCsVFdBghcsXQpLQIDAQAB\n-----END RSA PUBLIC KEY-----&#39; \<br>--header &#39;Content-Type: application/json&#39; \<br>--header &#39;User-Agent: insomnia/10.2.0&#39; \<br>--data &#39;&quot;another hello world&quot;&#39;</pre><p>the result : <br>plaint text : “another hello world”<br>encrypted to : zLTWdaQALaQDyISl8iI49fYUawtD61+a5yIee7N896j3LEbntF2zsJ1Reno31jCOl8rAPS7NgSQqpZoMpt5nSmuAcP/B7KQomMHrhajQq143sP7OHEYWo+0eIaDY6HHnAR/WpG6jD2v2PReLY5frJoM/cYikfbMJVo4647dDawljWZcQqJ5ZUAzYd7jTLM7XLHxhW1iH1zM4bbsdIKk05NhqQheoInZ9vHj2+t5xkxQ+TeTA9Lr1BTjOPOARrGCgiITnylSalTPuOj+JqFKWOse5Xmb4pyQfPcv0RnFL8ZAPryyy2tx9j21AoXjZabOCsaC++qYwa7VRRn15z1YwQ==<br>decrypted back to : “another hello world”</p><p>for the decryption, use the private key on the header :</p><pre>[HttpPost]<br>[Route(&quot;[controller]/decryptWithRSA&quot;)]<br>public string decryptWithRSA([FromBody] string stringRequest)<br>{        <br>    string stringAuthKey = Request.Headers[&quot;AuthorizedKey&quot;];        <br>    string stringPrivateKey = stringAuthKey<br>    .Replace(&quot;-----BEGIN RSA PRIVATE KEY-----&quot;, &quot;&quot;)<br>    .Replace(&quot;-----END RSA PRIVATE KEY-----&quot;, &quot;&quot;)<br>    .Replace(&quot;\\n&quot;, &quot;&quot;)<br>    .Replace(&quot;\r&quot;, &quot;&quot;);<br><br>    string stringDecrypted = Decryption.DecryptWithRSA(stringRequest,stringPrivateKey);<br>                    <br>    return stringDecrypted;<br>}</pre><pre>public class Decryption<br>{<br>  //WRAPPER<br>  public static string DecryptWithRSA(string cipherText, string privateKey)<br>  {<br>      byte[] cipherBytes = Convert.FromBase64String(cipherText);<br><br>      // Decrypt the byte array to a string.<br>      string decryptedString = DecryptWithRSA(cipherBytes, privateKey);<br><br>      return decryptedString;<br>  }<br>}</pre><pre>public class Decryption<br>{<br>  private static string DecryptWithRSA(byte[] cipherText, string privateKey)<br>  {<br>      using (RSA rsa = RSA.Create())<br>      {            <br>          rsa.ImportRSAPrivateKey(Convert.FromBase64String(privateKey),out _ );<br><br>          return Encoding.UTF8.GetString(rsa.Decrypt(cipherText,RSAEncryptionPadding.Pkcs1));            <br>      }<br>  }<br>}</pre><p>the curl :</p><pre>curl --request POST \<br>--url http://localhost:5120/User/decryptWithRSA \<br>--header &#39;AuthorizedKey: -----BEGIN RSA PRIVATE KEY-----\nMIIEpAIBAAKCAQEAvh4dnEytfFf9yzw6He/fw8hximVkB28Rc0uBhDGU33cW+DXP\nGkwSFbNa8KGyODOtX7GwuG5/ZWFtM4LtH8hzxEEm4wnvRCCqFiHvsLC6T17R9iKu\nN7+uOAthm5xa+z+Egicymyzw9P4FsGqABtttdNc5wv8xokr31lbBsKkF7RsPGzqm\nMJxQwzzCLRGCGaXxvi4L2RvmSNQ8JK26X+E9G6W5MZ/zHIgJ9CMmqWdhgj3SsPZi\nKpb+jWQTvi+0m0lSRxzDHJcG70VXkdYAAjbArN1E6Z+wotNdXku3wx8z+Po4xZyj\n03RThMVPqWcD/GmlWJ1lYQhCsVFdBghcsXQpLQIDAQABAoIBAASmQmWf528+zKVj\nge1ZADEuzf4LODzJTdUyv8ZemwwzAqQL1taHDTssIXl4jt36f48zToXYJ/PwA8Zq\neYeZNKGUUVHknI4fOWGkr1K0I75MrJhXJUkWPjm/J4IxevUhislPEZkDaponOzbj\nB+IDDER6/f3jlVBpgnGiugZqv8saX0AxF+rZf5QOCEt9fnOdPyvQVO0P5BN5Pq78\n4m6oUy1P3SxbQi9qMNS0IRIrJYchNYWwQRiamUF5zd+fcpDAawr5WWeXNwt32ME0\noR0TO0wGzAMLWaAPv5xC3VRffXzd/34i7sGgGFl3BUYz1PUM272wflECJvUHv2tC\n5drn0nECgYEA6JayjaTlfR6wuhL2ZJLEWkf5o+Mf6k+4Hg77JmNen7Hp0uQk97Qt\nk9DFPJhciwdhPh/OFF20q+yXGs00cnYZH5RiTI3aXsiMot7UPRNtfFttQZMs5OyZ\nyHrcaekkRimZF+x4+gB9Ig1Wpzy21twDKc/111KfYkStasBhaUl+5bECgYEA0UEI\nVodBXDMVlEwiO3+AjYJX6B4aygpjh5YQ6KJYExGjizlTcX82w3ZPiPxc8f0KPNBx\nxagyKwEbBbskhHCAX4S0abWSMCsNKj+0H7NaZdvxyKn3ilu4fvbs367NoQt6d5j7\nRRuf3gpSEZuro3ZIP3gqVEZ6c7O5t5JPSGlTzj0CgYAzVuA+x8EoJxgXWowskwDo\ndK6z8DRhQguABwqE5LZERb85H8bRLmJJGHIQ+AilX5GlZtvUPwLcWDLaZaVIBq1w\n/Q3dnAoxlc8FPG5YtOsb4gpxyQzF0zv2trfkYOPy4Me8MiRZ+rWkSJFyBMLPFm1U\nU2UOjFxGEqa8w4488U4jYQKBgQDDz9ZMmk74RzlnR4M1KBAU26cFJ76r1+LhSvVR\nrDE8zuG6c495ArEtYXX12ynirIY6+FeuvcEMawFtcH0wjdIjEBx/WxCMkIzGP0x/\n6aaq8JGl1B83UrMn5Esu2fXEQOh+KCLhvYLxFblMjt6jnRjog7sgl78YrFMazAfy\n29U3hQKBgQCtV6GbqvOvlhEUAAy6Oyetb2PN3W0Yy1DnrAQIwEynEqvVcFMjIZOr\n+M7prmFlmq4tarzLjp629Lk9kaLKpmV0KZQKFXBd49SMMqycfbTIF5F77+j0ZqDU\nm6s/QyejPlnA41HkqUz68TV2hTIgqMN7S1O8q25U+kAm+2p4v5/Dug==\n-----END RSA PRIVATE KEY-----&#39; \<br>--header &#39;Content-Type: application/json&#39; \<br>--header &#39;User-Agent: insomnia/10.2.0&#39; \<br>--data &#39;&quot;nzLTWdaQALaQDyISl8iI49fYUawtD61+a5yIee7N896j3LEbntF2zsJ1Reno31jCOl8rAPS7NgSQqpZoMpt5nSmuAcP/B7KQomMHrhajQq143sP7OHEYWo+0eIaDY6HHnAR/WpG6jD2v2PReLY5frJoM/cYikfbMJVo4647dDawljWZcQqJ5ZUAzYd7jTLM7XLHxhW1iH1zM4bbsdIKk05NhqQheoInZ9vHj2+t5xkxQ+TeTA9Lr1BTjOPOARrGCgiITnylSalTPuOj+JqFKWOse5Xmb4pyQfPcv0RnFL8ZAPryyy2tx9j21AoXjZabOCsaC++qYwa7VRRn15z1YwQ==&quot;&#39;</pre><p>Conclusion : As you can see from the two example of encryption, using asymmetric encryption (RSA) have a longer encrypted result, it’s not a perfect fits to encrypt a large plain text, such as your user address, because large result == large computation and most likely slower encryption process compared to the symmetric (AES), its better to use symmetric encryption to store your user data cause it will be faster and efficient for large data (due to scalability and mathematical operation, unless your company has a massive storage and definitely rich :) but hey don’t forget the slower operation point).</p><p>Asymmetric encryption is preferred to encrypt the SSL/TLS key exchange, but we can combine the Asymmetric and Symmetric encryption for Hybrid encryption to secure the data that we are about to stored in the database by using RSA to encrypt the <strong>stringKeyEncrypt (secret key) </strong>before we use the key to actually encrypt the data with Symmetric Encryption.</p><p>That’s what it took to store your sensitive user data safely, there are many attack out there but at least you have encrypted the sensitive information and there are no system can guarantee 100% safety, the effectiveness of encryption depends on factors like key management, implementation, and technological advancements. The combination of both algorithms (e.g., RSA for key exchange and AES for data encryption) offers strong security in many applications, but they are not immune to future technological threats.</p><p>Thank you for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9457a1ae25dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Efficiently Updating and Deleting Data in Entity Framework Core with ExecuteUpdate and…]]></title>
            <link>https://medium.com/@an.karenina/efficiently-updating-and-deleting-data-in-entity-framework-core-with-executeupdate-and-22ca54cec5aa?source=rss-a0d3c2d73eef------2</link>
            <guid isPermaLink="false">https://medium.com/p/22ca54cec5aa</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[entity-framework-core]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <dc:creator><![CDATA[Anna]]></dc:creator>
            <pubDate>Sat, 09 Mar 2024 09:48:19 GMT</pubDate>
            <atom:updated>2024-03-09T09:48:19.385Z</atom:updated>
            <content:encoded><![CDATA[<h3>Efficiently Updating and Deleting Data in Entity Framework Core with ExecuteUpdate and ExecuteDelete</h3><p>As a backend developer we frequently use select and update query in our daily basis, In Entity Framework Core (EF Core), we lean on SaveChanges() to persist our modifications within the database context.</p><p>When we use EF to interact with data, it keeps track of any modifications made to entities (objects representing database rows). This includes additions, updates, and deletions. EF uses a concept called “change tracking” to manage these modifications. EF provides a method called SaveChanges() on the DbContext object. This method iterates through the tracked changes and translates them into appropriate database operations (INSERT, UPDATE, DELETE) based on the entity’s state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wbvms9Py3FulteIYJdkTYw.png" /><figcaption>insert query using Language-Integrated Query (LINQ)</figcaption></figure><p>The query above will be translate into :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3_wyklF0-fMtpqjyB_BmCQ.png" /><figcaption>translated query on sql server profiler</figcaption></figure><p>To update the specific user data, we can use this query :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8ZQQanoxXu_jOlSmhBLdBQ.png" /></figure><p>And the translated query goes :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J4AN7JuA4V0zNyxUl1nXiA.png" /></figure><p>from the updateUser query we can see that there are two operation happen in database, which are SELECT and UPDATE, Obviously we just want to update one specific user data that’s why we should use the unique column as the parameter for the select query and then we updated the specific column that we want. EF’s queries are tracking by default, meaning that EF tracks the loaded entities in its internal <em>change tracker </em>that’s why we can directly re-assign the value of the <strong>modelUserResult </strong>and then when we call the SaveChanges method and the updates will be saved.</p><p>in terms of Big O, that was a O(n+2) step taken, in <strong>EF Core 7.0</strong> we can make it efficient using <strong>ExecuteUpdate</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EU8YmZoMVg5C_GRgpHYr8A.png" /><figcaption>Execute update</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6HZI1M84P7Zblt58F8JDGg.png" /><figcaption>translated execute update query</figcaption></figure><p>when using ExecuteUpdate there is only one database operation which means its a O(n) step taken, that’s a performance improvement!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*Qz_oh7a4B97NeM8T" /><figcaption>img source : <a href="https://media.licdn.com/">https://media.licdn.com</a></figcaption></figure><p>What about deletion? Let say we want to delete all the user who exactly have the same FirstName</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*H9SwmlZ-xNHYViBWH4SaGA.png" /></figure><p>Well..there are many approach but i have two most used approach, here are the queries :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0L6FDeRbEioaQPawF93CTg.png" /><figcaption>delete with Remove method</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Eh-ks2z5BqGZS4Xpw2liyw.png" /><figcaption>delete with RemoveRange method</figcaption></figure><p>Both approach have the same translated query :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FvvOJ0MUDOywue_Ly_BosA.png" /><figcaption>translated query of deletion</figcaption></figure><p>which means having the same Big O notation = O(N+2), we can make it efficient by using <strong>ExecuteDelete, </strong>with even more simple code where we no longer needed the SaveChanges method to execute the update that we made on the entity <strong>:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*31U01R1y9F37L-voCm5MuQ.png" /><figcaption>delete with ExecuteDelete method</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pSHRoGWuncvuOMoN3r9sMg.png" /><figcaption>translated query of ExecuteDelete method</figcaption></figure><p>As we can see, the ExecuteDelete method only took one database operation which makes the Big O notation to be O(1), another performance improvement!</p><p>Maybe it does not seem to be a significant performance improvement if we have little to medium amount to data, but let’s try it with 200k data and compare the time and operation result.</p><p>Here is the comparations result of SaveChanges() vs ExecuteDelete/Update with sample of 200k row of Data</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DJJC5fQHEfpHjpSLU6nAug.png" /><figcaption>Data sample</figcaption></figure><p>Delete operation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DfrybmoH2QOWTMXjywchCQ.png" /><figcaption>Start of Execution using SaveChanges()</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nR15rdJyBqqEw3xzdnuIZA.png" /><figcaption>End of Execution using SaveChanges()</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UDClWWtzUFFTM1LUNTzNuA.png" /><figcaption>ExecuteDelete with 200K data</figcaption></figure><p>The operation took around <strong>1</strong> <strong>minute</strong> as it started at 15:58 and finished at 15:19 as it use the SaveChanges method, but it is being optimized by ExecuteDelete to only <strong>1 Millisecond</strong></p><p>Update operation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*isnsO3kPtA6Eq0A1kWuGuQ.png" /><figcaption>Start of Execution</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iFwmoRn5z-BqVeh_By6rDg.png" /><figcaption>End of Execution</figcaption></figure><p>The operation took around <strong>2 minute</strong> as it started at 15:16 and finished at 15:18, even worst is that the method create around 4k row of update operation into the database, which is crazy🤯</p><p>and it’s even more crazy that ExecuteUpdate could optimized it into around <strong>3 Millisecond</strong> and took only one update operation to the database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SeEscxYsJYlUJcK-0ViXrw.png" /><figcaption>ExecuteUpdate with 200K data</figcaption></figure><p>As powerful as it looks, Execute method also have trade off, which are :</p><ol><li>Multiple invocations of these methods cannot be batched. Each invocation performs its own roundtrip to the database.</li><li>ExecuteUpdate and ExecuteDelete can only execute on one table a.k.a it cannot be use by joining child table.</li><li>For insertion, still need the SaveChanges method</li><li>These methods currently only work with relational database providers.</li></ol><p>You can consider to use Execute method if you wish to change a potentially large number of entities based on some criterion, example : you want to update every employee email that end with @olddomain to a @newdomain123</p><p>Thank you for reading! please let me know if there is anything i can improve.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22ca54cec5aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Simplest Way to Use Preferences DataStore]]></title>
            <link>https://medium.com/@an.karenina/the-simplest-way-to-use-preferences-datastore-1083d23fade2?source=rss-a0d3c2d73eef------2</link>
            <guid isPermaLink="false">https://medium.com/p/1083d23fade2</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[jetpack-datastore]]></category>
            <category><![CDATA[sharedpreferences]]></category>
            <dc:creator><![CDATA[Anna]]></dc:creator>
            <pubDate>Sun, 12 Nov 2023 11:04:10 GMT</pubDate>
            <atom:updated>2023-11-12T11:07:25.603Z</atom:updated>
            <content:encoded><![CDATA[<p>As per August 2021, Android has release the new library called J<a href="https://developer.android.com/jetpack/androidx/releases/datastore">etpack DataStore</a>, it is a new and improved data storage solution aimed at replacing SharedPreferences, Built on Kotlin coroutines and Flow.</p><p>Well.. as it said, this DataStore is aimed to replace SharedPreferences, which means SharedPref will get deprecated in anytime soon :( which means i have to migrate :( which means… i hate migration:( haha but yea it is what it is, as a developer <em>we have to keep ourselves updated with the latest technology, right?</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*nx_qAqtiI_S4WaS2iMZDyg.jpeg" /><figcaption>Source : Twitter</figcaption></figure><p>Now, let’s delve into the two types of DataStore:</p><ol><li><strong>Preferences DataStore</strong>: Similar to SharedPreferences, it stores data using a key-value format without the need to define a specific schema.</li><li><strong>Proto DataStore</strong>: It persists strongly-typed data that requires a schema using Protocol Buffers.</li></ol><p>Here are the differences between those 3 :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VyDuwT7Z8Lo0oz8hizxe_w.png" /><figcaption>Source : <a href="https://developer.android.com/">Developers Android</a></figcaption></figure><p>Since we are focusing on Preferences DataStore, add the following dependency to your <strong>build.gradle</strong>:</p><pre>implementation &quot;androidx.datastore:datastore-preferences-core:1.0.0&quot;</pre><p>To use Preferences DataStore, create an instance of DataStore using property delegation with <strong>preferencesDataStore</strong> and <strong>Context</strong> as the receiver:</p><pre>class MainActivity : BaseActivity() <br>{<br>    // Other declarations...<br>    <br>    companion object <br>    {<br>        private val Context.preferencesDataStore: DataStore&lt;Preferences&gt; by preferencesDataStore(name = STRING_DATASTORE_NAME)<br>        val keyOnBoardingSession = booleanPreferencesKey(STRING_ONBOARDING_SESSION)<br>    }<br>    // Other code...<br>}</pre><p>Ensure that there’s only a <strong>single instance</strong> of <strong>preferencesDataStore</strong> for a given file (in this case, the MainActivity file) to avoid errors, if not we will get the error of :</p><p>“There are multiple DataStores active for the same file: /data/user/0/com.nextint.learncrypto.app/files/datastore/test2.preferences_pb. You should either maintain your DataStore as a singleton or confirm that there is no two DataStore’s active on the same file (by confirming that the scope is cancelled).”</p><p>For simplicity i put it on companion object as a static property.</p><p>Next, create functions to save and read data:</p><pre>suspend fun &lt;T&gt; saveValue(key : Preferences.Key&lt;T&gt;, value: T)<br>{<br>    preferencesDataStore.edit { setting -&gt;<br>        setting[key] = value<br>    }<br>}</pre><pre>suspend fun &lt;T&gt; readValue(key: Preferences.Key&lt;T&gt;) : T?<br>{<br>    val result = preferencesDataStore.data.catch { exception -&gt;<br>        if (exception is IOException)<br>        {<br>            emit(emptyPreferences())<br>        }<br>        else<br>        {<br>            throw  exception<br>        }<br>    }.first()[key]<br><br>    return result<br>}</pre><p>Since preferencesDataStore.data is a Flow, these functions must be called inside a suspend function, and for reusability i use generic type as the parameters.</p><p>In this case, i am going to call the saveValue function from HomeFragment,</p><pre>class HomeFragment : BaseFragment&lt;OverviewViewModel&gt;() <br>{<br> // Other code...<br>  lifecycleScope.launch(Dispatchers.IO)<br>  {<br>      _activityMain.saveValue(MainActivity.keyOnBoardingSession,true)<br>  }<br> // Other code...<br>}</pre><p>and call the readValue function from the MainActivity cause i need the value to check if the user have passed the on boarding screen or not</p><pre>class MainActivity : BaseActivity()<br>{<br>// Other code...<br>  lifecycleScope.launch(Dispatchers.IO) <br>  {<br>    booleanOnBoarding = readValue(keyOnBoardingSession) ?: false<br>  }<br>// Other code...<br>}</pre><p>If the user has passed the onboarding screen, the <strong>booleanOnBoarding</strong> value will be true.</p><p>Additionally, the Android linter is intelligent enough to detect mismatches between key and value data types, providing helpful error messages.</p><pre>_activityMain.saveValue(stringPreferencesKey(&quot;key1&quot;),&quot;value1&quot;)<br>_activityMain.saveValue(booleanPreferencesKey(&quot;key2&quot;),&quot;true&quot;)<br>_activityMain.saveValue(intPreferencesKey(&quot;key3&quot;),true)</pre><p>it shows the error <em>“Type mismatch. Required: Boolean Found:String” </em>etc.</p><p>In conclusion, this approach allows you to call <strong>saveValue</strong> and <strong>readValue</strong> functions anywhere, as long as you have access to where the instance of <strong>preferencesDataStore</strong> is declared. Keep in mind that DataStore is ideally suited for simple or small data; for partial updates, referential integrity, or large/complex datasets, consider using <a href="https://developer.android.com/jetpack/androidx/releases/room">Room</a> instead.</p><p>Thank you for reading! please let me know if there is anything i can improve. You can find the source code <a href="https://github.com/itsannazzle/Learn-Crypto">here</a> for learning purpose only.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1083d23fade2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cross server connection with .NET 7.0]]></title>
            <link>https://medium.com/@an.karenina/cross-server-connection-with-net-7-0-c8ef2a79960a?source=rss-a0d3c2d73eef------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8ef2a79960a</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[servers]]></category>
            <category><![CDATA[aspnet-mvc]]></category>
            <category><![CDATA[aspnetcore]]></category>
            <dc:creator><![CDATA[Anna]]></dc:creator>
            <pubDate>Sat, 02 Sep 2023 16:31:19 GMT</pubDate>
            <atom:updated>2023-09-04T15:44:00.174Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NEMH9geYmIXIycXA" /><figcaption>Photo by <a href="https://unsplash.com/@tvick?utm_source=medium&amp;utm_medium=referral">Taylor Vick</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Cross server connection with .NET 7.0</h3><p>Long story short, I had my own belief that ‘a woman being a backend dev is freakin cool,’ and I asked the lead backend developer at my office to teach me. After around 3 weeks of learning, he said, ‘Let’s involve you in a real backend project.’ I was like… damn, wtf? I was just learning for fun, and now I’m a backend developer 🥲. And this was one of the things that I learned.</p><p>Let’s say we have 2 servers: the first one is the Transaction server, and the other one is the Users server. Every time we want to perform a transaction, we need to validate whether the request is coming from our registered user or not.</p><p>On the transaction server, we have the <strong>‘insertTransaction’</strong> API.</p><pre>[ApiController]<br><br>public class TransactionController : BaseController<br>{<br>    string _hostUrl = WebAddressConstant.STRING_SCHME_HTTP + WebAddressConstant.STRING_SCHME_LOCALHOST + WebAddressConstant.STRING_PORT_KIDZ;<br>    JsonSerializerOptions serializerOptions = new JsonSerializerOptions{ PropertyNameCaseInsensitive = true };<br>    public TransactionQuery _transactionQuery;<br>    public TransactionController(DatabaseContex databaseContex) : base(databaseContex)<br>    {<br>        _transactionQuery = new TransactionQuery(databaseContex);<br>    }<br>    [HttpPost]<br>    [Route(&quot;[controller]/insertTransaction&quot;)]<br><br>    public String insertTransaction([FromBody] String stringRequest)<br>    {<br>        HitHistoryModel modelHitHistory = new HitHistoryModel();<br>        ResultHistoryModel modelResultHistory = new ResultHistoryModel();<br>        TransactionModel modelTransactionRequest = new TransactionModel();<br>        UserModel modelUser = new UserModel();<br>        ResponseModel modelResponse = new ResponseModel();<br>        RequestModel modelRequest = new RequestModel();<br>        String stringRequestDecoded = &quot;&quot;;<br>        bool boolException = false;<br>        bool boolValidation = true;<br><br>        string stringToken = Request.Headers[&quot;Token&quot;];<br><br>        try<br>        {<br>            stringRequestDecoded = base64Decode(stringRequest);<br>            modelRequest.Data = stringRequestDecoded;<br>            modelTransactionRequest = JsonSerializer.Deserialize&lt;TransactionModel&gt;(stringRequestDecoded, serializerOptions);<br>        }<br>        catch (Exception exception)<br>        {<br>            modelResponse.MessageContent = exception.Message;<br>            modelResponse.MessageTitle = StringConstant.STRING_MESSAGE_TITLE_FAIL;<br>            modelRequest.Data = exception.Message;<br>            modelResponse.Data = exception.Message;<br>            boolException = true;<br>        }<br><br>        modelHitHistory.setHitHistoryFromRequest(modelRequest,_hostUrl+&quot;/insertTransaction&quot;);<br>        _hitHistoryQuery.insertHistory(modelHitHistory);<br><br>        if(!boolException)<br>        {<br>            if(!string.IsNullOrEmpty(stringToken))<br>            {<br>                if(stringToken == modelTransactionRequest.CreatedBy)<br>                {<br>                    RequestModel modelRequestToUser = new();<br>                    ResponseModel modelResponseFromUser = new();<br>                    UserModel modelUserRequest = new UserModel<br>                    {<br>                        Token = stringToken<br>                    };<br>                    UserModel modelUserResponse = new UserModel();<br><br>                    string stringModelUser = JsonSerializer.Serialize&lt;UserModel&gt;(modelUserRequest);<br>                    string stringModelUserEncoded = base64Encode(stringModelUser);<br><br>                    modelRequestToUser.Data = stringModelUserEncoded;<br><br>                    string stringModelRequest = JsonSerializer.Serialize&lt;RequestModel&gt;(modelRequestToUser);<br><br>                    modelResponseFromUser = UtilityFunction.callInternalService(WebAddressConstant.STRING_SCHME_HTTP + WebAddressConstant.STRING_SCHME_LOCALHOST + WebAddressConstant.STRING_PORT_KIDZ + WebAddressConstant.STRING_KIDZ_VALIDATEUSERTOKEN,stringModelRequest);<br><br>                    if(modelResponseFromUser != null)<br>                    {<br>                        if(modelResponseFromUser.ServiceResponseCode == ServiceResponseCodeConstant.STRING_RESPONSECODE_MODULE_SUCCESS &amp;&amp; !string.IsNullOrEmpty(modelResponseFromUser.Data))<br>                        {<br>                            modelUserResponse = JsonSerializer.Deserialize&lt;UserModel&gt;(modelResponseFromUser.Data, serializerOptions);<br><br>                        }<br>                        else<br>                        {<br>                            boolValidation = false;<br>                            //failed to get user<br>                        }<br>                    }<br>                    else<br>                    {<br>                        boolValidation = false;<br>                        //response empty from user server<br>                    }<br><br>                    if(boolValidation)<br>                    {<br>                        if(modelUserResponse.Token == modelTransactionRequest.CreatedBy)<br>                        {<br>                            if(_transactionQuery.insertTransaction(modelTransactionRequest))<br>                            {<br>                                modelTransactionRequest.Token = base64Encode(modelTransactionRequest.ID.ToString());<br><br>                                modelResponse.ServiceResponseCode = ServiceResponseCodeConstant.STRING_RESPONSECODE_MODULE_SUCCESS;<br>                                modelResponse.MessageContent = StringConstant.STRING_MESSAGE_CONTENT_SUCCESS;<br>                                modelResponse.MessageTitle = StringConstant.STRING_MESSAGE_TITLE_SUCCESS;<br><br>                            }<br>                            else<br>                            {<br>                                modelResponse.ServiceResponseCode = ServiceResponseCodeConstant.STRING_RESPONSECODE_MODULE_FAIL;<br>                                modelResponse.MessageContent = StringConstant.STRING_MESSAGE_CONTENT_INSERTFAIL;<br>                                modelResponse.MessageTitle = StringConstant.STRING_MESSAGE_TITLE_FAIL;<br>                            }<br>                        }<br>                        else<br>                        {<br>                            //user invalid<br>                        }<br>                    }<br>                }<br>                else<br>                {<br>                    // user invalid<br>                }<br>            }<br>            else<br>            {<br>                //header token not found<br>            }<br>            <br>        }<br><br>        modelResultHistory.setResultHistoryModel(modelResponse);<br>        _resultHistoryQuery.insertResultHistory(modelResultHistory);<br><br>        return base64Encode(JsonSerializer.Serialize&lt;ResponseModel&gt;(modelResponse));<br>    }<br>}<br></pre><p>From the code snippet above, we can see the function callInternalService connecting to the User server (I named it KIDZ, sorry for the random server name) by sending the server information along with the serialized request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IKl7lYo0wH8P5eIXcxzBBQ.png" /></figure><p>And this is how we actually made the connection to the User server, using StringContent as the request with the application/json format, and we called it using HttpClient. In this context, we are trying to call the validateUserToken API, and we will receive the result in an HttpResponseMessage.</p><pre>public static ResponseModel callInternalService(string stringURL, String stringRequest)<br>{<br>    JsonSerializerOptions serializerOptions = new()<br>    {<br>        PropertyNameCaseInsensitive = true,<br>    };<br>    ResponseModel modelResponse = new ResponseModel();<br>    string stringEncodedRequest;<br>    HttpClient client = new();<br>    Uri uri = new(stringURL);<br><br>    try<br>    {<br>        using StringContent content = new(JsonSerializer.Serialize(stringRequest),UnicodeEncoding.UTF8,&quot;application/json&quot;);<br><br>        HttpResponseMessage httpResponseMessage = client.PostAsync(uri, content).Result;<br><br>        Console.Write(httpResponseMessage.StatusCode);<br><br>        httpResponseMessage.EnsureSuccessStatusCode();<br><br>        string stringResult = httpResponseMessage.Content.ReadAsStringAsync().Result;<br><br>        if(!string.IsNullOrEmpty(stringResult))<br>        {<br>            modelResponse = JsonSerializer.Deserialize&lt;ResponseModel&gt;(stringResult,serializerOptions);<br>        }<br>        else<br>        {<br>            modelResponse.ServiceResponseCode = ServiceResponseCodeConstant.STRING_RESPONSECODE_MODULE_FAIL;<br>        }<br>    }<br>    catch (Exception exception)<br>    {<br><br>        Console.WriteLine(&quot;error message : &quot;+exception.Message);<br>    }<br><br>    return modelResponse;<br>}</pre><p>And this is how the validateUserToken API looks on the User server.</p><pre>[HttpPost]<br>[Route(&quot;[controller]/validateUserToken&quot;)]<br>public ResponseModel validateUserToken([FromBody] String stringRequest)<br>{<br>    RequestModel _modelRequest = new RequestModel();<br>    ResponseModel _modelResponse = new ResponseModel();<br>    bool _boolException = false;<br>    string _stringRequestDecoded = &quot;&quot;;<br><br>    try<br>    {<br>        _stringRequestDecoded = base64Decode(stringRequest);<br>    }<br>    catch (Exception exception)<br>    {<br>        _boolException = true;<br>        _modelResponse.MessageContent = exception.Message;<br>        _modelResponse.MessageTitle = StringConstant.STRING_MESSAGE_TITLE_FAIL;<br>        _modelResponse.Data = exception.Message;<br>    }<br><br>    if(!_boolException)<br>    {<br>         if(!(string.IsNullOrEmpty(_stringRequestDecoded)))<br>        {<br>            _modelRequest = JsonSerializer.Deserialize&lt;RequestModel&gt;(_stringRequestDecoded);<br>            UserModel modelUserData = JsonSerializer.Deserialize&lt;UserModel&gt;(_modelRequest.Data);<br>            UserModel modelUser = _userQuery.selectUserByToken(modelUserData);<br><br>            if( modelUser != null)<br>            {<br>                _modelResponse.ServiceResponseCode = ServiceResponseCodeConstant.STRING_RESPONSECODE_MODULE_SUCCESS;<br>                _modelResponse.MessageContent = StringConstant.STRING_MESSAGE_CONTENT_SUCCESS;<br>                _modelResponse.MessageTitle = StringConstant.STRING_MESSAGE_TITLE_SUCCESS;<br>                _modelResponse.Data = JsonSerializer.Serialize(modelUser);<br>            }<br>            else<br>            {<br>                _modelResponse.ServiceResponseCode = ServiceResponseCodeConstant.STRING_RESPONSECODE_MODULE_FAIL;<br>                _modelResponse.MessageContent = StringConstant.STRING_MESSAGE_CONTENT_FAIL;<br>                _modelResponse.MessageTitle = StringConstant.STRING_MESSAGE_TITLE_FAIL;<br>                _modelResponse.Data = JsonSerializer.Serialize(modelUser);<br>            }<br>        }<br>        else<br>        {<br>            _modelResponse.ServiceResponseCode = ServiceResponseCodeConstant.STRING_RESPONSECODE_MODULE_SUCCESS;<br>            _modelResponse.MessageContent = StringConstant.STRING_MESSAGE_CONTENT_DATAEMPTY;<br>            _modelResponse.MessageTitle = StringConstant.STRING_MESSAGE_TITLE_FAIL;<br>        }<br>    }<br><br>    return _modelResponse;<br>}</pre><p>That’s it; validating the user who made the API request is one of the most important things to do. It’s crucial to ensure that the request was made by an authorized user registered in our database. I mean… who knows if there is some man-in-the-middle attack, right? Safety first.</p><p>This was the basic simple example, what actually going on the server is soooo much more complicated but i hope you get the idea of it.</p><p>You can see the full code here :<br><a href="https://github.com/itsannazzle/Kidz">User server</a><br><a href="https://github.com/itsannazzle/Backend_101">Transaction server</a></p><p>will prolly deploy it to GCP once i <em>seriously</em> learn about Cloud computing but idk when haha. Thanks for reading, have a great day.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8ef2a79960a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Maximizing Efficiency: Using a Single Adapter for Different View Holders in RecyclerView]]></title>
            <link>https://medium.com/@an.karenina/maximizing-efficiency-using-a-single-adapter-for-different-view-holders-in-recyclerview-b4af05afd0ae?source=rss-a0d3c2d73eef------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4af05afd0ae</guid>
            <category><![CDATA[recyclerview]]></category>
            <category><![CDATA[adapter-recyclerview]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[viewholder]]></category>
            <category><![CDATA[efficiency]]></category>
            <dc:creator><![CDATA[Anna]]></dc:creator>
            <pubDate>Sat, 19 Aug 2023 13:56:16 GMT</pubDate>
            <atom:updated>2023-08-20T05:08:50.094Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi, it’s been ages since the last time I write something here.</p><p>As an android developer, we are often dealing with Recycler View that needs an Adapter which chained with View Holder to Bind the data.. like always. Those are components that can’t be separated when it comes to implementing a list of data. In this article I want to share a little tips on how we can optimize the code by using only one Adapter to achieve so.</p><p><strong>First thing first</strong></p><p>Create the view with ConstraintLayout and RecyclerView in it. Here I take one from my simple project called ‘<a href="https://github.com/itsannazzle/Learn-Crypto">Learn Crypto</a>’</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;androidx.constraintlayout.widget.ConstraintLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;<br>    xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;<br>    android:layout_marginStart=&quot;@dimen/dimen_16&quot;<br>    android:layout_marginEnd=&quot;@dimen/dimen_16&quot;<br>    android:layout_marginTop=&quot;@dimen/dimen_16&quot;<br>    tools:context=&quot;.features.coins.CoinsFragment&quot;&gt;<br><br>    &lt;TextView<br>        android:id=&quot;@+id/textViewCoins&quot;<br>        style=&quot;@style/title&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:text=&quot;@string/coins&quot;<br>        android:textColor=&quot;@color/black&quot;<br>        app:layout_constraintStart_toStartOf=&quot;parent&quot;<br>        app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt;<br><br>    &lt;androidx.recyclerview.widget.RecyclerView<br>        android:id=&quot;@+id/recylerViewCoins&quot;<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;0dp&quot;<br>        android:layout_marginTop=&quot;@dimen/dimen_8&quot;<br>        app:layout_constraintStart_toStartOf=&quot;parent&quot;<br>        app:layout_constraintTop_toBottomOf=&quot;@id/textViewCoins&quot;<br>        app:layout_constraintBottom_toBottomOf=&quot;parent&quot;<br>        app:layout_constraintEnd_toEndOf=&quot;parent&quot;<br>        tools:listitem=&quot;@layout/item_coins_layout&quot;/&gt;<br><br>    &lt;ProgressBar<br>        android:id=&quot;@+id/progressBar&quot;<br>        style=&quot;?android:attr/progressBarStyle&quot;<br>        android:layout_width=&quot;wrap_content&quot;<br>        android:visibility=&quot;gone&quot;<br>        android:layout_height=&quot;wrap_content&quot;<br>        android:indeterminateTint=&quot;@color/primary&quot;<br>        app:layout_constraintBottom_toBottomOf=&quot;parent&quot;<br>        app:layout_constraintEnd_toEndOf=&quot;parent&quot;<br>        app:layout_constraintStart_toStartOf=&quot;parent&quot;<br>        app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt;<br><br>&lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;</pre><p>and the item layout</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;com.google.android.material.card.MaterialCardView xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;<br>    xmlns:tools=&quot;http://schemas.android.com/tools&quot;<br>    android:id=&quot;@+id/card_coins&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;wrap_content&quot;<br>    android:layout_marginBottom=&quot;@dimen/dimen_8&quot;<br>    android:backgroundTint=&quot;@color/primaryAccent&quot;<br>    app:cardCornerRadius=&quot;15dp&quot;&gt;<br><br>    &lt;androidx.constraintlayout.widget.ConstraintLayout<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;match_parent&quot;<br>        android:padding=&quot;8dp&quot;&gt;<br><br>        &lt;TextView<br>            android:id=&quot;@+id/coin_name&quot;<br>            style=&quot;@style/title&quot;<br>            android:layout_width=&quot;wrap_content&quot;<br>            android:maxEms=&quot;5&quot;<br>            android:maxLines=&quot;2&quot;<br>            android:layout_height=&quot;wrap_content&quot;<br>            android:textColor=&quot;@color/black&quot;<br>            app:layout_constraintStart_toStartOf=&quot;parent&quot;<br>            app:layout_constraintTop_toTopOf=&quot;parent&quot;<br>            tools:text=&quot;Bitcoin&quot; /&gt;<br><br>        &lt;include<br>            android:id=&quot;@+id/status_active&quot;<br>            layout=&quot;@layout/item_indicator_status_layout&quot;<br>            android:layout_width=&quot;wrap_content&quot;<br>            android:layout_height=&quot;wrap_content&quot;<br>            android:layout_marginTop=&quot;@dimen/dimen_4&quot;<br>            android:layout_marginStart=&quot;@dimen/dimen_8&quot;<br>            app:layout_constraintStart_toEndOf=&quot;@+id/coin_name&quot;<br>            app:layout_constraintTop_toTopOf=&quot;@+id/coin_name&quot; /&gt;<br><br>        &lt;include<br>            android:id=&quot;@+id/status_new&quot;<br>            layout=&quot;@layout/item_indicator_status_layout&quot;<br>            android:layout_width=&quot;wrap_content&quot;<br>            android:layout_height=&quot;wrap_content&quot;<br>            android:layout_marginTop=&quot;@dimen/dimen_4&quot;<br>            android:layout_marginStart=&quot;@dimen/dimen_4&quot;<br>            app:layout_constraintStart_toEndOf=&quot;@+id/status_active&quot;<br>            app:layout_constraintTop_toTopOf=&quot;@+id/coin_name&quot; /&gt;<br><br>        &lt;TextView<br>            android:id=&quot;@+id/coin_symbol&quot;<br>            android:layout_width=&quot;wrap_content&quot;<br>            android:layout_height=&quot;wrap_content&quot;<br>            android:layout_marginTop=&quot;@dimen/dimen_4&quot;<br>            android:textAppearance=&quot;@style/TextAppearance.MaterialComponents.Body1&quot;<br>            app:layout_constraintStart_toStartOf=&quot;parent&quot;<br>            app:layout_constraintTop_toBottomOf=&quot;@id/coin_name&quot;<br>            tools:text=&quot;BTC&quot; /&gt;<br><br>        &lt;TextView<br>            android:id=&quot;@+id/label_coin_type&quot;<br>            android:layout_width=&quot;wrap_content&quot;<br>            android:layout_height=&quot;wrap_content&quot;<br>            android:layout_marginTop=&quot;@dimen/dimen_4&quot;<br>            android:text=&quot;@string/type&quot;<br>            android:textAppearance=&quot;@style/TextAppearance.MaterialComponents.Body1&quot;<br>            app:layout_constraintStart_toStartOf=&quot;parent&quot;<br>            app:layout_constraintTop_toBottomOf=&quot;@+id/coin_symbol&quot; /&gt;<br><br><br>        &lt;TextView<br>            android:id=&quot;@+id/textView7&quot;<br>            android:layout_width=&quot;wrap_content&quot;<br>            android:layout_height=&quot;wrap_content&quot;<br>            android:text=&quot;@string/rank&quot;<br>            android:textAppearance=&quot;@style/TextAppearance.MaterialComponents.Headline6&quot;<br>            app:layout_constraintEnd_toEndOf=&quot;parent&quot;<br>            app:layout_constraintTop_toTopOf=&quot;parent&quot; /&gt;<br><br>        &lt;TextView<br>            android:id=&quot;@+id/coin_rank&quot;<br>            android:layout_width=&quot;wrap_content&quot;<br>            android:layout_height=&quot;wrap_content&quot;<br>            android:layout_marginTop=&quot;2dp&quot;<br>            android:textAppearance=&quot;@style/TextAppearance.MaterialComponents.Headline6&quot;<br>            app:layout_constraintEnd_toEndOf=&quot;@+id/textView7&quot;<br>            app:layout_constraintStart_toStartOf=&quot;@+id/textView7&quot;<br>            app:layout_constraintTop_toBottomOf=&quot;@+id/textView7&quot;<br>            tools:text=&quot;1&quot; /&gt;<br>    &lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;<br><br><br>&lt;/com.google.android.material.card.MaterialCardView&gt;</pre><p><strong>next the most important, create the BaseAdapter.kt</strong></p><pre>class BaseAdapter&lt;Model : Any, ViewHolder : RecyclerView.ViewHolder&gt;<br>    (<br>    private val onCreateViewHolder : (parent : ViewGroup, viewType : Int) -&gt; ViewHolder,<br>    private val onBindViewHolder : (viewHolder : ViewHolder, position : Int, item : Model) -&gt; Unit,<br>    private val differCallback  : DiffUtil.ItemCallback&lt;Model&gt;,<br>    private val onViewType : ((viewType : Int, item : List&lt;Model&gt;) -&gt; Int)? = null,<br>    private val onDetachFromWindow : ((ViewHolder) -&gt; Unit)? = null<br>    ) : RecyclerView.Adapter&lt;ViewHolder&gt;() <br>    {<br>        var item = listOf&lt;Model&gt;()<br>        private var onGetItemViewType: ((position : Int) -&gt; Int)? = null<br>        val differ = AsyncListDiffer(this, differCallback)<br><br>        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder = onCreateViewHolder.invoke(parent,viewType)<br><br>        override fun onBindViewHolder(holder: ViewHolder, position: Int) <br>        {<br>            val item = differ.currentList[position]<br>            onBindViewHolder.invoke(holder,position, item)<br>        }<br>        <br>        override fun getItemCount(): Int = differ.currentList.size<br>       <br>        override fun getItemViewType(position: Int): Int <br>        {<br>            return if (onViewType != null) <br>            {<br>                onViewType.invoke(position, item)<br>            } else <br>            {<br>                val onGetItemViewType = onGetItemViewType<br>                onGetItemViewType?.invoke(position) ?: super.getItemViewType(position)<br>            }<br>        }<br><br>        override fun onViewDetachedFromWindow(holder: ViewHolder) <br>        {<br>            super.onViewDetachedFromWindow(holder)<br>            onDetachFromWindow?.invoke(holder)<br>        }<br>    }</pre><p>i will explain the BaseAdapter.kt sequentially,</p><p>the BaseAdapter.kt class have 2 generic parameter <strong>&lt;Model : Any, ViewHolder : RecyclerView.ViewHolder&gt; </strong>specifies the type parameters for the class. Model is a type parameter that represents the data model, and ViewHolder is a type parameter that represents the ViewHolder type.</p><p>5 constructor parameter with a <a href="https://kotlinlang.org/docs/lambdas.html"><em>Higher Order Function</em></a> as the parameters type except for the <strong>differCallback </strong>it takes DiffUtil.ItemCallback as the parameter type, the first 3 of them is non null parameter.</p><p><strong>onCreateViewHolder</strong>:<br>A lambda that takes a parent ViewGroup and a viewType Int as parameters, and returns a ViewHolder. It’s responsible for inflating the layout and creating a new ViewHolder instance.</p><p><strong>onBindViewHolder:</strong><br>A lambda that takes a viewHolder, position, and an item of type Model as parameters. It’s responsible for binding data to the ViewHolder at a given position.</p><p><strong>differCallback</strong>:<br>An instance of DiffUtil.ItemCallback&lt;Model&gt; used for calculating the difference between old and new data items. It’s used to efficiently update the RecyclerView’s items.</p><p>we are using DiffUtil here to <a href="https://medium.com/bootcampers/meningkatkan-peforma-recyclerview-dengan-diffutil-3392b7fdf358">optimizing the performance of RecylerView</a>, read more about DiffUtil in the amazing article by kak Vero.</p><p><strong>onViewType (optional):</strong><br>A lambda that takes a viewType and a list of Model items, and returns a viewType as an Int. This can be used to define different view types within the adapter.</p><p><strong>onDetachFromWindow (optional):</strong><br>A lambda that takes a ViewHolder as a parameter. It’s called when a ViewHolder is detached from the window, which can be useful for performing cleanup.</p><p>The class extends <strong>RecyclerView.Adapter&lt;ViewHolder&gt;()</strong>, which means it’s inheriting from the RecyclerView.Adapter class and is specialized to work with the provided ViewHolder type.</p><p>enough for the parameters, lets see what the class do. There are some variable declaration : <br><strong>item</strong> is a private property that holds the list of data items that will be displayed by the adapter.<br><strong>onGetItemViewType</strong> is a lambda that determines the view type for a given position. It takes a position and returns a view type integer. This lambda is set to null initially and can be customized externally.<br><strong>differ</strong> is an instance of AsyncListDiffer, a utility class that calculates differences between old and new lists efficiently. It uses a differCallback to detect changes.</p><p>and some Overridden function which are :<br><strong>onCreateViewHolder:</strong><br>This function is overridden to create a ViewHolder using the onCreateViewHolder lambda that was provided when constructing the adapter. It uses the invoke function of the lambda to create the ViewHolder.<br><strong>onBindViewHolder:</strong><br>This function is overridden to bind data to a ViewHolder using the onBindViewHolder lambda provided when constructing the adapter. It retrieves the current item from the AsyncListDiffer and invokes the lambda with the ViewHolder and item.<br><strong>getItemCount:<br></strong>do i really have to explain this one? lol jk, as the name itself it is use to return the size of the current list managed by the AsyncListDiffer.<br><strong>getItemViewType:<br></strong>This function is overridden to determine the view type of a particular item at a given position. It first checks if the onViewType lambda is provided. If it is, it invokes the lambda with the position and the item list. If not, it either uses the custom onGetItemViewType lambda if provided, or falls back to the default behavior.<br>last but not least,<strong> onViewDetachedFromWindow:<br></strong>This function is overridden to handle the detachment of a ViewHolder from the window. It invokes the onDetachFromWindow lambda if provided.</p><p>move to the next step, let’s create the ViewHolder Class, this class is basically to inflate the item layout into the view holder, declare the diff util callback, data binding from model to item layout and defining the click action.</p><pre>class CoinViewHolder(itemView : View) : RecyclerView.ViewHolder(itemView)<br>{<br>    companion object<br>    {<br>        fun inflate(parent  : ViewGroup) : CoinViewHolder<br>        {<br>            return CoinViewHolder(LayoutInflater.from(parent.context)<br>                    .inflate(R.layout.item_coins_layout,parent,false)<br>            )<br>        }<br><br>        val differCallback = object : DiffUtil.ItemCallback&lt;CoinsResponseItem&gt;(){<br>            override fun areItemsTheSame(oldItem: CoinsResponseItem, newItem: CoinsResponseItem): Boolean <br>            {<br>                return oldItem.id == newItem.id<br>            }<br><br>            override fun areContentsTheSame(oldItem: CoinsResponseItem, newItem: CoinsResponseItem): Boolean <br>            {<br>                return oldItem == newItem<br>            }<br>        }<br>    }<br><br>    fun bind(coinsResponseItem: CoinsResponseItem)<br>    {<br>        with(itemView)<br>        {<br>            coinsResponseItem.apply()<br>            {<br>                findViewById&lt;TextView&gt;(R.id.coin_name).text = name<br>                findViewById&lt;TextView&gt;(R.id.coin_rank).text = rank.toString()<br>                findViewById&lt;TextView&gt;(R.id.coin_symbol).text = symbol<br>                findViewById&lt;TextView&gt;(R.id.label_coin_type).text = resources.getString(R.string.type, type)<br>                findViewById&lt;CardView&gt;(R.id.status_active).findViewById&lt;TextView&gt;(R.id.textViewStatus).text = resources.getString(UtilitiesFunction.convertBooleanToActiveOrNotActive(isActive))<br>                if (isNew)<br>                {<br>                    findViewById&lt;CardView&gt;(R.id.status_new).findViewById&lt;TextView&gt;(R.id.textViewStatus).text = resources.getString(UtilitiesFunction.convertBooleanToNew(isNew))<br>                    findViewById&lt;CardView&gt;(R.id.status_new).setCardBackgroundColor(resources.getColor(R.color.teal_700))<br>                }<br>                else<br>                {<br>                    findViewById&lt;CardView&gt;(R.id.status_new).findViewById&lt;TextView&gt;(R.id.textViewStatus).visibility = View.GONE<br>                }<br>            }<br>        }<br>    }<br><br>    fun setAction(action : (position : Int) -&gt; Unit)<br>    {<br>        itemView.setOnClickListener()<br>        {<br>            action.invoke(adapterPosition)<br>        }<br><br>    }<br>}</pre><p>Now let’s see how we can use the Adapter over and over again with different types of Model and ViewHolder.</p><p>In the CoinsFragment Class, call the BaseAdapter, define the Model as well as the ViewHolder and setup the adapter just like this code below.</p><pre>class CoinsFragment : BaseFragment&lt;CoinsViewModel&gt;() <br>{<br>    private var _bindingCoinsFragment : FragmentCoinsBinding? = null<br>    private val _getbindingCoinsFragment get() = _bindingCoinsFragment<br><br>    private lateinit var _coinAdapter : BaseAdapter&lt;CoinsResponseItem, CoinViewHolder&gt;<br>    private val _lazyCoinAdapter by lazy { _coinAdapter }<br><br>    override fun onViewCreated(view: View, savedInstanceState: Bundle?)<br>    {<br>        super.onViewCreated(view, savedInstanceState)<br>        setupAdapter()<br>        displayView()<br>        observeLiveData()<br>    }<br><br>    private fun setupAdapter()<br>    {<br>        _coinAdapter = BaseAdapter(<br>            { parent, _ -&gt; CoinViewHolder.inflate(parent) },<br>            { viewHolder, _, item -&gt; viewHolder.bind(item)<br>                viewHolder.setAction {<br>                    val bundle = Bundle()<br>                    bundle.putString(ID_COIN_CONSTANT,item.id)<br>                    UtilitiesFunction.replaceFragment(parentFragmentManager, CoinDetailFragment(),bundle)<br>                }<br>            },<br>            CoinViewHolder.differCallback<br>        )<br>    }<br><br>   private fun observeLiveData()<br>   {<br>      _viewModel.coins.observe(viewLifecycleOwner)<br>      { response -&gt;<br>          when(response)<br>          {<br>              is ApiResponse.Success -&gt;<br>              {<br>                  _activityMain._dialog.hide()<br>                  response.data?.let { _lazyCoinAdapter.differ.submitList(it) }<br>              }<br>          }<br>      }<br>   }<br><br>  private fun displayView()<br>  {<br>      _bindingCoinsFragment?.recylerViewCoins.apply {<br>          this?.setVertical()<br>          this?.adapter = _lazyCoinAdapter<br>      }<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*NaR6XSmOJXxAZbyV0RSiIg.png" /></figure><p>That’s really it, the next time you have another Recycler View with a different Item Layout, all you have to do is just create the View Holder and then call the BaseAdapter and define the Model as well as the ViewHolder, no more creating the Adapter.</p><p>Thank you for reading, if there is any misconception/misunderstanding or anything i can improve please let me know so i can do better :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4af05afd0ae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is being successful really means?]]></title>
            <link>https://medium.com/@an.karenina/what-is-being-successful-really-means-4d9ca5733a89?source=rss-a0d3c2d73eef------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d9ca5733a89</guid>
            <category><![CDATA[careers]]></category>
            <category><![CDATA[success]]></category>
            <dc:creator><![CDATA[Anna]]></dc:creator>
            <pubDate>Sat, 16 Jul 2022 06:53:07 GMT</pubDate>
            <atom:updated>2022-07-16T06:53:07.846Z</atom:updated>
            <content:encoded><![CDATA[<p>Yesterday I took a bus and train to get home (as usual) and it took me a 4-hour trip😭 such a long Friday, but the trip wasn’t really boring cause my senior co-worker(who stopped by the same train station as I’m) just popped out in the bus shelter. We talked a lot and mostly about careers, he told me how he started his career in our company and how he spent 12 years in it, it amazed me and actually makes me think “How could you stay in one place for so long?” he started from the bottom, as the company grow.. so he is and turned out our company treated him very well with the salary, the bonuses + incentives and soo many other benefits that makes me “no wonder he stays for 12 years”.</p><p>As I get home, I kept thinking.. did I took the wrong step to begin my career? Should I stay and be loyal to one company for so long? Could i reach that successful point as he had? But if i look back to the moment where i started my career, most of my friends said “You are a successful person now” or “You work in high building, you already successful now” or “Your job is really cool, you must made a lot of money from it” honestly it makes me feel like I have reached the successful standard that most people have, but have i actually reached my own successful standard? I..don’t know, i found it quite hard to define my own success. Mostly i found myself not even close to success if i compare my career and achievements to others.</p><p>I understand people have different standards for success, some are working in a high building, some are bought stuff from those fancy luxury brands, some are getting a promotion, some are getting a job, and some are surviving through the day. The more I compare the more I realize there are so many factors to reach the success standard, we might take the same path, the same journey, the same destination but who knows if we found an even better destination on our way there, as well as broken road, flood or even disaster, it is something that we could not predict accurately, all we gotta do is keep going until we reach the success point.</p><p>When I look at the people around me, i found myself feeling left behind, Why are they moving so fast? Why is my pace slow? Why is it not happening to me as it is happening to them? Is there anything did i do wrong? Did i made a mistake? Did i don’t deserve it? As those questions popped up frequently in my head, i remember the day when i had my first period, people my age have had their first period like a year or two before mine, i was thingking if it’s normal or maybe i got some dissease, but when the day has finally come, i realize that nothing is wrong with it, it just the matter of time, just because your timing was not the same as they are..doesn’t mean you are late, just because it tooks you some times to reached some points..doesn’t mean you failed, things takes time to process, things take time to grow and so is our career, achievement and success, all we gotta do is keep going, moving forward and keep progressing. Maybe in our point view when looking at other people life is seems all fun and gems, rainbow and butterflies but who knows what kind of thing they have been through to reached their success. I’m sure my senior co-worker have gone through a lot in his 12 years of career.</p><p>I think success is a never-ending destination, and at this point, my destination is to survive through the day while learning new things on my way home.</p><p>I wonder what will happend to me in the next 12 years, Will i stay for one company for so long? Will i reach my success standard? I hope i could go back to this little post 12 years later, i’m super excited to see but super scared at the same time.</p><p>How about you, what is your success standard? Have you reach it?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d9ca5733a89" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>