<?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 Sharath Holla on Medium]]></title>
        <description><![CDATA[Stories by Sharath Holla on Medium]]></description>
        <link>https://medium.com/@ksholla20?source=rss-3191fa972fa7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*XPuXCNGnAxporFdd</url>
            <title>Stories by Sharath Holla on Medium</title>
            <link>https://medium.com/@ksholla20?source=rss-3191fa972fa7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 15:21:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ksholla20/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[Sharing code between web and native projects of React in a Monorepo]]></title>
            <link>https://medium.com/@ksholla20/sharing-code-between-web-and-native-projects-of-react-in-a-monorepo-5b6e3b09d315?source=rss-3191fa972fa7------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b6e3b09d315</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[yarn-workspace]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[monorepo]]></category>
            <dc:creator><![CDATA[Sharath Holla]]></dc:creator>
            <pubDate>Fri, 22 Nov 2019 09:48:19 GMT</pubDate>
            <atom:updated>2019-11-22T09:48:19.598Z</atom:updated>
            <content:encoded><![CDATA[<p>Suppose you or your team is developing a e-commerce website. Interaction of buyers and sellers with the app will be different. Hence you might develop two different WebApps for these. In addition, you will be developing mobile apps too. How do we structure our app code repositories in such cases?</p><p>One approach is to have 2 different repos for these WebApps. Clean and simple. To maintain coherence between visuals of these apps, there will be many components which would be same, or similar. In order to avoid duplication of work, we can extract out these common components into a different repo and include it in our app projects as external dependency. As the project grows, one might split this common repo into multiple different projects to maintain some logical boundaries. Also, if we want to publish few independent shareable components into public or private npm repo, there will be further more repositories. Suppose there is a change in one of these components, then to upgrade all the dependent projects, we need to upgrade version in each projects, raise a PR for each of them, have a code reviewer sign off these changes, and merge each of them to master individually.</p><p>Other approach is to maintain all these projects in a monorepo.</p><h3>Monorepo</h3><p>As per <a href="https://en.wikipedia.org/wiki/Monorepo">Wikipedia</a>,</p><blockquote>A monorepo (syllabic abbreviation of monolithic repository) is a software development strategy where code for many projects are stored in the same repository. As of 2017 this software engineering practice was over a decade old, but had only recently been named.<br>Google, Facebook, Microsoft, Uber, Airbnb and Twitter all employ very large monorepos with varying strategies to scale build systems and version control software with a large volume of code and daily changes.</blockquote><p>A clarification here is that monorepo is not monolith. Each packages will have it’s own boundary and independence, along with ease of code and knowledge sharing between projects and teams respectively.</p><p>If the projects are yarn based, then we have <strong><em>yarn workspaces</em></strong> as one of the ways to maintain a monorepo.</p><p><strong>Project structure:<br></strong>Typical repo structure will be as below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*wn9EmdD3VQ0rAKPGz6Wjcg.png" /></figure><p>Here, <strong><em>React App 1</em></strong> uses shared component <strong><em>Common 1</em></strong>. When added as dependency in React App 1, a symlink of Common 1 is created in node_modules of React App 1.</p><p>In this article, we will create a monorepo containing a basic react app, a react native app, and a common shared project, which exposes a function that will be used by react and react native apps.</p><h3>Getting Started with code</h3><p><strong>Basic Structure for Mono repo:</strong></p><p>Let’s start with creating a Monorepo folder</p><pre>mkdir &lt;folder_name&gt;</pre><p>Initialize a yarn package. Make sure that private flag is true</p><pre>cd &lt;folder_name&gt;<br>yarn init</pre><p>Create a folder called packages. This will host all the different web and native packages</p><pre>mkdir packages</pre><p>To support yarn workspaces, add following code to package.json</p><pre>“workspaces”: {<br>    “packages”: [<br>        “packages/*”<br>    ],<br>    “nohoist”: []<br>},</pre><p><strong>Create React Native Mobile App:</strong></p><p>Let’s create a react native app. I will be using create-react-native-cli to create the app. One catch in creation of package is in the install of react-native package. Due to Hoisting, the packages will be installed in node modules of root folder of the monorepo project. However, the create-react-native-cli expects react-native package to be in app node modules. More details on Hoisting is explained <a href="https://yarnpkg.com/blog/2018/02/15/nohoist/">here</a>.</p><p>To avoid this issue, we need to add react native packages in nohoist list of root package.json</p><pre>“nohoist”: [“**/react-native”, “**/react-native/**”]</pre><p>We will then create a react native app.</p><pre>cd packages<br>react-native init mobile</pre><p>This will create a react native app. You can test the app by running on a simulator</p><pre>cd mobile<br>yarn run android</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/1*D04KCkm32VmxDAP3fX4Jyw.png" /><figcaption>Screenshot of default react native app</figcaption></figure><p>The code checkpoint is pushed <a href="https://github.com/ksholla20/react-native-react-monorepo-starter/tree/v1.0">here</a></p><p><strong>Create React Web App:</strong></p><p>This step is pretty easy.</p><pre>cd ..<br>npx create-react-app web</pre><p>We can test the app</p><pre>cd web<br>yarn start</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LNIMBHoeO8tb_OWsfDsJCQ.png" /><figcaption>Default WebApp screenshot</figcaption></figure><p>The code checkpoint is pushed <a href="https://github.com/ksholla20/react-native-react-monorepo-starter/tree/v2.0">here</a></p><p><strong>Creating a common code and calling it from Apps</strong></p><p>We will start with creating a common project to share code between web and mobile.</p><p>Let’s create a project and add some exportable code</p><pre>cd .. //This will take to packages folder<br>mkdir common<br>yarn init<br>mkdir src</pre><p>In source folder, let’s create a file named main.js, with following content</p><pre>//packages/common/src/main.js</pre><pre>export const getWelcomeString = (name) =&gt;{<br>    return `Welcome ${name} to our project`<br>}</pre><p>We will use this function in our mobile and web projects</p><p>Starting with native, let us include ‘<em>common</em>’ package in dependency section of package.json</p><pre>//dependency section of packages/mobile/package.json</pre><pre>“dependencies”: {<br>    “react”: “16.9.0”,<br>    “react-native”: “0.61.4”,<br><strong><em>    “common”: “1.0.0”</em></strong><br>},</pre><p>When we do yarn build after this, a symlink will be created in node_modules of root.</p><p>The default packager in a React Native app created by cli, is Metro bundler. We need to configure this bundler to use files from outside the project. Hence change the metro.config.js to following. <strong><em>(This is the key change to be done for this to work)</em></strong></p><pre>//packages/mobile/metro.config.js</pre><pre>/**<br>* Metro configuration for React Native<br>* <a href="https://github.com/facebook/react-native">https://github.com/facebook/react-native</a><br>*<br>* @format<br>*/</pre><pre><strong><em>const path = require(&#39;path&#39;);</em></strong></pre><pre>module.exports = {<br>  transformer: {<br>    getTransformOptions: async () =&gt; ({<br>      transform: {<br>        experimentalImportSupport: false,<br>        inlineRequires: false,<br>      },<br>    }),<br>  },<br><strong><em>  resolver: {<br>    extraNodeModules: new Proxy(<br>      {},<br>      {<br>        get: (target, name) =&gt; {<br>          return path.join(__dirname, `node_modules/${name}`);<br>        },<br>      },<br>    ),<br>  },<br>  watchFolders: [path.resolve(__dirname, &#39;../&#39;)],<br></em></strong>};</pre><p>Let’s now use the imported module in Native code (App.js) (Changes Highlighted)</p><pre>//packages/mobile/App.js<br>/**<br>* Sample React Native App<br>* <a href="https://github.com/facebook/react-native">https://github.com/facebook/react-native</a><br>*<br>* @format<br>* @flow<br>*/</pre><pre>import React from &#39;react&#39;;</pre><pre>import {<br>  SafeAreaView,<br>  StyleSheet,<br>  ScrollView,<br>  View,<br>  Text,<br>  StatusBar,<br>} from &#39;react-native&#39;;</pre><pre>import {<br>  Header,<br>  LearnMoreLinks,<br>  Colors,<br>  DebugInstructions,<br>  ReloadInstructions,<br>} from &#39;react-native/Libraries/NewAppScreen&#39;;</pre><pre><strong><em>import {getWelcomeString} from &#39;common/src/main&#39;;</em></strong></pre><pre>const App: () =&gt; React$Node = () =&gt; {<br>  return (<br>    &lt;&gt;<br>      &lt;StatusBar barStyle=&quot;dark-content&quot; /&gt;<br>      &lt;SafeAreaView&gt;<br>        &lt;ScrollView<br>          contentInsetAdjustmentBehavior=&quot;automatic&quot;<br>          style={styles.scrollView}&gt;<br>          &lt;Header /&gt;<br>          {global.HermesInternal == null ? null : (<br>            &lt;View style={styles.engine}&gt;<br>              &lt;Text style={styles.footer}&gt;Engine: Hermes&lt;/Text&gt;<br>            &lt;/View&gt;<br>          )}<br>          &lt;View style={styles.body}&gt;<br>            &lt;View style={styles.sectionContainer}&gt;<br><strong><em>              &lt;Text style={styles.sectionDescription}&gt;{getWelcomeString(&quot;World&quot;)}&lt;/Text&gt;<br>              </em></strong>&lt;Text style={styles.sectionTitle}&gt;Step One&lt;/Text&gt;<br>              &lt;Text style={styles.sectionDescription}&gt;<br>                Edit &lt;Text style={styles.highlight}&gt;App.js&lt;/Text&gt; to change this<br>                screen and then come back to see your edits.<br>              &lt;/Text&gt;<br>            &lt;/View&gt;<br>            &lt;View style={styles.sectionContainer}&gt;<br>              &lt;Text style={styles.sectionTitle}&gt;See Your Changes&lt;/Text&gt;<br>              &lt;Text style={styles.sectionDescription}&gt;<br>                &lt;ReloadInstructions /&gt;<br>              &lt;/Text&gt;<br>            &lt;/View&gt;<br>            &lt;View style={styles.sectionContainer}&gt;<br>              &lt;Text style={styles.sectionTitle}&gt;Debug&lt;/Text&gt;<br>              &lt;Text style={styles.sectionDescription}&gt;<br>                &lt;DebugInstructions /&gt;<br>              &lt;/Text&gt;<br>            &lt;/View&gt;<br>            &lt;View style={styles.sectionContainer}&gt;<br>              &lt;Text style={styles.sectionTitle}&gt;Learn More&lt;/Text&gt;<br>              &lt;Text style={styles.sectionDescription}&gt;<br>                Read the docs to discover what to do next:<br>              &lt;/Text&gt;<br>            &lt;/View&gt;<br>            &lt;LearnMoreLinks /&gt;<br>          &lt;/View&gt;<br>        &lt;/ScrollView&gt;<br>      &lt;/SafeAreaView&gt;<br>    &lt;/&gt;<br>  );<br>};</pre><pre>const styles = StyleSheet.create({<br>  scrollView: {<br>    backgroundColor: Colors.lighter,<br>  },<br>  engine: {<br>    position: &#39;absolute&#39;,<br>    right: 0,<br>  },<br>  body: {<br>    backgroundColor: Colors.white,<br>  },<br>  sectionContainer: {<br>    marginTop: 32,<br>    paddingHorizontal: 24,<br>  },<br>  sectionTitle: {<br>    fontSize: 24,<br>    fontWeight: &#39;600&#39;,<br>    color: Colors.black,<br>  },<br>  sectionDescription: {<br>    marginTop: 8,<br>    fontSize: 18,<br>    fontWeight: &#39;400&#39;,<br>    color: Colors.dark,<br>  },<br>  highlight: {<br>    fontWeight: &#39;700&#39;,<br>  },<br>  footer: {<br>    color: Colors.dark,<br>    fontSize: 12,<br>    fontWeight: &#39;600&#39;,<br>    padding: 4,<br>    paddingRight: 12,<br>    textAlign: &#39;right&#39;,<br>  },<br>});</pre><pre>export default App;</pre><p>Running the react native app should reflect the new changes</p><pre>cd ../mobile //this will take to packages/mobile folder<br>yarn<br>yarn run android</pre><p>Following is the screen shot. Notice the addition of sentence “Welcome World to our project”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/1*95kjkxLf1xqG6hOJUw39vw.png" /><figcaption>Screen shot of mobile app after changes</figcaption></figure><p>Similarly, let’s do changes in web app</p><pre>//packages/web/package.json dependency section<br>“dependencies”: {<br>  &quot;react&quot;: &quot;^16.12.0&quot;,<br>  &quot;react-dom&quot;: &quot;^16.12.0&quot;,<br>  &quot;react-scripts&quot;: &quot;3.2.0&quot;,<br>  <strong><em>“common”: “1.0.0”</em></strong><br>},</pre><p>And the App.js code</p><pre>//packages/web/App.js<br>import React from &#39;react&#39;;<br>import logo from &#39;./logo.svg&#39;;<br>import &#39;./App.css&#39;;<br><strong><em>import {getWelcomeString} from &#39;common/src/main&#39;;</em></strong></pre><pre>function App() {</pre><pre>  return (<br>    &lt;div className=&quot;App&quot;&gt;<br>      &lt;header className=&quot;App-header&quot;&gt;<br>        &lt;img src={logo} className=&quot;App-logo&quot; alt=&quot;logo&quot; /&gt;<br>        <strong><em>&lt;p&gt;{getWelcomeString(&quot;World&quot;)}&lt;/p&gt;</em></strong><br>        &lt;p&gt;<br>          Edit &lt;code&gt;src/App.js&lt;/code&gt; and save to reload.<br>        &lt;/p&gt;<br>        &lt;a<br>          className=&quot;App-link&quot;<br>          href=&quot;https://reactjs.org&quot;<br>          target=&quot;_blank&quot;<br>          rel=&quot;noopener noreferrer&quot;<br>        &gt;<br>          Learn React<br>        &lt;/a&gt;<br>      &lt;/header&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><pre>export default App;</pre><p>Building and running this app will reflect the changes done</p><pre>yarn<br>yarn start</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IR56IJh2t9BJKDcEdtITRQ.png" /><figcaption>Screen shot of WebApp with changes</figcaption></figure><p>The code checkpoint is pushed <a href="https://github.com/ksholla20/react-native-react-monorepo-starter/tree/v3.0">here</a></p><h3>Conclusion</h3><p>We just saw a way to create and use monorepos for react and react native projects. During our development, we faced issue in creating and using React Native project in Yarn Workspaces. The steps described above were used to overcome these issues. The code is hosted in github at <a href="https://github.com/ksholla20/react-native-react-monorepo-starter">https://github.com/ksholla20/react-native-react-monorepo-starter</a></p><p>Monorepo, overall, is a nice technique to maintain large projects, individual teams can work independently on respective projects and reuse goodness developed by other teams in their projects.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b6e3b09d315" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design and implement a Caching library]]></title>
            <link>https://medium.com/@ksholla20/design-and-implement-a-caching-library-e456b0f6449f?source=rss-3191fa972fa7------2</link>
            <guid isPermaLink="false">https://medium.com/p/e456b0f6449f</guid>
            <category><![CDATA[cache]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[lfu-cache]]></category>
            <category><![CDATA[lru-cache]]></category>
            <category><![CDATA[design-process]]></category>
            <dc:creator><![CDATA[Sharath Holla]]></dc:creator>
            <pubDate>Wed, 02 Oct 2019 16:28:08 GMT</pubDate>
            <atom:updated>2019-10-02T16:28:08.897Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the common question in a design round interview is to design a caching library. In this article, I have tried to address this question.</p><p>Disclaimer: I had failed in an interview with one of the FAANG companies, where this question was asked. After coming out of interview, I gave an afterthought, and came up with this design.</p><p>C++ implementation of this code is shared in git. github link for same is <a href="https://github.com/ksholla20/cachelib">here</a></p><h3>What is cache?</h3><p>As in <a href="https://en.wikipedia.org/wiki/Cache_(computing)">Wikipedia</a>, a cache is a hardware or software component that stores data so that future requests for that data can be served faster; the data stored in a cache might be the result of an earlier computation or a copy of data stored elsewhere.</p><p>In simple terms, a cache is a key value store to access frequently required data. Instead of accessing database or computing a data every time, such data can be stored in a cache, for easy retrieval.</p><h3>Types of caches</h3><p><strong>In-Process cache:<br></strong>These are local caches where an application instantiates, manages and runs it’s own cache, with code residing inside the application or as a 3rd party dynamic library. As cache shares memory with the application, multiple instances of application will be maintaining it’s own cache instance, leading to data duplication. Such kind of caches are useful in end user applications like mobile apps, or web apps.</p><p><strong>Distributed Caching:<br></strong>When we are dealing with back end applications catering thousands to million requests per seconds, we would require dedicated machines to handle caching. Also, with multiple nodes trying to access database, a common cache across instances becomes a necessity. In such cases, a separate hardware with dedicated resources like flash, SSD, etc, can be used for better and faster throughput.</p><p>In this article, we are dealing with design of an in-process cache.</p><h3>Cache hit, miss, eviction</h3><p>Data in Cache is stored as key-value format, where data is stored as value and a unique key is associated with it to access. If requested key is present, cache hit occurs and associated value is returned. If requested key is not present, cache miss occurs. In this case, required value is calculated or fetched from database, and put back in cache.<br>However, Cache will be having limited memory. Hence to store the new value, some existed key-value pair should be removed. This is called eviction. There are various eviction strategies: Least Recently Used (LRU), Least Frequently Used (LFU), Most Recently Used (MRU), etc. In this article, we target LRU and LFU.</p><h3>Cache library Design Overview</h3><p>As an end user, what all functions are to be exposed?<br>1. <em>put(key, value)</em> to create or update a key-value pair<br>2. <em>get(key)</em> to return a value for a given key<br>3. <em>delete(key)</em> to hard delete a particular value pair<br>4. <em>clear()</em> to clear all data from cache.</p><p>Data in cache might turn stale after some time. Actual data in database would have changed. For some data, like company logo, or product images, data does not change very often. In such cases, a TTL (Time To Live) comes handy.</p><p>To implement TTL, signature of put would change, where another argument for TTL will be sent.</p><h3>Implement different Eviction strategy</h3><p>In current article, we try to implement 2 eviction strategies. LRU and LFU. To achieve the same, <em>factory pattern</em> will be used. A virtual base class of Cache will be implemented, with above mentioned functions as interface and the 2 different cache implementations will inherit from this.</p><pre>// cache.h<br>#pragma once</pre><pre>#include &lt;string&gt;<br>#include &lt;memory&gt;<br>constexpr auto MAX_CACHE_SIZE = 4096;<br>using namespace std;</pre><pre>enum CacheType {<br>LRU_CACHE,<br>LFU_CACHE<br>};</pre><pre>class Cache;<br>typedef shared_ptr&lt;Cache&gt; CachePtr;</pre><pre>class Cache<br>{<br>public:<br>    Cache(int size = MAX_CACHE_SIZE);<br>    virtual string get(string key) = 0;<br>    virtual void put(string key, string value, int ttl = -1) = 0;<br>    virtual void deleteKey(string key) = 0;<br>    virtual void clear() = 0;<br>    static CachePtr getCache(CacheType c, int size = MAX_CACHE_SIZE);<br>    ~Cache();<br>};</pre><h3>LRU Cache Implementation</h3><p><strong>Data-structures<br></strong>Queue (Using Doubly Linked List) — The node value containing key and value pair is stored as a queue. The queue is implemented using a Doubly Linked List (DLL), which allows easy manipulation of the queue.<br>Map — This has map of key to the node in DLL.</p><p><strong>Implementation details<br></strong><em>put</em>: Any new entry to the cache is put to the back of the DLL. If the size of DLL exceed the max cache size, eviction of front of the node is done. This ensures that the oldest node is removed, while newest entries are at the back of the queue. When there is an update, the value of the node is changed, and the node is pushed to the back of the queue.<em><br>get</em>: Using the map, the DLL node extracted using the key. The value to the key can be extracted using this node. Also, node is taken out of DLL and pushed to the back of the DLL, making it the most recent node.<br><em>delete</em>: The node is removed from DLL, and corresponding entry is deleted from the map<br><em>clear</em>: All nodes of DLL is deleted, and the map is emptied</p><p>Code for this is check pointed <a href="https://github.com/ksholla20/cachelib/tree/V1.0">here</a></p><h3>LFU Cache Implementation</h3><p><strong>Data-structures<br></strong>Map— Key to Value map is used<br>Map — Key to count map. The count here is the frequency count of usage/access of the key.<br>Map — Count to Key map. As this is a one to many relation (Many keys can have same frequency count), keys are stored in doubly linked list of keys</p><p><strong>Implementation details<br></strong><em>put</em>: Any new entry to the cache, a key-value pair is added to corresponding map. In count map, a new entry with count 1 is added at the back of the DLL. In count to key map, a new entry of key is added against entry of 1. If the size exceeds max size, we go to the lowest count entry in count to key map. Then the key is removed from front of the queue. This ensures that Lest recently used in the least frequently used keys is removed. Corresponding entries of other maps are removed<br><em>get</em>: key-value map contains the return value. We then increment the frequency count in key to count map. In count to key map, we remove entry from old count DLL and add to new count DLL<br><em>delete</em>: key value is deleted from all maps<br><em>clear</em>: All nodes of all DLL in count-key map are deleted, and all maps are emptied</p><p>The code is check pointed <a href="https://github.com/ksholla20/cachelib/tree/V2.0">here</a>.</p><h3>TTL Implementation</h3><p>There are many ways of implementing TTL.<br>One of the most common way is a reactive way, wherein when get of the key is called ttl is checked and is and deleted is key has expired.<br>Another way is a proactive way where, entry is deleted as soon as expiry is hit.<br>In this implementation, we have taken pseudo proactive way, where whenever any call is made to the library, all expired entries are removed.</p><p><strong>Details<br></strong>A min heap is maintained to store TTL values. Top of the tree denotes which is the next key to be removed. During any call to the library, Top of the heap is examined and corresponding entries are deleted</p><h3>Conclusion</h3><p>We have discussed here one of the ways of designing a Cache. Neither the design is feature complete nor the code is production ready. It is just a proof of concept. The final code is shared <a href="https://github.com/ksholla20/cachelib">here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e456b0f6449f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React-Redux with Typescript]]></title>
            <link>https://medium.com/@ksholla20/react-redux-with-typescript-ad7266896a9b?source=rss-3191fa972fa7------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad7266896a9b</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Sharath Holla]]></dc:creator>
            <pubDate>Wed, 23 Jan 2019 06:25:51 GMT</pubDate>
            <atom:updated>2019-05-06T04:07:08.910Z</atom:updated>
            <content:encoded><![CDATA[<p>React is one of the most popular framework to build a Web Application. However, as we start building more complex application state management becomes a necessity. Redux is one such tool, which helps in managing the state of entire application in a single entity called <strong>Store</strong>.</p><h3>Brief description of Redux</h3><p>Official Redux documentation describes it as <em>a predictable state container for JavaScript apps. </em>Lets break the definition here.</p><p>In traditional react, each component maintains it’s own state. If you want to move state component from parent to child component, you can pass it using props. However, if one wants to share state between two components which are not in parent-child relationship, then it gets messy</p><p>This is where state management tools like Redux come in handy. Redux maintains a single Store. Any component connected to this store can update state, or read state. The connected component that has access to store is called container. When any component wants to update the store, it calls an <strong>Action</strong>. Then we have functions called <strong>Reducers</strong>, which reads these actions and return an updated state. All the components update based on the new state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j2rUfsp2c8d3-Ud_wDwwkg.png" /><figcaption>Redux workflow</figcaption></figure><p>We use <em>react-redux</em> library in our example.</p><h3>Typescript with react</h3><p>Most of the react applications are developed using JavaScript. This is beneficial if you want to develop application quickly, without worrying about type-checking. However, for better maintainability, or if more developers are involved in app development, typescript comes handy, by adding type checking into the code. This helps in avoiding many possible bugs during development. It also helps while using IDE’s as they can provide better auto completes.</p><p>Create React App has added support for generation of a typescript project during project creation (Version 2.1.0 and onward). However for existing projects, one can install typescript using npm or yarn.</p><h3>Getting hands dirty with code</h3><p>Let us build an app, where you enter 2 numbers, and results of few binary operations will be listed. Following is the screenshot of the final application we are planning</p><p>The project is shared at <a href="https://github.com/ksholla20/react-redux-typescript-starter/tree/master">https://github.com/ksholla20/react-redux-typescript-starter/tree/master</a><br>The checkpoint versions are shared in respective sections</p><h4>Project creation</h4><p>Let’s start with creation of a typescript project</p><pre>npx create-react-app calculator-app --typescript</pre><p>This will create a folder calculator-app with typescript<br>The code checkpoint is shared <a href="https://github.com/ksholla20/react-redux-typescript-starter/tree/1.0">here</a></p><h4>Adding View layer</h4><p>We will add 2 input components, operandA and operandB<br>Also there will be paragraphs listing the binary operation results</p><p>We will define a component to take in numbers and display</p><pre>//src/components/numberInput.tsx</pre><pre>import * as React from &quot;react&quot;;<br>interface Props {<br>  name: string,<br>  value: number<br>}</pre><pre>interface ClassState {<br>  value: number;<br>}</pre><pre>const inputStyle = {<br>  marginTop: &#39;10px&#39;,<br>  display: &#39;inline-flex&#39;<br>}</pre><pre>const divStyle = {<br>  width: &#39;150px&#39;<br>}</pre><pre>export class NumberInput extends React.Component&lt;Props, ClassState&gt; {<br>  constructor(props: any, context: any) {<br>    super(props, context);<br>    this.state = {value: props.value};<br>    this.onNumberChange = this.onNumberChange.bind(this);<br>  }</pre><pre>  onNumberChange(e:any){<br>    this.setState({value: e.target.value});<br>  }</pre><pre>  render(){<br>    return (<br>      &lt;div style={inputStyle}&gt;<br>        &lt;div style={divStyle}&gt;{this.props.name}&lt;/div&gt;<br>        &lt;input<br>          name={this.props.name}<br>          type=&quot;number&quot;<br>          value={this.state.value}<br>          onChange={this.onNumberChange}<br>        /&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>}</pre><pre>export default NumberInput;</pre><p>Unlike in javascript, we import react as <em>import * as React from “react”;<br></em>To define Props, we need to define an interface and define all the prop types. Similarly, to define local state, we need to first define an interface declaring all state variables, and then define it in the component</p><p>Now let us define a component which calls 2 input components. As we have not yet integrated state management, we are currently calling a dummy value.</p><pre>//src/components/inputHolder.tsx<br>import * as React from &quot;react&quot;;<br>import NumberInput from &#39;../numberInput&#39;</pre><pre>interface Props {<br>}</pre><pre>const holderStyle = {<br>  marginTop: &#39;20px&#39;,<br>  display: &#39;inline-grid&#39;<br>}</pre><pre>export class InputHolder extends React.Component&lt;Props&gt; {<br>  render(){<br>    const initValue = [0, 1];<br>    return (<br>      &lt;div style = {holderStyle}&gt;<br>        &lt;NumberInput name = &quot;OPERANDA&quot; value = {initValue[0]} /&gt;<br>        &lt;NumberInput name = &quot;OPERANDB&quot; value = {initValue[1]} /&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>}</pre><pre>export default InputHolder;</pre><p>In the same way, we define output holders. Again, as state management in not integrated yet, we have dummy values in the components</p><pre>//src/components/numberOutput<br>import * as React from &quot;react&quot;;<br>interface Props {<br>  name: string,<br>  value: number<br>}</pre><pre>const inputStyle = {<br>  marginTop: &#39;10px&#39;,<br>  display: &#39;inline-flex&#39;<br>}</pre><pre>const divStyle = {<br>  width: &#39;150px&#39;<br>}</pre><pre>export class NumberOutput extends React.Component&lt;Props&gt; {<br>  render(){<br>    return (<br>      &lt;div style={inputStyle}&gt;<br>        &lt;div style={divStyle}&gt;{this.props.name}&lt;/div&gt;<br>        &lt;div&gt;: {this.props.value}&lt;/div&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>}</pre><pre>export default NumberOutput;</pre><p>And the holder corresponding to this</p><pre>//src/components/outputHolder.tsx<br>import * as React from &quot;react&quot;;<br>import NumberOutput from &#39;../numberOutput&#39;<br>interface Props {<br>}</pre><pre>const holderStyle = {<br>  marginTop: &#39;20px&#39;,<br>  display: &#39;inline-grid&#39;<br>}</pre><pre>export class OutputHolder extends React.Component&lt;Props&gt; {<br>  render(){<br>    const initValue = [0,1];<br>    const operandA = initValue[0], operandB = initValue[1];<br>    const sum = operandA + operandB;<br>    const dif = operandA - operandB;<br>    const mul = operandA * operandB;<br>    const dvs = operandB ? 0:operandA / operandB;</pre><pre>    return (<br>       &lt;div style = {holderStyle}&gt;<br>        &lt;NumberOutput name = &quot;ADDITION&quot; value = {sum}/&gt;<br>        &lt;NumberOutput name = &quot;SUBTRACTION&quot; value = {dif}/&gt;<br>        &lt;NumberOutput name = &quot;MULTIPLICATION&quot; value = {mul}/&gt;<br>        &lt;NumberOutput name = &quot;DIVISION&quot; value = {dvs}/&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>}</pre><pre>export default OutputHolder;</pre><p>And finally, we piece it all in a container</p><pre>//src/containers/calculator.tsx<br>import * as React from &quot;react&quot;;<br>import InputHolder from &#39;../../components/inputHolder&#39;<br>import OutputHolder from &#39;../../components/outputHolder&#39;</pre><pre>interface Props {<br>}</pre><pre>const calculatorStyle = {<br>  marginLeft: &#39;30%&#39;,<br>  marginTop: &#39;20px&#39;,<br>  display: &#39;grid&#39;<br>}</pre><pre>const divStyle = {<br>  color: &#39;indigo&#39;,<br>  fontSize: &#39;xx-large&#39;<br>}</pre><pre>export class Calculator extends React.Component&lt;Props&gt; {<br>  render(){<br>    return (<br>      &lt;div style={calculatorStyle}&gt;<br>        &lt;div style = {divStyle}&gt;This is a simple calculator&lt;/div&gt;<br>        &lt;InputHolder/&gt;<br>        &lt;OutputHolder/&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>}</pre><pre>export default Calculator;</pre><p>We now call this in our react application. We modified the App.tsx to call this container</p><pre>//src/App.tsx<br>import * as React from &quot;react&quot;;<br>import Calculator from &#39;./containers/calculator&#39;</pre><pre>export const App = (): JSX.Element =&gt; {<br>  return (<br>    &lt;div&gt;<br>      &lt;Calculator /&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><pre>export default App;</pre><p>With this, we have a react app which just displays the required UI layer.<br>The code checkpoint is shared <a href="https://github.com/ksholla20/react-redux-typescript-starter/tree/1.1">here</a></p><h4>Adding Redux State management</h4><p>We will be installing following npm packages for this project.</p><ul><li>react-redux</li><li>react-router-dom</li><li>react-router-redux</li><li>redux-actions</li><li>redux-observable</li></ul><p>And corresponding typescript packages as dev dependencies</p><ul><li><a href="http://twitter.com/types/react-redux">@types/react-redux</a></li><li><a href="http://twitter.com/types/react-router-dom">@types/react-router-dom</a></li><li><a href="http://twitter.com/types/react-router-redux">@types/react-router-redux</a></li><li><a href="http://twitter.com/types/redux-actions">@types/redux-actions</a></li></ul><p>With standard release version of react-router-redux, we faced issue in provider. Hence we moved to <em>react-router-redux@next</em></p><pre>npm install -S react-redux react-router-dom react-router-redux@next redux-actions redux-observable<br>npm install -D <a href="http://twitter.com/types/react-redux">@types/react-redux</a> <a href="http://twitter.com/types/react-router-dom">@types/react-router-dom</a> <a href="http://twitter.com/types/react-router-redux">@types/react-router-redux</a> <a href="http://twitter.com/types/redux-actions">@types/redux-actions</a></pre><p>Lets define actions and states. In current example, 2 types of actions are required. Change in operandA and change in operandB. Similarly, state contains 2 variables.</p><p>Following is the model file, where we define require interface</p><pre>//src/interfaces/calculatorModels.ts<br>export interface CalculatorModel {<br>  operandA: number;<br>  operandB: number;<br>}</pre><pre>export interface OperandAPayload {<br>  operandA: number;<br>}</pre><pre>export interface OperandBPayload {<br>  operandB: number;<br>}</pre><p>Define the actions file</p><pre>//src/actions/calculatorActions.ts<br>import { createAction } from &quot;redux-actions&quot;;<br>import { OperandAPayload, OperandBPayload } from &quot;../interfaces/calculatorModels&quot;;</pre><pre>export const Type = {<br>  SET_OPERANDA: &quot;SET_OPERANDA&quot;,<br>  SET_OPERANDB: &quot;SET_OPERANDB&quot;<br>};</pre><pre>export const setOperandA = createAction&lt;OperandAPayload&gt;(<br>  Type.SET_OPERANDA<br>);</pre><pre>export const setOperandB = createAction&lt;OperandBPayload&gt;(<br>  Type.SET_OPERANDB<br>);</pre><p>Finally define reducers</p><pre>//src/reducers/calculatorReducer.ts<br>import { combineReducers } from &quot;redux&quot;;<br>import { handleActions, Action } from &quot;redux-actions&quot;;<br>import { CalculatorModel, OperandAPayload, OperandBPayload} from &quot;../interfaces/calculatorModels&quot;;<br>import * as CalculatorActions from &quot;../actions/calculatorActions&quot;;</pre><pre>export type State = {<br>  readonly operandA: number;<br>  readonly operandB: number;<br>};</pre><pre>const initialState: State = {<br>  operandA: 0,<br>  operandB: 1<br>};</pre><pre>export const calculatorReducer = handleActions&lt;State, CalculatorModel&gt;(<br>  {<br>    [CalculatorActions.Type.SET_OPERANDA]: (<br>      state: State,<br>      action: Action&lt;OperandAPayload&gt;<br>    ) =&gt; {<br>      return {<br>        operandA: action.payload ? (action.payload as any) : 0,<br>        operandB: state.operandB<br>      };<br>    },</pre><pre>    [CalculatorActions.Type.SET_OPERANDB]: (<br>      state: State,<br>      action: Action&lt;OperandBPayload&gt;<br>    ) =&gt; {<br>      return {<br>        operandA: state.operandA,<br>        operandB: action.payload ? (action.payload as any) : 0<br>      };<br>    }<br>  },<br>  initialState<br>);</pre><p>We might have many reducers. Hence we will have a master reducer which will combine all the reducers</p><pre>//src/reducers/index.ts<br>import { combineReducers } from &quot;redux&quot;;<br>import { routerReducer as router, RouterState } from &quot;react-router-redux&quot;;<br>import { calculatorReducer, State as CalculatorState<br>} from &quot;./calculatorReducer&quot;;<br>import { CalculatorModel } from &quot;../interfaces/calculatorModels&quot;;</pre><pre>interface StoreEnhancerState {}</pre><pre>export interface RootState extends StoreEnhancerState {<br>  router: RouterState;<br>  calculatorReducer: CalculatorState;<br>}</pre><pre>export const rootReducer = combineReducers&lt;RootState&gt;({<br>  router,<br>  calculatorReducer: calculatorReducer as any<br>});</pre><p>We will also define a store, which will apply this reducer as middleware. This will be used while defining the root component</p><pre>//src/reducers/store.ts<br>import { createStore, applyMiddleware, compose } from &quot;redux&quot;;<br>import { createEpicMiddleware } from &quot;redux-observable&quot;;<br>import { routerMiddleware as createRouterMiddleware } from &quot;react-router-redux&quot;;<br>import createHistory from &quot;history/createBrowserHistory&quot;;<br>import { rootReducer, RootState } from &quot;./index&quot;;</pre><pre>export const history = createHistory();</pre><pre>export const routerMiddleware = createRouterMiddleware(history);</pre><pre>export function configureStore(initialState?: RootState) {<br>  // configure middlewares<br>  const middlewares = [routerMiddleware];<br>  // compose enhancers<br>  const enhancer = compose(applyMiddleware(...middlewares));<br>  // create store<br>  return createStore(rootReducer, initialState!, enhancer);<br>}</pre><p>We have our actions and reducers ready. Let us use this in the existing application</p><p>First, let us modify index.tsx in src folder to use the store, and pass it as a prop to its children</p><pre>//src/index.tsx<br>import * as React from &quot;react&quot;;<br>import * as ReactDOM from &quot;react-dom&quot;;<br>import * as serviceWorker from &quot;./serviceWorker&quot;;<br>import { Provider } from &quot;react-redux&quot;;<br>import { configureStore, history } from &quot;./reducers/store&quot;;<br>import { ConnectedRouter } from &quot;react-router-redux&quot;;</pre><pre>import App from &#39;./App&#39;;</pre><pre>const store = configureStore();</pre><pre>ReactDOM.render(<br>  &lt;Provider store={store}&gt;<br>    &lt;ConnectedRouter history={history} store={store}&gt;<br>      &lt;App /&gt;<br>    &lt;/ConnectedRouter&gt;<br>  &lt;/Provider&gt;,</pre><pre>  document.getElementById(&quot;root&quot;)<br>);</pre><pre>serviceWorker.unregister();</pre><p>We can optionally change the App.tsx to add routes. This is not a necessary step in this demo, but nice to have one</p><pre>//src/App.tsx<br>import * as React from &quot;react&quot;;<br>import { Route, Switch } from &quot;react-router-dom&quot;;<br>import Calculator from &#39;./containers/calculator&#39;</pre><pre>export const App = (): JSX.Element =&gt; {</pre><pre>  return (<br>    &lt;div&gt;<br>      &lt;Route exact={true} path=&quot;/&quot; component={Calculator} /&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><pre>export default App;</pre><p>We will now modify the container to pack these states and actions into props</p><pre>//src/containers/calculator.tsx<br>import * as React from &quot;react&quot;;<br>import { connect } from &quot;react-redux&quot;;<br>import { bindActionCreators, Dispatch } from &quot;redux&quot;;<br>import * as calculatorActions from &quot;../../actions/calculatorActions&quot;;<br>import { RootState, rootReducer } from &quot;../../reducers&quot;;<br>import { CalculatorModel } from &quot;../../interfaces/calculatorModels&quot;;<br>import InputHolder from &#39;../../components/inputHolder&#39;<br>import OutputHolder from &#39;../../components/outputHolder&#39;</pre><pre>interface Props {<br>  calculatorState: CalculatorModel;<br>  actions: any;<br>}</pre><pre>const calculatorStyle = {<br>  marginLeft: &#39;30%&#39;,<br>  marginTop: &#39;20px&#39;,<br>  display: &#39;grid&#39;<br>}</pre><pre>const divStyle = {<br>  color: &#39;indigo&#39;,<br>  fontSize: &#39;xx-large&#39;<br>}</pre><pre>export class Calculator extends React.Component&lt;Props&gt; {<br>  render(){<br>    return (<br>      &lt;div style={calculatorStyle}&gt;<br>        &lt;div style = {divStyle}&gt;This is a simple calculator&lt;/div&gt;<br>        &lt;InputHolder<br>          actions = {this.props.actions}<br>          calculatorState = {this.props.calculatorState}<br>        /&gt;</pre><pre>        &lt;OutputHolder<br>          calculatorState = {this.props.calculatorState}<br>        /&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>}</pre><pre>const actions: any = Object.assign({}, calculatorActions);</pre><pre>function mapStateToProps(state: RootState) {<br>  return {<br>    calculatorState: state.calculatorReducer<br>  };<br>}</pre><pre>function mapDispatchToProps(dispatch: Dispatch) {<br>  return {<br>    actions: bindActionCreators(actions, dispatch)<br>  };<br>}</pre><pre>export default connect(<br>  mapStateToProps,<br>  mapDispatchToProps<br>)(Calculator);</pre><p>We can now change the individual components to handle these states</p><pre>//src/components/inputHolder.tsx<br>import * as React from &quot;react&quot;;<br>import NumberInput from &#39;../numberInput&#39;<br>import { CalculatorModel } from &quot;../../interfaces/calculatorModels&quot;;</pre><pre>interface Props {<br>  calculatorState: CalculatorModel;<br>  actions: any;<br>}</pre><pre>const holderStyle = {<br>  marginTop: &#39;20px&#39;,<br>  display: &#39;inline-grid&#39;<br>}</pre><pre>export class InputHolder extends React.Component&lt;Props&gt; {<br>  render(){<br>    return (<br>      &lt;div style = {holderStyle}&gt;<br>        &lt;NumberInput<br>          name = &quot;OPERANDA&quot;<br>          value = {this.props.calculatorState.operandA}<br>          callback = {this.props.actions.setOperandA}<br>        /&gt;</pre><pre>        &lt;NumberInput<br>          name = &quot;OPERANDB&quot;<br>          value = {this.props.calculatorState.operandB}<br>          callback = {this.props.actions.setOperandB}<br>        /&gt;</pre><pre>      &lt;/div&gt;<br>    );<br>  }<br>}</pre><pre>export default InputHolder;</pre><p>Note that we now are sending the operand value from global state</p><pre>//src/components/numberInput.tsx<br>import * as React from &quot;react&quot;;</pre><pre>interface Props {<br>  name: string,<br>  value: number<br>  callback: any;<br>}</pre><pre>const inputStyle = {<br>  marginTop: &#39;10px&#39;,<br>  display: &#39;inline-flex&#39;<br>}</pre><pre>const divStyle = {<br>  width: &#39;150px&#39;<br>}</pre><pre>export class NumberInput extends React.Component&lt;Props&gt; {<br>  constructor(props: any, context: any) {<br>    super(props, context);<br>    this.onNumberChange = this.onNumberChange.bind(this);<br>  }</pre><pre>  onNumberChange(e:any){<br>    this.props.callback(e.target.value);<br>  }</pre><pre>  render(){<br>    return (<br>      &lt;div style={inputStyle}&gt;<br>        &lt;div style={divStyle}&gt;{this.props.name}&lt;/div&gt;</pre><pre>        &lt;input<br>          type=&quot;number&quot;<br>          value={this.props.value}<br>          onChange={this.onNumberChange}<br>        /&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>}</pre><pre>export default NumberInput;</pre><p>Note here that we removed the local state, and we now call actions when number is changed</p><pre>//src/components/outputHolder.tsx<br>import * as React from &quot;react&quot;;<br>import NumberOutput from &#39;../numberOutput&#39;<br>import { CalculatorModel } from &quot;../../interfaces/calculatorModels&quot;;<br>interface Props {<br>  calculatorState: CalculatorModel;<br>}</pre><pre>const holderStyle = {<br>  marginTop: &#39;20px&#39;,<br>  display: &#39;inline-grid&#39;<br>}</pre><pre>export class OutputHolder extends React.Component&lt;Props&gt; {<br>  render(){<br>    const operandA:number = this.props.calculatorState.operandA;<br>    const operandB:number = this.props.calculatorState.operandB;</pre><pre>    const sum = Number(operandA) + Number(operandB);<br>    const dif = operandA - operandB;<br>    const mul = operandA * operandB;<br>    const dvs = operandB ? operandA / operandB:0;</pre><pre>    return (<br>      &lt;div style = {holderStyle}&gt;<br>        &lt;NumberOutput name = &quot;ADDITION&quot; value = {sum}/&gt;<br>        &lt;NumberOutput name = &quot;SUBTRACTION&quot; value = {dif}/&gt;<br>        &lt;NumberOutput name = &quot;MULTIPLICATION&quot; value = {mul}/&gt;<br>        &lt;NumberOutput name = &quot;DIVISION&quot; value = {dvs}/&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>}</pre><pre>export default OutputHolder;</pre><p>Now we have all our pieces ready to run our application</p><h3>Conclusion</h3><p>The goal of this article is to get started with react-redux using Typescript. Emphasis was not given on beautifying the UI, but add a basic redux code to a new project. The project is shared in <a href="https://github.com/ksholla20/react-redux-typescript-starter/tree/master">https://github.com/ksholla20/react-redux-typescript-starter/tree/master</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad7266896a9b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to create a copy of Azure SQL database in another subscription]]></title>
            <link>https://medium.com/@ksholla20/how-to-create-a-copy-of-azure-sql-database-in-another-subscription-7ddd000f15f4?source=rss-3191fa972fa7------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ddd000f15f4</guid>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[powershell]]></category>
            <category><![CDATA[sql-server]]></category>
            <dc:creator><![CDATA[Sharath Holla]]></dc:creator>
            <pubDate>Mon, 31 Dec 2018 11:56:23 GMT</pubDate>
            <atom:updated>2018-12-31T11:56:23.545Z</atom:updated>
            <content:encoded><![CDATA[<p>In many use cases, we would need to create a copy of database from one server to another. In some cases, the source and the destination databases would be in different Azure subscription. This article explores different ways to achieve this.</p><p>We had a requirement of automating the copy. Hence all our approaches are using commands, with no involvement of Azure portal or SQL Server Management services</p><p>In our search, We found three ways of creating a copy of a database</p><h3>Using Transact-SQL statements</h3><p>Using transact-SQL statements, we can create and copy data from one database to another. However, this will require us to have an admin user to be created in both source and destination servers and this credentials of this user should be used for transfer.</p><h4>Prerequisite steps of creating users:</h4><ul><li>Create login and user in source server</li></ul><pre>CREATE LOGIN &lt;username&gt; WITH PASSWORD = &#39;&lt;password&gt;&#39;<br>CREATE USER &lt;username&gt; FOR LOGIN &lt;username&gt; WITH DEFAULT_SCHEMA=[dbo]</pre><ul><li>Create the user in the source database and grant db owner permission to the database</li></ul><pre>CREATE USER &lt;username&gt; FOR LOGIN &lt;username&gt; WITH DEFAULT_SCHEMA=[dbo]<br>exec sp_addrolemember &#39;db_owner&#39;,&#39;&lt;username&gt;&#39;</pre><ul><li>Capture the SID of the user from source server</li></ul><pre>SELECT [sid] FROM sysusers WHERE [name] = &#39;&lt;username&gt;&#39;</pre><ul><li>Create login and user in destination server. Use same username and password as in source server</li></ul><pre>CREATE LOGIN &lt;username&gt; WITH PASSWORD = &#39;&lt;password&gt;&#39;, SID = [SID]<br>CREATE USER &lt;username&gt; FOR LOGIN &lt;username&gt; WITH DEFAULT_SCHEMA=[dbo]</pre><ul><li>Grant dbmanager permission to the user in destination server</li></ul><pre>exec sp_addrolemember &#39;dbmanager&#39;,&#39;&lt;username&gt;&#39;</pre><h4>Actual copy of database</h4><p>Once a common user is created, script can be created to automate the copy.<br>To copy, use credentials of newly created user.</p><pre>CREATE DATABASE &lt;staging_copy&gt; AS COPY OF &lt;source_server_name&gt;.&lt;source_database_name&gt; (SERVICE_OBJECTIVE = &#39;P1&#39;)</pre><p>Here, service objective is the pricing tier of destination database.</p><h4>Limitations</h4><p>This method does not work if source database is a read only. In cases where you do not want to risk using primary database as source, owing to performance considerations, you would wish to have read only replica as source. In those cases, create database step would throw permission errors.</p><p>Microsoft documentation <a href="https://docs.microsoft.com/en-us/azure/sql-database/sql-database-copy#copy-a-sql-database-to-a-different-server">link</a></p><h3>Using PowerShell import/export database command</h3><p>In this method, you can create a backup of source database and store is in a blob or local store. Later, you can create a new database by importing from this backup.<br>Following is the sample code:</p><p>Initialize powershell variables</p><pre>#Source server details<br>$SourceResourceGroupName = &lt;source_resource_group_name&gt;<br>$SourceServerName = &lt;source_server_name&gt;<br>$SourceDatabaseName = &lt;source_database_name&gt;<br>$SourceUserName = &lt;source_server_username&gt;<br>$SourcePassword = &lt;source_server_password&gt;</pre><pre>#destination server details<br>$DestResourceGroupName = &lt;destination_resource_group_name&gt;<br>$DestServerName = &lt;destination_server_name&gt;<br>$DestDatabaseName = &lt;destination_database_name&gt;<br>$DestUserName = &lt;destination_server_username&gt;<br>$DestPassword = &lt;destination_server_password&gt;</pre><pre>#Blob Store details<br>$StorageKey = &lt;blob_store_secret&gt;<br>$BacpacUri = &lt;required_url_of_backup_in_blob&gt;</pre><p>Export source database to Blob store</p><pre>Set-AzureRmSubscription &#39;&lt;source_server_subscription&gt;&#39;<br>$exportRequest = New-AzureRmSqlDatabaseExport  `<br>  -ResourceGroupName $SourceResourceGroupName `<br>  -ServerName $SourceServerName `<br>  -DatabaseName $SourceDatabaseName`<br>  -StorageKeytype &#39;StorageAccessKey&#39; `<br>  -StorageKey $StorageKey `<br>  -StorageUri $BacpacUri `<br>  -AdministratorLogin $SourceUserName `<br>  -AdministratorLoginPassword $(ConvertTo-SecureString -String &#39;$(SourcePassword)&#39; -AsPlainText -Force)</pre><pre># Check and want for export status<br>$exportStatus = Get-AzureRmSqlDatabaseImportExportStatus -OperationStatusLink $exportRequest.OperationStatusLink<br>Write-Host &quot;Exporting&quot;<br>while ($exportStatus.Status -eq &quot;InProgress&quot;)<br>{<br>    Start-Sleep -s 10<br>    $exportStatus = Get-AzureRmSqlDatabaseImportExportStatus -OperationStatusLink $exportRequest.OperationStatusLink<br>    Write-Host &quot;.&quot;<br>}<br>Write-Host &quot;$exportStatus&quot;<br>}</pre><p>Import backup file to a database:</p><pre>Set-AzureRmSubscription &#39;&lt;destination_server_subscription&gt;&#39;<br>$importRequest = New-AzureRmSqlDatabaseImport `<br>   -ResourceGroupName $DestResourceGroupName `<br>   -ServerName $DestServerName `<br>   -DatabaseName $DestDatabaseName `<br>   -DatabaseMaxSizeBytes &quot;800000000000&quot; `<br>   -StorageKeyType &quot;StorageAccessKey&quot; `<br>   -StorageKey $StorageKey `<br>   -StorageUri $BacpacUri `<br>   -Edition &quot;Premium&quot; `<br>   -ServiceObjectiveName &quot;P1&quot; `<br>   -AdministratorLogin $DestUserName `<br>   -AdministratorLoginPassword $(ConvertTo-SecureString -String $(DestPassword) -AsPlainText -Force)<br>}<br># Max size is assigned is 800GB</pre><pre>$importStatus = Get-AzureRmSqlDatabaseImportExportStatus -OperationStatusLink $importRequest.OperationStatusLink<br>Write-Host &quot;Importing&quot;<br>while ($importStatus.Status -eq &quot;InProgress&quot;)<br>{<br>    $importStatus = Get-AzureRmSqlDatabaseImportExportStatus -OperationStatusLink $importRequest.OperationStatusLink<br>    Write-Host &quot;.&quot;<br>    Start-Sleep -s 10<br>}<br>Write-Host &quot;$importStatus&quot;</pre><h4>Limitations</h4><p>Time taken for export and import is huge if data size is in 100s of GB. (Import time depends on pricing tier of database)</p><h4>Microsoft Documentation</h4><p>Export: <a href="https://docs.microsoft.com/en-us/azure/sql-database/sql-database-export#export-to-a-bacpac-file-using-powershell">link</a><br>Import: <a href="https://docs.microsoft.com/en-us/azure/sql-database/sql-database-import#import-from-a-bacpac-file-using-powershell">link</a></p><h3>Using PowerShell copy database command</h3><p>Azure directly provides API to create a copy of database. However, you cannot create the copy in a different subscription<br>Hence we can use a workaround by creating the database and server in same subscription, and then move the server to and destination subscription</p><p>Following is the Sample code</p><p>Initialize powershell variables</p><pre>#Source server details<br>$SourceResourceGroupName = &lt;source_resource_group_name&gt;<br>$SourceServerName = &lt;source_server_name&gt;<br>$SourceDatabaseName = &lt;source_database_name&gt;</pre><pre>#destination server details<br>$DestResourceGroupName = &lt;destination_resource_group_name&gt;<br>$DestServerName = &lt;destination_server_name&gt;<br>$DestDatabaseName = &lt;destination_database_name&gt;<br>$DestSubscriptionId = &lt;destination_subscription_id&gt;</pre><p>Create a copy of database in current subscription</p><pre>Set-AzureRmSubscription &#39;&lt;source_server_subscription&gt;</pre><pre>&#39;New-AzureRmSqlDatabaseCopy -ResourceGroupName $SourceResourceGroupName `<br>    -ServerName $SourceServerName `<br>    -DatabaseName $SourceDatabaseName `<br>    -CopyResourceGroupName $DestResourceGroupName `<br>    -CopyServerName $DestServerName `<br>    -CopyDatabaseName $DestDatabaseName</pre><p>Move the resource group to destination subscription</p><pre>$Resource = Get-AzureRmResource -ResourceType &quot;Microsoft.Sql&quot; -ResourceGroupName  $SourceResourceGroupName<br>Move-AzureRmResource -ResourceId $Resource.ResourceId -DestinationResourceGroupName $DestResourceGroupName -DestinationSubscriptionId $DestSubscriptionId</pre><h4>Limitations:</h4><p>As shown in the sample, we cannot append copy database to existing server.<br>In order to achieve that, we can move server and databases to destination subscription, and then call copy database to create a copy in existing destination server</p><h3>Conclusion</h3><p>We have discussed 3 ways to create a copy of azure SQL database across subscriptions. Each of them have their own limitations. Based on the needs, any of these methods can be used to accomplish the job.</p><p>As mentioned in the introduction, command based solutions are provided here. Methods 2 and 3 have Azure portal based click sequences to achieve the goal, which is not explained in this article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ddd000f15f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a Cronjob in Kubernetes and use secrets as environment variables]]></title>
            <link>https://medium.com/@ksholla20/creating-a-cronjob-in-kubernetes-and-use-secrets-as-environment-variables-b8e0166f2d51?source=rss-3191fa972fa7------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8e0166f2d51</guid>
            <category><![CDATA[secrets]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[cronjob]]></category>
            <dc:creator><![CDATA[Sharath Holla]]></dc:creator>
            <pubDate>Thu, 30 Aug 2018 12:01:59 GMT</pubDate>
            <atom:updated>2018-08-30T12:01:59.787Z</atom:updated>
            <content:encoded><![CDATA[<h3>Kubernetes</h3><p>With most of the applications moving from Monolith architecture to Microservices architecture, deployment, orchestration, and managing these services becomes important part of devops. Kubernetes has become a forefront platform to bridge this need. Kubernetes is an open-source platform, originaly developed by Google, for automating deployment, scaling, and maintenance of application containers across clusters of hosts.</p><h3>Cronjob</h3><p>In most of the application, there will be requirement to run few tasks periodically. These might be a background job to clean up data periodically, or remove subscription of users at end of month, etc. To accomplish this, one can create a pod, which runs a loop of executing the task once, sleeps for the required amount of time, wakes up and loop again. However, a pod will be dedicated for this loop of execution and sleep.</p><p>Cronjob task in kubernetes is a handy one to use in such scenario. Once a cronjob is scheduled, cronjob controller of kubernetes, polls and checks whether any job is to be scheduled, creates a pod for each of these scheduled job. After the job is completed, the pod is removed. This helps manage resources efficiently as the controller is the only one which runs continuously. The actual job pods are created and removed as and when required</p><h3>Secrets</h3><p>Every production grade applications will have few variables, which contain keys like database access keys, API keys, etc. These might be different for different environments and can contain sensitive information. Hence, we might not want to store these in the code repository. In kubernetes, we can put these as a secret and upload to the cluster. Later, while spinning up the container pod, these secrets can be pulled and injected to the pod</p><h3>Creating a Kubernetes Cronjob</h3><p>Let us start with a simple python task, which we wish to run</p><pre><em># demo_script.py<br></em><strong>from </strong>datetime <strong>import </strong>datetime<br><strong>import </strong>os<br><br><strong>if </strong>__name__ == <strong>&quot;__main__&quot;</strong>:<br>    print(<strong>&#39;Time now: &#39; </strong>+ datetime.now().strftime(<strong>&quot;%Y-%m-%d %H:%M:%S&quot;</strong>))<br>    d = datetime.now()<br>    <strong>if </strong>os.getenv(<strong>&#39;DAY_OF_WEEK&#39;</strong>, <strong>&#39;0&#39;</strong>) == str(d.weekday()):<br>        print(<strong>&#39;Have a great day&#39;</strong>)<br>    <strong>if </strong>os.getenv(<strong>&#39;DATE_OF_MONTH&#39;</strong>) == str(d.day):<br>        print(<strong>&#39;Yay!! Salary Day&#39;</strong>)</pre><p>This is a simple task, which prints current time. This takes variable ‘DAY_OF_WEEK’ and ‘DATE_OF_MONTH’ from environment and prints a message accordingly.</p><p>This file is put in a docker image and uploaded to docker repository. Let the image name be ‘demo-image’.</p><p>To create a secret, there are many ways. The kubernetes documentation <a href="https://kubernetes.io/docs/concepts/configuration/secret/">here</a> explains this in great detail. For the ease of demonstration, we will take a simple secret yaml</p><pre><em># secrets.yaml<br></em><strong>apiVersion: </strong>v1<br><strong>kind: </strong>Secret<br><strong>metadata:<br>  name: </strong>demo-secret<br><strong>type: </strong>Opaque<br><strong>data:<br>  DAY_OF_WEEK: </strong>NA==<br>  <strong>DATE_OF_MONTH: </strong>MQ==</pre><p>Here, we create a yaml file of type secret. One of secret added, is with key ‘DAY_OF_WEEK’. Value assigned is 4 and it is base 64 encoded. The secret name is ‘demo-secret’. This will be used as reference during pod creation</p><p>Following is the sample cron yaml</p><pre><em># cron_demo.yaml<br></em><strong>apiVersion: </strong>batch/v1beta1<br><strong>kind: </strong>CronJob<br><strong>metadata:<br>  name: </strong>demo-cron<br><strong>spec:<br>  schedule: &quot;0 0 */1 * *&quot;<br>  jobTemplate:<br>    spec:<br>      template:<br>        spec:<br>          containers:<br>          </strong>- <strong>name: </strong>demo-cron<br>            <strong>image: </strong>demo-image:latest<br>            <strong>envFrom:<br>            </strong>- <strong>secretRef:<br>                name: </strong>demo-secret<br>            <strong>args:<br>            </strong>- python<br>            - <em>demo_script.py</em><br>          <strong>restartPolicy: </strong>OnFailure</pre><p>Here, a cronjob named demo-cron will be created, which will run everyday at 00:00 hours (cron format ‘0 0 */1 * * conveys this). All secrets in demo-secret will be pulled and injected as environment variable of the python application. Once pod is created, following command ‘python demo-script.py’ will be run in the pod.</p><p>There are various secret pull policies, which are described <a href="https://kubernetes.io/docs/concepts/configuration/secret/">here</a>. The above used way is handy for many application, which do not want to mention the secrets to be pulled explicitly.</p><h3>Conclusion</h3><p>Cronjob, which was in v2 alpha, was promoted to beta from version 1.8. This has been one of the useful feature as running a scheduled job is a common scenario. This also reduces developers effort in developing and maintaining custom scheduler as a workaround.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8e0166f2d51" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>