<?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 Ritesh Modi on Medium]]></title>
        <description><![CDATA[Stories by Ritesh Modi on Medium]]></description>
        <link>https://medium.com/@ritesh.modi?source=rss-95e9b4985f23------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*j7CJbQGfwLCDHhqufXg87g.png</url>
            <title>Stories by Ritesh Modi on Medium</title>
            <link>https://medium.com/@ritesh.modi?source=rss-95e9b4985f23------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 07:21:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ritesh.modi/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[Concurrency check with Azure Durable Entities]]></title>
            <link>https://medium.com/@ritesh.modi/concurrency-check-with-azure-durable-entities-22bc6b374f2c?source=rss-95e9b4985f23------2</link>
            <guid isPermaLink="false">https://medium.com/p/22bc6b374f2c</guid>
            <category><![CDATA[durable-entities]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[durable-functions]]></category>
            <category><![CDATA[concurrency-checks]]></category>
            <dc:creator><![CDATA[Ritesh Modi]]></dc:creator>
            <pubDate>Sun, 19 Sep 2021 15:03:15 GMT</pubDate>
            <atom:updated>2021-09-23T08:26:04.489Z</atom:updated>
            <content:encoded><![CDATA[<p>How many times do we come across requirement to perform concurrency checks for a Job execution. Let me go a bit more deeper into the problem! Imagine you are implementing a Job Processor. The Job processor loads up messages delivered to message queue and starts executing them, taking them through a series of functions to eventually complete its path of execution. The question to answer is what happens when a new message comes in with the same payload while an existing Job is already getting processed. Should the Job get executed in parallel to existing Job or it should be throttled to be executed when the original job gets completed.</p><p>There have been multiple design that takes help from features related to Message broker like using sessions and transactions however they are not flexible and require custom implementation for any additional complexity.</p><p>Again, If the Job should be throttled, the implementation that comes immediately to mind is to add some sort of “persistent state” where any Job that gets executed, adds information about Job execution into a data store. The next Job that comes-in searches if the same Job information is available in the persistent store. If it finds one, then it does not execute the Job. It might put the message in a different queue or to a database for later processing. It might completely ignore it as well. Once the Job execution is complete, the state stored in persistent state is eventually removed so that newer jobs with same data can be executed. The implementation is simple but involves many more components in design — It needs a data store, code for adding, deleting and searching of jobs and more. This does not end here — any additional code has to tested as well thereby adding more time and effort for implementation. Testing for parallelism has its own quirks (I am not going to go through them in this blog) and has too many edge cases. In short, is has its own risks and issues that things might not work as expected even though considerable testing has been executed.</p><p>The above solution and implementation is common across any platform or architecture we adopt. Even if we use Simple or Durable functions, the implementation logic would almost remain the same. So, how do we make it simple and elegant at the same time.</p><p>This is where<strong> Azure Durable Entities </strong>shines bright and helps in easy implementation of concurrency check with fewer lines of code and artefacts.</p><p>Azure Durable Entities are similar to Actors in Actor pattern that can hold some state and identified using a unique entity id. They implement functionality that can bring changes and manage its internal state. The whole premise of these entities are that they are accessed by sending messages and the messages are processed one after another — so, there are no chances of parallel execution of code within them. They help in storing state however the data stored in them should not be large. They are best meant for smaller quantities of data. The entity id plays an important role as it helps in identifying an entity uniquely and sending messages to it. (Explaining Actor pattern in totality is something I have kept reserved for another blog).</p><p><strong>How Does Azure Durable Entities help in easy concurrency checks.</strong></p><p>Azure Durable entities are Plain Old C# objects (POCO) with internal state. Azure Durable entities are backed by JSON files and provides easy mechanism to read and write them. This read/write happens behind the scene and we just need to update the internal state with new values.</p><p>Let’s dive in into a simple example to implement a (simple) concurrency check for a Job processor. However, before we get into the implementation, let’s understand its architecture at a high level.</p><p><strong>Architecture</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-jAmBq-FgtyWpQBSAJzChw.png" /></figure><p>The architecture is again quite simple. It consists of Azure Service bus acting as Message broker. A starter Azure function reads all the messages coming in to the message broker. It all things go fine in this function, it invokes the Orchestrator function. Within Orchestrator function, the activity functions get called and finally the Orchestrator function ends the workflow execution. Durable Entities are read and creates within the Azure starter function in case they already don’t exists for a particular Job id and are deleted as last step within the Orchestrator function.</p><p><strong>Implementation</strong></p><p>The implementation involves implementing the starter and Orchestration function. It would also need to define the Durable Entity function using a POCO (Plain old simple class). There are rules are implementation of this POCO and those are well documented within Microsoft documentation @ <a href="https://docs.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-entities?tabs=csharp">https://docs.microsoft.com/en-us/azure/azure-functions/durable/durable-functions-entities?tabs=csharp</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ntU1XZTPBHoIztqSwFvKdw.png" /><figcaption>Sequence flow for a Job with Durable Entities</figcaption></figure><p>The Durable Entity Poco along with its function is defined with “Add”, “Reset”, “Delete” and “Get” Methods. They perform different operations on the internal state. It also has a function that helps in dispatching messages to the Durable Entity.</p><pre>[JsonObject(MemberSerialization.OptIn)]<br>    public class JobExists<br>    {</pre><pre>[JsonProperty(&quot;myCounterState&quot;)]<br>        public string dummyCounter { get; set; }</pre><pre>public Task Add(string internalState)<br>        {<br>            this.dummyCounter  = internalState;<br>            return Task.CompletedTask;<br>        }</pre><pre>public Task Reset()<br>        {<br>            this.dummyCounter = &quot;&quot;;<br>            return Task.CompletedTask;<br>        }</pre><pre>public Task&lt;string&gt; Get()<br>        {<br>            return Task.FromResult(this.dummyCounter);</pre><pre>}</pre><pre>public Task Delete()<br>        {<br>            Entity.Current.DeleteState();<br>            return Task.CompletedTask;<br>        }</pre><pre>[FunctionName(nameof(JobExists))]<br>        public static Task Run([EntityTrigger] IDurableEntityContext context) =&gt; context.DispatchAsync&lt;JobExists&gt;();</pre><pre>}</pre><p>The first place for implementing the concurrency check is with the starter function. The started function has the payload of the incoming message. Using it,</p><ul><li>It can construct a unique entity id.</li><li>After the unique id is created, the function can query Durable entity runtime for any such entity already exists using the ReadEntityStateAsync function. This function returns an object of type EntityStateResponse having a property EntityExists.</li><li>Using EntityExists property, it can be determined, if the entity exists of not.</li><li>If the entity does not exists, start the orchestrator or throttle the message by saving it to a database, ignoring it completely or dispatching it to another queue.</li></ul><pre>[FunctionName(&quot;de1_HttpStart&quot;)]<br>public static async Task HttpStart(<br>    [ServiceBusTrigger(&quot;myqueue&quot;, Connection = &quot;sbconnection&quot;)]  <br>         string myQueueItem,<br>    [DurableClient] IDurableOrchestrationClient starter,<br>    [DurableClient] IDurableEntityClient client,<br>    ILogger log<br> ){</pre><pre>var entityid = new EntityId(&quot;JobExists&quot;, myQueueItem.ToString());</pre><pre>EntityStateResponse&lt;JobExists&gt; mystate = await client.ReadEntityStateAsync&lt;JobExists&gt;(entityid);<br>            <br>log.LogInformation($&quot;Started orchestration with ID = &#39;{mystate.EntityExists}&#39;.&quot;);<br>            <br>if (mystate.EntityExists)<br>            {<br>                log.LogInformation($&quot;Started orchestration with ID = <br>                &#39;{mystate.EntityState.dummyCounter}&#39;.&quot;);</pre><pre>                log.LogInformation($&quot;cannot process at this time&quot;);<br>            }<br>            else<br>            {<br>                <strong>await client.SignalEntityAsync(entityid, &quot;Add&quot;,  <br>                           myQueueItem);</strong></pre><pre>                <strong>await starter.StartNewAsync&lt;string&gt;<br>                      (&quot;Orchestrationdemo&quot;, myQueueItem.ToString());</strong></pre><pre>             }</pre><pre>}</pre><p>Now, if a new message with the same message payload comes having the same id, will get throttled and won’t be processed. However, now no new job will be processed unless the currently execution of the job is deleted. This entity should be deleted once the orchestration/workflow is completed. So, the deletion of the Entity state should happen within the Orchestrator function.</p><p>Orchestration function</p><p>Within the Orchestration function</p><ul><li>First, the message payload should be read to recreate the same entity id in consideration.</li><li>Execute the workflow with all its activity functions within try-catch-finally block. The exception handling block is important because, the entity state should be deleted not only when the workflow completes but also whenever there is an error or exception within any part of the workflow execution. Within the finally block, the entity should be deleted. It is important to note here that a Timer is used that would wait for 30 seconds to mimic the Job Logic. The actual code should not have Timer but actual job logic.</li><li>Once the entity is deleted, the next message with the same payload will be able to get executed since now the entity associated with it no longer exists.</li></ul><pre>[FunctionName(&quot;Orchestrationdemo&quot;)]<br>public static async Task RunOrchestrator(<br> [OrchestrationTrigger] IDurableOrchestrationContext context)<br>  {<br>    string jobid = context.GetInput&lt;string&gt;();<br>    var entityid = new EntityId(&quot;JobExists&quot;, jobid);<br>     try<br>     {</pre><pre>        var targetTime = context.CurrentUtcDateTime.Add(<br>                         TimeSpan.FromSeconds(30));</pre><pre>         await context.CreateTimer(targetTime,  <br>              System.Threading.CancellationToken.None);</pre><pre>      }<br>      catch (Exception ex)<br>      {<br>      }<br>      finally<br>      {<br>         <strong>await context.CallEntityAsync(entityid, &quot;Delete&quot;);</strong><br>      }</pre><pre>    }</pre><p><strong>Runtime Behaviour</strong></p><p>We should have a service bus up and running before executing the functions.</p><p>Once both the functions and Service bus are up and running, we can send a message to the Service bus queue. we are sending a value of 6 in this case.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m-nU0YGAnq1IfiJrEsWWKw.png" /></figure><p>This will lead to successful execution of the all the functions involved.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gcvb80wHwC5mXriBJSXBZg.png" /></figure><p>However it two message with payload “6” comes immediately one after another, the second message won’t be processed as shown next.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OY7YfzrQxqeQcfXFpPyQdA.png" /></figure><p>and it we wait for the current job with id “6” to get completed, we will be able to send another message with the same id and obviously, messages with other id would get executed since, the entity for it does not yet exists.</p><p><strong>Summary</strong></p><p>Durable Entities makes implementing Concurrency checks with very few lines of code. You do not need to provision any persistent storage, no code to read, write and delete data from persistent storage and no need to actively manage them as well. The only thing required is an Entity function and class along with its usage within Durable functions. Hope you enjoyed reading this blog and would be able to implement concurrency in your solution quite easily!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22bc6b374f2c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Callback Pattern with Databricks and Durable functions]]></title>
            <link>https://medium.com/@ritesh.modi/callback-pattern-with-databricks-and-durable-functions-478659dca9b?source=rss-95e9b4985f23------2</link>
            <guid isPermaLink="false">https://medium.com/p/478659dca9b</guid>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[patterns]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[durable-functions]]></category>
            <dc:creator><![CDATA[Ritesh Modi]]></dc:creator>
            <pubDate>Wed, 15 Sep 2021 16:30:21 GMT</pubDate>
            <atom:updated>2021-09-20T05:24:58.266Z</atom:updated>
            <content:encoded><![CDATA[<p>With the explosion of availability of data with companies, organisations&#39; have started storing data in data lake. Data lakes helps in storing large quantity of data in multiple file formats and provides means to access them easily from compute engines. Compute engines that could load large amount of data and crunch them to generate meaningful and insightful data generally required distributed computing where each compute gets a portion of data and each works on that portion to eventually combine them into a consolidated output. Hadoop and Spark are the two main compute engines for large data. There are multiple data lake platforms and Databricks brings together the combined power of compute engine as well as data lake storage. Databricks is built on top of Spark and supports multiple languages to work on data. It also allows access to almost any external data storage as well. In short, Databricks is a one of the most competent and leading Big data compute and storage service available today in the market.</p><p>While a majority of use cases are related to data migration, extract-transform-load, and machine learning in which generally there is no application that front-end’s the data process, there are other use cases that involves a front-end application or service that initiates Jobs in Databricks. These application and services use Databricks provided REST APIs to interact with Databricks and invoke notebooks or any other program logic to initiate a Job.</p><p>While the before mentioned client using APIs to invoke a Job is nothing new, it has its own set of challenges. Let’s understand these challenges better to appreciate need for an alternate mechanism for executing Jobs in Databricks.</p><p><strong>Problem</strong></p><p>The Jobs in Databricks can be short-running but a majority of them are time-consuming. When a Service invokes a Job in Databricks using an API, it does not get the result of the Job immediately instead a Job ID is returned which can be used to get the status of the Job using another API. This means multiple API calls are required to get the status of the jobs.</p><p>Calling an API to get status of a job introduces another challenge. How does the client service know that the job has completed? It has to regularly keep polling Databricks using the API to get the status and only exit if the status is equal to completed (failed or success). It means the entire process of starting a Job and getting its final status involves multiple Databricks API calls.</p><p>Polling of an external API involves that the current thread within the service is running in a loop thereby consuming valuable resources in terms of compute and bandwidth. These resources should ideally be used to serve additional new requests rather than waiting for an existing job in Databricks to be completed.</p><p>If the before mentioned challenges are not enough, there are other issues as well. Databricks API’s have a throttle limits applied to them. After a certain number of API calls, the new calls get throttled. The only way to remove the throttling limit is to move to higher Databricks SKU which obviously are more costly than the lower SKU’s. If multiple API calls are used for a single valid client request, eventually the cost of each client goes up multiple times. Thus, Cost is another issue using the approach of waiting for a Job to be complete indefinitely.</p><p><strong>Solution</strong></p><p>The solution to the given problem is quite simple. If somehow, we can remove the polling from the client service and instead Databricks runbook callbacks the service to let it know the final status will solve all the challenges in current design. Although the solution sounds simple, it involves quite a few new components to be implemented to make it happen.</p><ul><li>There should be some way to store the temporal data like Job id, instance id etc. on the client service in a data storage.</li><li>While invoking the Databricks API, additional metadata information should be supplied to correlate the current execution values with the values that comes back with the Databricks callbacks.</li><li>The Notebooks in Databricks should be modified to include code for callbacks. Additional endpoints within service should be implemented to act as a sink for the callbacks.</li><li>This endpoint should load the temporal data from storage based on correlation data and then execute subsequent steps.</li></ul><p><strong>Architecture</strong></p><p>While the steps mentioned in the solution can be implemented as bespoke development using any technology, data storage and language, Azure provides Durable functions as out of box workflow based serverless execution that can manage state inherently using Azure storage account. Durable function Orchestrator are long running workflows that can checkpoint and store its current state on table storage after invoking an activity function. Once the activity function completes its work, the Orchestrator would load the state back and start execution of the workflow from the point of last checkpoint. This ensures that point 1 and 4 are automatically taken care if Durable functions are used in the solution.</p><p>Durable function Orchestrator also generates endpoints for each workflow execution automatically that can be invoked from external sources. The endpoints are helpful in managing the execution of the Orchestrator function. It provides an endpoint for querying the current execution status of the function, to post an event to the Orchestrator during human hand-off situations, to terminate the current execution and couple of more. The event post endpoint helps external services to send an event with custom payload to the Orchestrator and it can take further actions based on the payload. This is also the endpoint used by the Databricks notebook to callback the Orchestrator with its status as payload.</p><p>The metadata information required by the Databricks notebook is the URL representing the Durable function endpoint for posting a new event to the Orchestrator. This URL consists of the function app domain along with durable function instance id. Both of these information can be passed as parameter to the notebook from durable function and the notebook can use it to construct the complete URL and callback the orchestrator. A sequence diagram will help understand the entire flow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*rYHKJ4H6nNxHzkc8YaX7Pg.png" /></figure><p><strong>Implementation</strong></p><p>The implementation involves the following steps</p><p>1. Provision an Azure Service Principal</p><p>2. Provide the newly creates Service Principal Contributor access to the subscription</p><p>3. Login to azure using Service Principal through az cli</p><p>4. Create a new Resource Group</p><p>5. Provision Databricks workspace</p><p>6. Provision Databricks PAT token</p><p>7. Provision Databricks cluster</p><p>8. Install python libraries within Databricks cluster</p><p>9. Upload the Notebook that has both logic as well as callback code</p><p>10. Implement Azure Durable functions that acts as client for Databricks</p><p><strong>Provisioning an Azure Service Principal</strong></p><p>The approach undertaken to provision any resource on Azure is through az cli. A service principal can quickly be creates using the command</p><pre><em>az ad sp create-for-rbac</em></pre><p><strong>Provide the newly creates Service Principal Contributor access to the subscription</strong></p><p>The command assigns Contributor role at the subscription scope to the newly created service principal.</p><pre><em>az role assignment create — role “Contributor” — assignee “xxxx” — scope /subscriptions/xxx</em></pre><p><strong>Login to azure using Service Principal through az cli</strong></p><pre><em>az login — service-principal -u 8994c56f-xxxx-xxxx-xxxx-xxxxxxxxxx -p xxx — tenant 771f1cf4-xxxx-xxxx-xxxx-xxxxxxxxxxxx</em></pre><p><strong>Create a new Resource Group</strong></p><pre><em>az group create -l “westeurope” -n databricksclient</em></pre><p><strong>Provision Databricks workspace by providing name, location, sku and the name of the resource group.</strong></p><pre><em>az databricks workspace create — location “westeurope” — name “databricksample” — sku trial — resource-group databricksclient</em></pre><p>This will result in the installation of az cli databricks extension locally if it is not already installed as shown next.</p><pre>The command requires the extension databricks. Do you want to install it now? The command will continue to run after the extension is installed. (Y/n): y<br>Run ‘az config set extension.use_dynamic_install=yes_without_prompt’ to allow installing extensions without prompt.</pre><p>Eventually, if everything goes fine, it will result in successful provisioning of Databricks workspace.</p><p>If we now look at the resources within the subscription, there would be 2 resource groups provisioned — one that was created by us and the other created by databricks itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*vJBDvtP8yxiucVljJAPk4A.png" /><figcaption>provisioned resources group on Azure</figcaption></figure><p><strong>Provision Databricks PAT token</strong></p><p>We would be invoking Databricks API to execute notebooks in Databricks and this requires a PAT (personal access token). The PAT should be generated before we can use the Databricks API. We need the Databricks unique identifier and its URL along with access token to create a PAT token. The next set of commands retrieve the unique ID and Databricks URL using az cli and also generates the access token. It uses these values to invoke the 2.0/token/create Databricks API to generate the PAT token.</p><pre>dbid=$(az resource show — resource-type Microsoft.Databricks/workspaces -g databricksclient -n databricksample — query id -o tsv)</pre><pre>/subscriptions/9755ffce-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/databricksclient/providers/Microsoft.Databricks/workspaces/databricksample</pre><pre>dbUrl=$(az resource show — resource-type Microsoft.Databricks/workspaces -g databricksclient -n databricksample — query properties.workspaceUrl — output tsv)</pre><pre>adb-3181151620326766.6.azuredatabricks.net</pre><pre>accessToken=$(az account get-access-token — resource 2ff814a6–3304–4ab8–85cb-cd0e6f879c1d | jq .accessToken -r)</pre><pre>aztoken=$(curl -X GET -H ‘Content-Type: application/x-www-form-urlencoded’ -d ‘grant_type=client_credentials&amp;client_id=8994c56f-xxxx-xxxx-xxxx-xxxxxxxxxxxx&amp;resource=https://management.core.windows.net/&amp;client_secret=xxxxx&#39; <a href="https://login.microsoftonline.com/771f1cf4-b1ac-4f2e-ad21-de39ea201e7e/oauth2/token/">https://login.microsoftonline.com/771f1cf4-b1ac-4f2e-ad21-de39ea201e7e/oauth2/token/</a> | jq .access_token -r)</pre><pre>pat_token=$(curl -X POST -H “Authorization: Bearer $accessToken” -H “X-Databricks-Azure-SP-Management-Token: $aztoken” -H “X-Databricks-Azure-Workspace-Resource-Id: $dbid” -d ‘{“lifetime_seconds”: 300,”comment”: “token generation”}’ <a href="https://$dbUrl/api/2.0/token/create">https://$dbUrl/api/2.0/token/create</a> | jq .token_value -r)</pre><p><strong>Provision Databricks cluster</strong></p><p>Once we have the workspace and access token, we can now provision a cluster within the workspace. We need to provide a name for the cluster, spark version, node type and number of worker node in JSON format and invoke 2.0/clusters/create Databricks API. The access token is supplied using the HTTP header along with the request.</p><pre>CLUSTER_CONFIG=$( jq -n -c ‘{cluster_name: “testcluster”,spark_version: “8.3.x-scala2.12”,node_type_id: “Standard_D3_v2”,num_workers: 2}’ )</pre><pre>cluster_id=$(curl -X POST -H “Authorization: Bearer $accessToken” -H “X-Databricks-Azure-SP-Management-Token: $aztoken” -H “X-Databricks-Azure-Workspace-Resource-Id: $dbid” -d $CLUSTER_CONFIG <a href="https://$dbUrl/api/2.0/clusters/create">https://$dbUrl/api/2.0/clusters/create</a> | jq .cluster_id -r)</pre><p>This command would generate a new cluster and would return the cluster id as shown next. This id is important as it would be used in Durable function while invoking the Databricks notebook and also needed to install the python libraries.</p><p>“0912–122443-mangy527”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*ZI5HZFLblcHfyg7PGqKDOg.png" /></figure><p><strong>Install python libraries within Databricks cluster</strong></p><p>At this time, if the notebook in databricks is depended on any python libraries, they can be installed using the 2.0/libraries/install Databricks API. It also needs a custom payload with the name of the packages to be installed as shown next.</p><pre>LIBRARY_CONFIG=$( jq -n -c ‘{ cluster_id: “0912–122443-mangy527” , libraries: [ { pypi: { package: “azure-storage-blob”}},{ pypi: { package: “azure-storage-common”}} ]}’ )</pre><pre>Library_details=$(curl -X POST -H “Authorization: Bearer $accessToken” -H “X-Databricks-Azure-SP-Management-Token: $aztoken” -H “X-Databricks-Azure-Workspace-Resource-Id: $dbid” -d $LIBRARY_CONFIG <a href="https://$dbUrl/api/2.0/libraries/install">https://$dbUrl/api/2.0/libraries/install</a>)</pre><p><strong>Upload the Notebook that has both logic as well as callback code</strong></p><p>A sample notebook is available with accompanied code @. This notebook should be uploaded as shared notebook within the cluster since the Orchestrator function expects in a shared directory.</p><p>There are few changes that should be incorporated within the notebooks to align to the new design. The first change is to accept parameters related to metadata that would help in composing the callback URL. This would generally include the domain name of the function app and the instance id of the orchestrator. Databricks provides widgets using which parameters can be added along with their name and default values.</p><pre>dbutils.widgets.text(“callbackurl”, “https://defaulturl&quot;, “urlEmptyLabel”)</pre><pre>callbackurl = dbutils.widgets.get(“callbackurl”)</pre><pre>dbutils.widgets.text(“instance”, “https://instance&quot;, “instanceEmptyLabel”)</pre><pre>instance = dbutils.widgets.get(“instance”)</pre><p>After the availability of the parameters, the notebook should have section that invokes the callback URL. This should be done at multiple places. It should for sure be done as the last piece of the code logic within the notebook to let the callee know about the Job status. It should also be implemented within the notebook that can potentially generate errors or exceptions that might not result in a return value from the notebook. In other words, appropriate error handling should be implemented within the notebook using try-catch-finally constructs and within them the callback URL should be invoked to denote ‘failure completion’. The sample code that should be part of the notebook is shown next. Note, how the parameters are used to construct the callback URL. Also notice the URL has the name of the event as “databricks_status”. We can create as many events as we want using this pattern.</p><pre>import requests<br>import json</pre><pre>headers = {<br>  “content-type” : “application/json”<br>}</pre><pre>requests.post(f”https://<strong>{callbackurl}</strong>.azurewebsites.net/runtime/webhooks/durabletask/instances/<strong>{instance}</strong>/raiseEvent/<strong>databricks_status</strong>?taskHub=<strong>{callbackurl}</strong>&amp;connection=Storage&amp;code=xxx&quot;, <strong>data=json.dumps(payload)</strong>, headers=headers)</pre><p><strong>Implement Azure Durable functions that acts as client for Databricks</strong></p><p>The final bit that is yet to be implemented is the actual Durable function itself.</p><p>The important aspect of the function is explained next. The orchestrator function is responsible for invoking the activity function. The activity function would start the job by executing the notebook in Databricks environment. However, the activity function is asynchronous in nature and would return back immediately. Now, the Orchestrator has to wait for the callback to happen. It does not wait by occupying memory space and continually looping. Rather it checkpoints itself whenever it encounters a Timer or Waitforexternalevent function. This means that the orchestrator state is stored in the Table storage and when an external event is posted to the orchestrator using its generated endpoints, it would restart execution from point of last checkpoint. Notice, that the orchestrator is waiting for an event named “databricks_status”.</p><p>Readers would now be able understand that the notebook is raising an event of type “databricks_status” and the orchestrator is also waiting on the availability of the same event. Once the event is received, the data part of the payload from the URL is extracted and made available to the orchestrator. Orchestrator can use this data (can contain status like success, failure, done or any other information that might seem important) to execute next set of actions.</p><pre>[FunctionName(“DatabricksNotebookRunOrchestrator”)]<br>public static async Task&lt;List&lt;string&gt;&gt; RunOrchestrator(<br>[OrchestrationTrigger] IDurableOrchestrationContext context, ILogger log){</pre><pre>var outputs = new List&lt;string&gt;();<br>log.LogInformation($”Orchestrator started !!”);</pre><pre>outputs.Add(await context.CallActivityAsync&lt;string&gt;(“ExecuteDatabricksRunbook”, context.InstanceId));</pre><pre>string status = await context.WaitForExternalEvent&lt;string&gt;(“databricks_status”);</pre><pre>if (status == “done”)<br>{<br>    log.LogInformation($”done”);<br>}</pre><pre>   return outputs;</pre><pre>}</pre><p>The activity function is where the actual Job execution with the Databricks notebook gets initiated. The activity function should compose of payload that is expected by Databricks API and the important information that should be made available are the cluster id, the name and path of the notebook to be executed and the parameters it expects. Since we have instance id and callbackurl as parameters defined within the notebook — both of them should also be passed with appropriate values.</p><pre>[FunctionName(“ExecuteDatabricksRunbook”)]<br>public static async Task&lt;string&gt; ExecuteDatabricksRunbook([ActivityTrigger] string instance, ILogger log)<br>{<br>   DatabricksExecution e = new DatabricksExecution<br>   {<br>existingClusterId = “0912–122443-mangy527”,<br>RunName = “run1”,<br>TimeoutSeconds = 36000,<br>NotebookTask = new Notebook_Task<br>{<br>NotebookPath = “/Shared/testnotebook”,<br>BaseParameters = new Dictionary&lt;string, string&gt;() {<br>{ “instance”, instance },<br>{ “callbackurl”, Environment.GetEnvironmentVariable(“WEBSITE_SITE_NAME”)}<br>}<br>}<br>};</pre><pre>string jsonData = e.ToString();<br>var data = new StringContent(jsonData);<br>using (HttpClient client = new HttpClient())<br>{</pre><pre>client.BaseAddress = new Uri(“https://adb-3181151620326766.6.azuredatabricks.net/api/2.0/jobs/runs&quot;);</pre><pre>client.DefaultRequestHeaders.Accept.Clear();</pre><pre>client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue(“application/json”));</pre><pre>client.DefaultRequestHeaders.Add(“Authorization”, String.Format(“Bearer {0}”, “xxxxxx”));</pre><pre>var response = await client.PostAsync(client.BaseAddress + “/submit”, data);</pre><pre>dynamic result = JsonConvert.DeserializeObject&lt;dynamic&gt;(response.Content.ReadAsStringAsync().Result);</pre><pre>return $”Hello {result.run_id}!”;</pre><pre>}</pre><pre>}</pre><p>Once the function app is developed, it can be published using Visual studio and selecting either a new Function app or an existing app. The steps of publishing are not mentioned in this post but there is ample content available on internet on them.</p><p><strong>Runtime execution</strong></p><p>Once the environment is ready, the function app can be executed using curl or postman as shown next.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*xGuKYPjvruemGdBZeH20CQ.png" /><figcaption>Issuing HTTP request using Postman</figcaption></figure><p>It would result in Durable function endpoint generation as shown next.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*qefPfcK3CIaddKlJRDQJ4Q.png" /><figcaption>Management URL’s generated for each instance of Durable function</figcaption></figure><p>Notice that the “sendEventPostUri” has a placeholder for “eventName”. This should be replaced with the actual event name as we did in previous section. This is also the URL used for the callback purpose.</p><p>The log for the function shows the orchestrator starts executing and eventually is receives an external event “databricks_status”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*xSYvsZ4A2aEsIJ4ICEeaow.png" /><figcaption>Result from executing the Durable Orchestrator</figcaption></figure><p>After the event is received, the orchestrator can take next set of action based on the status. For example, it can update the status of the Job in Databased, can execute a compensating activity function in case of failure or any other logic as it may deem necessary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*z6q-mfJFD1uIzvnC8YH51g.png" /><figcaption>Callback execution of Durable function from Databricks</figcaption></figure><p><strong>Summary</strong></p><p>This blog showed that it is not required to poll Databricks for obtaining the status of a job executing after submission. These kind of polling results in unnecessary consumption of valuable compute and memory resources. Moreover, it also adds into the overall count of API invocation on Databricks which generally has a throttle limits. Using the pattern and implementation shown in this blog, it is possible to overcome this challenge and instead of polling, let Databricks inform the caller as and when a state change happens to let the callee decide the next course of action.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=478659dca9b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AKS internal load balancer with static IP address that is generated dynamically]]></title>
            <link>https://medium.com/@ritesh.modi/aks-internal-load-balancer-with-static-ip-address-that-is-generated-dynamically-8beb050f2481?source=rss-95e9b4985f23------2</link>
            <guid isPermaLink="false">https://medium.com/p/8beb050f2481</guid>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[services]]></category>
            <category><![CDATA[yaml]]></category>
            <category><![CDATA[static-ip]]></category>
            <dc:creator><![CDATA[Ritesh Modi]]></dc:creator>
            <pubDate>Wed, 08 Sep 2021 06:30:37 GMT</pubDate>
            <atom:updated>2021-09-08T06:34:31.641Z</atom:updated>
            <content:encoded><![CDATA[<p>Azure Kubernetes Services(AKS) allows provisioning of both external as well as internal Load balancer. Load Balancer help in distributing traffic between multiple pods backing them. A public load balancer has a public IP address assigned to it and reachable on internet while an internal load balancer has an internal IP address associated to the Pod virtual network. It does not have public IP address associated with it. It means an internal load balancer is not reachable via internet. It is only available from within the Kubernetes cluster.</p><p>A Load Balancer is created using the Service Kind in AKS. A Service by default creates a public load balancer in AKS. Let’s look at an example of creating a public load balancer in yaml format.</p><pre>apiVersion: v1<br>kind: Service <br>metadata: <br>  name: Public-IP-address<br>spec: <br>  type: LoadBalancer <br>  ports: <br>  — port: 80 <br>  selector: <br>    app: internal-app</pre><p>The code before creates a new Service resource in AKS. AKS understands that the type of service is Load balancer and it provisions a new load balancer or reuses an existing external load balancer and assigns a public IP address to it. The IP address can be obtained by executing the command on CLI.</p><pre>kubectl get service Public-IP-Address</pre><p>There is no specific attribute within the Service definition that provisions an internal load balancer. To provision an internal load balancer, annotations can be used and this is specific to AKS. Annotations are additional metadata information that can be added to any resource. AKS uses this metadata information to provision an internal load balancer instead of public load balancer.</p><p>The next code segment creates an internal load balancer instead of a public load balancer in AKS. Note the annotations attribute — it contains information that an internal load balancer should be created by assigning a true value to it. Another thing to notice here is that a dynamic IP address from the POD subnet will be assigned to the load balancer instead of the public IP address.</p><pre>apiVersion: v1 <br>kind: Service <br>metadata:   <br>  name: internal-app   <br>  <em>annotations: service.beta.kubernetes.io/azure-load-balancer-        internal: &quot;true&quot;</em> <br>spec:   <br>  type: LoadBalancer    <br>  ports:   <br>  - port: 80   <br>  selector:     <br>    app: internal-app</pre><p>The challange with this approach of creating an internal load balancer is that it will get assigned a new internal IP address in case the service object is recreated after deletion and this might break client applications in case they are directly using this IP address. One solution to this problem is to assign a static internal IP address to the load balancer as shown next. Note the attribute loadBalancerIP with value of 10.240.0.5</p><pre>apiVersion: v1 <br>kind: Service <br>metadata:   <br>  name: internal-app   <br>  <em>annotations: service.beta.kubernetes.io/azure-load-balancer-        internal: &quot;true&quot;</em> <br>spec:   <br>  type: LoadBalancer   <br>  <em>loadBalancerIP: 10.240.0.5</em>   <br>  ports:   <br>  - port: 80   <br>  selector:     <br>    app: internal-app</pre><p>while the code with statically assigned IP address to internal load balancer works and should be fine in most of the situation, there is a better way to do so. Image what would happen if the static IP address is not available at the time of creation of load balancer? What happens when you delete the service and meanwhile someone creates a POD and get assigned the load balancer IP address.</p><p>In short, the current solution needs active administration to ensure that it keeps on working in future.</p><p>A better solution is to create an internal load balancer without any static IP address. Let Azure and Kubernetes decide the best next available IP address available from the network subnet and then somehow make the newly generated IP address static for the load balancer.</p><p>To do this, create a new Service without any static IP address as shown here again.</p><pre>apiVersion: v1 <br>kind: Service <br>metadata:   <br>  name: internal-app   <br>  <em>annotations: service.beta.kubernetes.io/azure-load-balancer-        internal: &quot;true&quot;</em> <br>spec:   <br>  type: LoadBalancer    <br>  ports:   <br>  - port: 80   <br>  selector:     <br>    app: internal-app</pre><p>after creation of internal load balancer gather the newly dynamically assigned IP address</p><pre>kubectl get service internal-app -o jsonpath=&#39;{.status.loadBalancer.ingress[0].ip}&#39;</pre><p>now this IP address can be replaced in the original code using bash utilities like sed.</p><p>The new yaml file should like shown next. Note that the IP address is dynamically generated and then put statically in the yaml file. There is no need to be find or be aware of what IP addresses are available within the network subnet.</p><pre>apiVersion: v1 <br>kind: Service <br>metadata:   <br>  name: internal-app   <br>  <em>annotations: service.beta.kubernetes.io/azure-load-balancer-        internal: &quot;true&quot;</em> <br>spec:   <br>  type: LoadBalancer   <br>  <em>loadBalancerIP: 10.240.0.5</em>   <br>  ports:   <br>  - port: 80   <br>  selector:     <br>    app: internal-app</pre><p>now, the new file can be applied again using command</p><pre>kubectl apply -f ‘internal-lb.yaml’</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8beb050f2481" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing Unit Test style Performance tests to evaluate Code performance]]></title>
            <link>https://medium.com/@ritesh.modi/writing-unit-test-style-performance-tests-to-evaluate-code-performance-1e23015b1e6b?source=rss-95e9b4985f23------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e23015b1e6b</guid>
            <category><![CDATA[visual-studio]]></category>
            <category><![CDATA[performance-testing]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[cosmosdb]]></category>
            <dc:creator><![CDATA[Ritesh Modi]]></dc:creator>
            <pubDate>Wed, 02 Dec 2020 06:31:13 GMT</pubDate>
            <atom:updated>2020-12-02T06:31:13.813Z</atom:updated>
            <content:encoded><![CDATA[<p>Developers write code divided over multiple functions and check in their code to version control system. Generally, they have multiple options to write same logic using different code constructs. Each option provides different levels of performance. Developers rely on the fact that the code merged to any higher-level branch would undergo performance tests and feedback about the same would be known eventually. It would be much better if developer can test the multiple options locally before raising the pull request. Developer should be able to ascertain the performance or execution time of each function during his daily chore of coding and raise pull request after ascertaining the most performant code.</p><p>Recently, I was working on a brown field project where I was trying to evaluate whether the changes in code were improving the performance or not. It was necessary to evaluate during development whether the code change will be better-off in performance.</p><h3>Problem</h3><p>The art and science of performance tests involves trial and error methods. Using trial and error, various combinations of hyper-parameters are evaluated to find the best combination that can provide optimal performance. The difficulty arises when developers have multiple options to implement but not sure the best option to use. The developers get feedback about code performance much later during the lifecycle of code deployment. These should be mechanism through which a developer can quickly profile his code with different options and eventually push the code with the best option.</p><p>There are multiple ways to write Cosmos DB queries each resulting in same result with different performance levels. Moreover, there are multiple variables writing code against Cosmos DB. Some of the important factors that can impact performance are the Request units assigned to collection, the size of the documents stored in those collections, pre-fetching and buffering results, degree of parallelism for reading partitions, the document model (referenced vs embedded documents), indexes and more.</p><p>This post will bring out how to evaluate different options by developers and use appropriate ones to merge optimized code.</p><h3>Background</h3><p>NoSQL is the non-relational way of storing data. The backend storage can be name-value pairs, columnar, document based or any other format apart from row-column relational model.</p><p>Cosmos DB is one of the NoSQL data stores provided by Azure with multiple different types of API and storage formats. It provides MongoDB, Cassandra, graph and SQL APIs and data storage.</p><p>Data Modelling is an important aspect using NoSQL data stores. NoSQL does not have concepts related to relational databases like primary-foreign key constraints and joins. It stores data in document format. Document format is semi-structured fluid json based data structure. In both the techniques there are different document types. For example, an Order is one of the document-type while OrderDetails is another document type. There is a relationship between these two document types and the relationship should be modelled using NoSQL modelling techniques. There are two distinctive data modelling techniques with document-based NoSQL data stores.</p><h3>Embedded documents</h3><p>In this technique, the child document is embedded within the parent document. If there is a single instance of child document, then its 1:1 relationship between both parent and child document-type while if there are multiple instances of child document then it becomes 1:many relationships between them. It is difficult to project many: many relationships using embedded relationship between documents.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*mhCgkTBkFX4NXCTABHxvfQ.png" /></figure><h3>Referenced documents</h3><p>In this technique, the child document is stored in separate document from parent document and there is no relationship enforced from NoSQL engine perspective. The relationship is pure managed and decided by the application code. It is possible to have all types of relationships like 1:1, 1:Many and Many: Many with this technique.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*yqTNNMZFOSqrLn2e0xlukg.png" /></figure><p>The general recommendations to use each of the data modelling technique is</p><p><strong>Embedded documents</strong></p><p>1. When the child document is almost always queried along with parent document. Functionally, there is close interdependence between them.</p><p>2. When both the parent and child document should be updated together.</p><p>3. The number of child documents are limited</p><p>4. The child documents are not frequently updated separately</p><p>5. The child document size is small</p><p><strong>Referenced documents</strong></p><p>1. When the parent and child documents are almost always queried separately</p><p>2. When both the parent and child document are updated separately.</p><p>3. The number of child documents are unlimited</p><p>4. The child document size is large</p><p>Since the data in embedded document model are stored together in a single document, a single query is sufficient to retrieve the required data whereas multiple queries are needed in case of Referenced document model. Results from these multiple queries are joined together at client end. Again, since multiple queries are involved in case of referenced document model, it is possible to execute them in parallel or in sequence. Moreover, while running the queries in parallel, the number of threads to create becomes an important hyper-parameter. With so many variables effecting the code execution against Cosmos DB, it is important to determine the right combination for these hyper-parameters upfront and to find the optimal value for them, we will execute tests using multiple such combination and find the results.</p><h3>Embedded Queries</h3><p>Five different types of Cosmos DB queries are used to evaluate and compare the response time. These queries for embedded document model are</p><p><strong><em>1.</em></strong> <strong><em>Simple select query (select top 5000 * from c).</em></strong></p><p><strong><em>2.</em></strong> <strong><em>Query with a where clause (select * from c where c.SalesOrderId=’71884’)</em></strong></p><p><strong><em>3.</em></strong> <strong><em>Query with summation and grouping of data (SELECT top 1000 sum(c.TotalDue), c.CustomerId from c group by c.CustomerId)</em></strong></p><p><strong><em>4.</em></strong> <strong><em>Query using inbuilt function in select and/or where clause (select top 1000 CONCAT(c.SalesOrderNumber, c.AccountNumber) from c where ENDSWITH(c.SalesOrderNumber, ‘4’, false)</em></strong></p><p><strong><em>5.</em></strong> <strong><em>Query with join clause (SELECT top 1000 c.SalesOrderId, f.SalesOrderDetailID FROM c join f in c.orderdetails)</em></strong></p><h3>Referenced Queries</h3><p>The queries for referenced document model are</p><p>1. Simple Select Query to identify documents using where clause</p><p><strong><em>SELECT top 5000 * from c where IS_DEFINED(c.CustomerId)</em></strong></p><p><strong><em>SELECT top 5000 * from c where IS_DEFINED(c.SalesOrderDetailID)</em></strong></p><p>2. Query with additional where clause</p><p><strong><em>SELECT top 1000 * from c where IS_DEFINED(c.CustomerId) and c.SalesOrderId=’71783&#39;</em></strong></p><p><strong><em>SELECT top 1000 * from c where IS_DEFINED(c.SalesOrderDetailID) and c.SalesOrderId=’71783&#39;</em></strong></p><p>3. Query with group by clause</p><p><strong><em>SELECT top 1000 sum(c.TotalDue), c.CustomerId,c.SalesOrderId from c group by c.CustomerId, c.SalesOrderId</em></strong></p><p><strong><em>SELECT top 1000 * from c where IS_DEFINED(c.SalesOrderDetailID)</em></strong></p><p>4. Query with usage of inbuilt functions</p><p><strong><em>select top 1000 CONCAT(c.SalesOrderNumber, c.AccountNumber), c.SalesOrderId from c where ENDSWITH(c.SalesOrderNumber, ‘4’, false)</em></strong></p><p><strong><em>SELECT top 1000 * from c where IS_DEFINED(c.SalesOrderDetailID) and c.SalesOrderId=’71783&#39;</em></strong></p><p>5. Query with join clause</p><p><strong><em>SELECT top 1000 c.SalesOrderId, f.SalesOrderDetailID FROM c join f in c.orderdetails</em></strong></p><p><strong><em>SELECT top 1000 * from c where IS_DEFINED(c.SalesOrderDetailID)</em></strong></p><p>There are two sets of functions for response time related to Referenced documents. One using parallel execution of queries using PLINQ and other being sequential execution.</p><h3>Environment</h3><p>· Separate collection and Database for <strong>embedded</strong> and <strong>referenced</strong> documents</p><p>· The tests were run in a virtual machine with <strong>8GB of RAM</strong> <strong>and 2 vCPU</strong>.</p><p>· Number of documents in Cosmos DB collection with embedded documents : <strong>100000</strong></p><p>· Number of documents in Cosmos DB collection with embedded documents : <strong>400000</strong></p><p>· Number of executions for each test: <strong>30</strong></p><p>· Request units : <strong>5000 RU for each collection</strong></p><h3>High Level solution</h3><p>This blog provides a solution using a use-case from real life project to determine the optimal code option to use and deploy out of many implementation options. It provides the necessary details about the use case, tools used for finding the response time by Querying Cosmos DB using different queries under different conditions and eventually do comparisons between them before finalizing one of the options.</p><p>The use case used in this blog is to Query Documents from NoSQL Cosmos DB data store with SQL API provided by Azure, but it can easily be extended to any other use case or scenario. The code is written in C# and so It can be used to profile any C# code.</p><p>Cosmos DB provides client-side SDK to query Cosmos DB. It provides configuration options while querying and modifying documents in Cosmos DB collections with different levels of parallelism and pre-fetching buffering documents. Configuring these elements needs trial and error methods since each query demands different level of parallelism and buffering depending on size of documents, number of documents retrieved, the amount of request units allocated to collection and more. The current blog focus on query or read aspects and find the optimal code for querying Cosmos DB. Writing and modifying Cosmos DB will be part of subsequent blogs.</p><h3>Technologies</h3><p>· Cosmos DB — NoSQL Data store from Azure with SQL API.</p><p>· .NET core 3.1 as development framework</p><p>· Xunit — basic unit tests on the functions</p><p>· Xunit.performance — basic response time tests on the functions.</p><p>· Visual Studio 2019 as development editor</p><h3>Setup</h3><h3>Provision Cosmos DB database and collection</h3><p>Provision Cosmos DB database and collection in Azure — This step can easily be executed using portal, Azure CLI or Azure PowerShell. There should be two databases each containing a single collection with 5000 Request units and “/SalesOrderId” as partitionKey.</p><h3>Ensure data in Cosmos DB collections</h3><p>Migration of existing data into Cosmos DB collection or data should already be available within the collection. I had written a utility class that generates documents in the format required. The important thing to take care s to ensure the availability of partitionkey “SalesOrderId” in all documents since they are in same container.</p><h3>Develop the solution to query Cosmos DB collection</h3><p>Development of sample class library consisted of 3 functions that connects Cosmos DB to retrieve documents</p><p>1. Querying Cosmos DB collection containing embedded document — A function that retrieves documents based on embedded document model</p><p>2. Sequentially querying Cosmos DB collection containing multiple related reference document — A function that retrieves documents based on reference document model. This function executed couple of queries in sequence, performs groupjoin on returned documents based on SalesOrderId and returns consolidated result set.</p><p>3. Parallel querying Cosmos DB collection containing multiple related reference document — Another function very similar to second function mentioned above with the difference that queries are executed in parallel using parallel linq library instead of in sequence.</p><h3>Write Performance tests with dynamic hyper-parameters</h3><p>Development of performance test project using “xunit” template and Installing xunit.performance nuget package to write tests for measuring response time of each function under different scenarios. These scenario includes using different values for <strong><em>MaxBufferedItemCount </em></strong>and<strong><em> MaxDegreeOfParallelism </em></strong>in case of “Query Hierarchy Document function” and “Sequential Query Reference Document function” while also using different values for pLinq provided <strong><em>MaxDegreeOfParallelism </em></strong>configuration.</p><p>Xunit.performance nuget package is available at <a href="https://dotnet.myget.org/feed/dotnet-core/package/nuget/xunit.performance.api">https://dotnet.myget.org/feed/dotnet-core/package/nuget/xunit.performance.api</a> and there are multiple ways to add this package to existing project. All the option details are available at this URL.</p><p>The entire solution consists of two projects.</p><p>1. A class library project with implemented functions</p><p>2. Another xUnit unit test project for performance testing the functions in class library using multiple different hyper-parameters.</p><p>The code for the tests is available at <a href="https://github.com/ritesh-modi/CosmosDBPerformanceTesting">https://github.com/ritesh-modi/CosmosDBPerformanceTesting</a>.</p><h3>Execution</h3><p>The performance test project consists of multiple test cases for each function in class library. There are 5 functions for each of Embedded, parallel referenced documents and sequential referenced documents. These 5 functions execute 5 different queries of Cosmos DB. We have already seen these queries in setup section. Each function can be executed multiple times by supplying different values for hyper-parameters. There are two hyper-parameter configurations for each function.</p><p>The performance tests can be executed using the command shown next from within the performance project folder.</p><p><strong><em>dotnet run — perf:collect stopwatch</em></strong></p><h3>Results</h3><p>As a result of executing the test, the data shows the response times for each of the class library functions under different conditions. The yellow marked metric is the best case performance from within given constraints.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*jyC688yOU-IBAx5w9kCKQw.png" /></figure><h3>Query with Where clause and different hyper-parameters</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*MhYrCsiO1p0AWR_aBUUC0g.png" /></figure><h3>Query with Groupby clause and different hyper-parameters</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*b_rIa5GfhuD3OLTqJY2h3A.png" /></figure><h3>Query with inbuilt Cosmos DB provided functions and different hyper-parameters</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*2JK0mnF8ldJ3N_hJgQQ1EQ.png" /></figure><h3>Query with Join clause and different hyper-parameters</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*VuyDSO7B7-USvzCNwFIJMA.png" /></figure><h3>Conclusion</h3><p>It is quite evident from the results obtained that embedded model works better in terms of response time in comparison to documents referencing other documents. This is primarily because there are multiple queries involved in case of documents referencing other documents and these documents needs to be inter-weaved together before returning back to caller. However, each application and solution are different and depending on given conditions and constraints, readers should evaluate their scenario’s and determine the best modelling technique along with right hyper-parameter values for Cosmos DB. There are scenario’s where documents referencing other documents is the way to move forward in spite of embedded document providing better performance. It is important to understand to treat each use case differently and determine the performance requirement. Based on this input determine the right document modelling technique and finally use the approach mentioned here to determine the right values for hyper-parameters.</p><p>I had further executed same tests using 10000 RU’s and on a virtual machine with 32 GB RAM and 8 vCPU’s. There was no need to modify the code for the new environment and the performance results could be compared with one shown above.</p><p>Using Cosmos DB was just an example to show cause performing performance optimization during development time. As mentioned before, it could be for any code written in c#. There are further improvements possible and next blob will give perspectives on writing performance tests for modifying and adding records in Cosmos DB.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e23015b1e6b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Developing a Serverless solution to detect people without masks]]></title>
            <link>https://medium.com/@ritesh.modi/developing-a-serverless-solution-to-detect-people-without-masks-f33615059452?source=rss-95e9b4985f23------2</link>
            <guid isPermaLink="false">https://medium.com/p/f33615059452</guid>
            <category><![CDATA[coronavirus]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[covid19]]></category>
            <category><![CDATA[cognitive-science]]></category>
            <dc:creator><![CDATA[Ritesh Modi]]></dc:creator>
            <pubDate>Mon, 18 May 2020 08:02:24 GMT</pubDate>
            <atom:updated>2020-06-24T11:34:09.352Z</atom:updated>
            <content:encoded><![CDATA[<h3>Developing a Serverless solution to detect people with masks</h3><blockquote>“Build an production grade HTTP Serverless API and Frontend that detects whether people within images are wearing Masks or not. It helps in identifying if masks are not worn by individuals within images.”</blockquote><p>Code can be downloaded from <a href="https://github.com/RIteshSolidity/MaskIdentifier">https://github.com/RIteshSolidity/MaskIdentifier</a></p><p>The app created here should be provided an URL or binary data of an Image. The Image data or url is send to the Serverless API hosted on Azure functions to detect the people wearing masks. Azure function will use Azure Cognitive Services to get the relevant information and return them back to the Application. The application would render the people wearing masks in Red rectangle. Check the sample images to understand the concept better.</p><p>This is an image with a few people in it — some wearing mask while others not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/280/1*rMysIqxwJGGIwamHcA41tA.jpeg" /><figcaption>People with and without Masks</figcaption></figure><p>The same image after rendering within the app is shown next. Note that three people are wearing mask and they are identified using Red Rectangle while others are not highlighted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/287/1*U0-6gaybirrvclyzkKYo1A.png" /></figure><p>Some more examples are shown here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*Q2rPvquv3X59owmGjUAvsA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/287/1*I5STcE-27ap2HUuplxS6kw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*ahpOthPzZp0a11eNgNxALQ.png" /></figure><p><strong>Usage</strong></p><ol><li>Authorities can use for identifying people not following guidelines.</li><li>Hotels, airports, any means of commute can use to check the compliance related to masks.</li><li>Companies opening up can check for employee and integrate into their existing Covid19 related compliance infrastructure.</li><li>Local meetups can use to check community members if not wearing masks.</li><li>Any place where people gather can be checked for compliance like parks, community halls, shops etc.</li></ol><p><strong>Implementation</strong></p><p>The front end is a desktop application and can easily be created into Android and IOS app. It expects a file path for an image, loads the file and passes to API to which eventually identifies all the masks along with the coordinates within the image. The coordinates are available as JSON array with each item consisting of left, width, right and height of the masks. The response also contains the score in terms of probability to determine the confidence level whether it actually is a mask.</p><p>Serverless is one of the most talked about paradigm in recent times after the combination of (IaaS-PaaS-SaaS) in technology and especially cloud world. CxO’s of almost all enterprises are thinking, discussing their strategies for their next set for digitization, modernization and transformation and Serverless is one of the prominent topics in them. While creating a simple API using Serverless is quite simple and can be done in few minutes; important question to ask is whether it is production ready.</p><h3>Background</h3><p>Serverless technically does not mean “without servers”. It means although servers are used to provide compute resources for applications, the customer does not see, manage, govern the server, its infrastructure and Operating system. Customers are responsible for bringing their code and serverless will execute them on any server that it deems fit or fixed for it.</p><h3>Serverless</h3><p>Serverless brings numerous path breaking paradigm changes when compares to older deployment models. Some of the important ones are</p><p>1. <strong>Pay as you consume (PAYC) model </strong>— In this model, if a Serverless application is not consumed at all or consumed within a given limit ( the limit differs between cloud providers and availability of their free limit) a customer do not incur any cost to cloud provider. This is especially very beneficial for start-ups and early stage companies that do not have super monetary monetary power to block compute, storage and network on monthly basis from cloud providers (as in case of IaaS as well as PaaS deployments) not ability to purchase hardware for On-premises.</p><p>2. <strong>Unlimited Scalability </strong>— This is again a big advantage for companies that have B2C model and at stroke of luck may see demand for their API’s in millions within hours. Although IaaS and PaaS provides this features using observability and automation, it is not free from delays and cost; moreover requires prior auto-scaling configuration, testing and at times manual intervention. Serverless provides true scalability in terms that it provides SLA in terms of serving all requests and throughput. If it needs to scale to hundreds of servers behind due to sudden spike in demand, it does so without even informing the customer.</p><p>3. <strong>Out-of-box High Availability </strong>— High Availability is one of the tenets customers are moving to Cloud and there are different ways to achieve High availability depending on the type of deployment — IaaS or PaaS. Serverless is highly available by default at cloud region level and there is no configuration required to achieve it. However, to achieve High availability across region, multiple Serverless instances can be created across regions connected by global load balancers.</p><h3>Covid19</h3><p>If there is anything that has impact any one of us the most this year or may be from the time we are born, it is the Coronavirus a.k.a. Covid19. It is caused such mass scale health and economic destruction across the globe and it has been unprecedented. There are lots of changes in statutory laws and public health procedures. So much so that people are under lock down and it is mandatory to wear Masks — no matter what kind if stepping out to public places.</p><p>The entire scientific community is spending days and nights to find a cure for this virus and technologies companies are creating applications in fortnight related to social-distancing, Contact tracing, people and vehicle movements, approvals from Government, tracking of patients and many more.</p><p>In this article, I have tried to provide the steps to create a simple REST API using Azure Functions (although any cloud provider can be used) to detect whether individuals within an image are wearing Masks or not. The Focus has been to create production ready Azure function based REST API by means of detecting and identifying Masks within images.</p><p><strong>Technology Used</strong></p><p>1. Azure functions</p><p>2. Azure Cognitive Services Custom Computer Vision API</p><p>3. Visual Studio 2019</p><p>4. POSTMAN</p><p><strong>Approach</strong></p><ul><li>Started with creating an instance of Cognitive Services Custom Vision on Azure.</li><li>Then identified more than 50 images from Bing/Google that has people wearing masks and another set of 50 images in which people are not wearing masks. The images were identified keep in view</li></ul><blockquote><em>Different backgrounds</em></blockquote><blockquote><em>Different shades, color and lighting</em></blockquote><blockquote><em>People in Groups and individual</em></blockquote><blockquote><em>Different camera angles</em></blockquote><ul><li><strong>Uploaded </strong>the images to <strong>Customvision.ai</strong> portal and <strong>tagged </strong>all the images with — mask or no mask</li><li><strong>Trained </strong>and <strong>published </strong>the model</li><li><strong>Created </strong>a new Azure Function project using Visual Studio 2019 and implemented the logic for the REST API</li><li><strong>Conducted </strong>unit testing using <strong>MOQ </strong>and <strong>xUnit</strong></li><li><strong>Deployed </strong>the API on Azure Function APP</li></ul><p><strong>Prerequisites</strong></p><ol><li>Access to Azure portal and RBAC (Role based access control) permissions to create resources. <a href="https://azure.microsoft.com/en-in/free/">docs here</a> and <a href="https://docs.microsoft.com/en-us/azure/role-based-access-control/overview">here</a>.</li><li>Visual Studio 2019 environment for implementation and local testing of code. <a href="https://visualstudio.microsoft.com/">docs here</a></li><li>Postman to invoke Function API. It can be downloaded from <a href="https://www.postman.com/">here</a></li></ol><h3>Configuration</h3><p>In order to use this application, there are some configurations you should do first. local.settings.json within the project:</p><pre>// local.settings.json{&quot;Values&quot;: {&quot;cognitiveapi&quot;: &quot;{{url of Cognitive Services}}&quot;,&quot;cognitivekey&quot;: &quot;{{Access Key of Cognitive Services}}&quot;}}</pre><p><strong>Developing the Application</strong></p><p>The first step is to create Cognitive Service Custom vision Service on Azure, upload images and tag them between “mask” and “nomask”. After Tagging the entire model should be trained and tested.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/0*SqAOvzipevGAKj-P.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IXRg_8xzYZ__g3qM.png" /></figure><p>After appropriate testing, it should be published. This will generate the url that should be consumed from Azure functions.</p><p>The next step in to create a function app using HTTP Trigger in visual Studio 2019. The Visual studio scaffolding will create a default function. We will remove the Get method and provide implementation for connecting to Cognitive Service and get appropriate response from it.</p><p>The settings file is updated with Cognitive Services URL and key.</p><p>The code for the function is upload and can be found <a href="https://github.com/RIteshSolidity/MaskIdentifier/tree/master/FunctionApp27">here</a>.</p><p>Write unit tests to test the function and upload the function to function app.</p><h3>Use the application</h3><p>The API has been deployed on Azure within Function App and can be invoked using postman.</p><p>The function accepts POST request in JSON format. The same can be configured within Postman.</p><p>The body of the request should contain the URL of the image that needs to be evaluated for mask identification. The payload should be send using JSON payload as shown here.</p><blockquote><em>{</em></blockquote><blockquote><em>“url” : “https://deststorage13.blob.core.windows.net/kokokokok/5e71267bc4854010b62f5925.jpg&quot;</em></blockquote><blockquote><em>}</em></blockquote><p>The postman should be configured as shown here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1UC8dTNyXeMX6uZb.png" /></figure><p>It would return</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/0*a6SuwUioJEQFTngF.png" /></figure><p><strong>To run in Azure</strong></p><ol><li>Right click in VS Code left menu and click Deploy to Function App…</li><li>Go to portal and add the following keys to the function app’s APP SETTINGS</li></ol><blockquote><em>“ cognitiveapi”: “&lt;&lt;COGNITIVE_URL&gt;&gt;”</em></blockquote><blockquote><em>“ cognitivekey”: “&lt;&lt;COGNITIVE_KEY&gt;&gt;”</em></blockquote><p><strong>Solution hosting options</strong></p><blockquote><em>Azure functions — this has been used for the solution</em></blockquote><blockquote><em>Azure Kubernetes services within Pods</em></blockquote><blockquote><em>Azure App Services</em></blockquote><blockquote><em>virtual machines</em></blockquote><blockquote><em>Containers on Virtual machines using images with Azure Function runtime</em></blockquote><p><em>Azure Functions was chosen as deployment target since it provides high availability and unlimited scalability out of the box. It is also cost effective (cost based on usage) compared to other options where there is fixed cost associated with underlying virtual machine. AKS will have fixed cost for worker nodes.</em></p><p><strong>Assumptions</strong></p><ul><li>English as the language of communication</li><li>The response from API when greater than 75% probability for Mask is shown as “Mask” otherwise as “nomask”</li><li>the API uses HTTP POST method and did not use GET method — although it could have been used.</li><li>JSON is the choice of data serialization.</li><li>Instead of uploading the entire file to Cognitive services, URL of the images is passed as POST request to API. The Cognitive Services is able to download the image locally and provide its analysis.</li></ul><p><strong>steps to deploy</strong></p><ol><li>provision a Function APP in a region</li><li>Provision a storage account in same region. All resources should be in same region</li><li>Clone the solution in local environment</li><li>publish the function app project to Function APP. Please remember to update the Azure App Service settings in visual studio before publishing the function to function app. Also manually edit the function app configuration to add the connection string of table storage.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/0*yTlVOUm57rYXf2vY.png" /></figure><p>5. Update the Cognitive Services URL and key either in visual studio as shown in next image or from portal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1EZ7s9592ysOhCTQ.png" /></figure><p>Few architectural concerns that should be taken care before deploying the API on production has been listed next.</p><p><strong>Security consideration</strong></p><p>Azure Function provides numerous ways to invoke functions and HTTP trigger based function needs addition protection since they can be invoked by anyone who knows about the URL.</p><p>Foremost, the endpoint must be protected using TLS 2.0 at minimum. It means that they only way to reach out to the service is by means of HTTPS. This would ensure the request-response messages are encrypted and that only the intended participants can understand the messages. So, the next question arises how do we know who are the intended participants and how can vouch their Identity. For a customer facing endpoint, it is not prudent to manage the identities locally and manage them actively. Instead, it is better to delegate the identity verification process to an established identity providers like Facebook, Twitter, google etc. They all implement Open ID connect and oAuth protocols and with trust build between the API and these Identity providers, it is possible to authenticate and authorize users before accessing the API.</p><p>The API also should be behind a firewall. It means that only valid and allowed requests should be allowed to reach the API. Well known security threat assets should be configured on the firewall to filter any unwanted traffic from suspicious IP addresses, port and files.</p><p>The API can be hosted within an API management service that can manage and administer the API. For example, Azure API management can be used for rate limit the requests to the API based on the kind of user and plan they have subscribed for, generating unique keys to access the API and many more other benefits.</p><p><strong>Automated Build and Releases</strong></p><p>The API should have a well-defined build and release process. The build pipeline should ensure the readiness of the API to be deployed on any environment starting from Development eventually to production environment. Both the build and release pipelines should have quality checks passed before moving from one environment to another environment. At minimum some of the checks that should be performed are unit tests getting passed, code coverage of both unit tests as well as API itself. Code quality using tools like <em>StyleCop</em>, <em>FxCop </em>and <em>SonarCube</em>. Static as well dynamic code security checks to identify an password, credentials or any other secret and confidential information not getting leaked within the source code, integration between multiple module etc.</p><p><strong>Code Quality</strong></p><p>Ensure proper logging and exception handling is implemented within the code. This should ensure that there should not be leakage of any sensitive information to both logs as well as to users invoking the API.</p><p>The code should have minimal hard-coding and secrets should be derived from vaults like Azure Key Vault and non-sensitive information from configuration files.</p><p>Reuse code and each function should not be very length. The cyclometric complexity of any function should be less than 10.</p><p>There should not be long running loops since Serverless requests are time-boxed and they should be stateless (should not be session dependent or require sticky sessions).</p><p>Test your application enough to ensure all edge cases along with regular cases have been addressed.</p><p><strong>Monitoring</strong></p><p>The API should be actively monitored using Azure App Insights, Log Analytics, Security center and Sentinel for Performance, Health, Security, SLA, KPI and other aspects like exception and traces.</p><p><strong>Resources/Tools</strong></p><ul><li><a href="https://visualstudio.microsoft.com/"><strong>Visual Studio</strong></a></li><li><a href="https://www.getpostman.com/downloads/"><strong>Postman</strong></a></li><li><strong>PowerShell</strong></li></ul><p><strong>Next Steps 🏃</strong></p><ul><li>Write more unit tests</li><li>Instead of just capturing whether mask is in picture or not, we can get all faces and whether mask it there or not on faces with probabilities</li></ul><p><strong>Important Resources ⭐️</strong></p><p>Here include all the important resources related to the article</p><p><a href="https://docs.microsoft.com/azure/azure-functions"><strong>Azure Functions documentation</strong></a></p><p><a href="https://docs.microsoft.com/azure/azure-functions/functions-develop-vs"><strong>Create your first Function app using Visual Studio</strong></a></p><p><a href="https://docs.microsoft.com/en-us/azure/cognitive-services/custom-vision-service/"><strong>Cognitive Services Custom Vision</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f33615059452" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to run Production Grade Serverless based API on Azure]]></title>
            <link>https://medium.com/@ritesh.modi/how-to-run-production-grade-serverless-based-api-on-azure-2c40bb2726cd?source=rss-95e9b4985f23------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c40bb2726cd</guid>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[coronavirus]]></category>
            <category><![CDATA[azure-functions]]></category>
            <category><![CDATA[covid19]]></category>
            <category><![CDATA[cognitive]]></category>
            <dc:creator><![CDATA[Ritesh Modi]]></dc:creator>
            <pubDate>Sun, 17 May 2020 16:31:48 GMT</pubDate>
            <atom:updated>2025-05-11T11:54:56.514Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to run production grade serverless based API on Azure</h3><p>Code for article available @ github <a href="https://github.com/RIteshSolidity/MaskIdentifier/tree/master/FunctionApp27">here</a></p><blockquote><em>“Build an production grade HTTP serverless API that detects whether people within images are wearing Masks or not. It helps in identifying if masks are not worn by individuals within images.”</em></blockquote><p>Serverless is one of the most talked about paradigm in recent times after the combination of (IaaS-PaaS-SaaS) in technology and especially cloud world. CxO’s of almost all enterprises are thinking, discussing their strategies for their next set for digitization, modernization and transformation and Serverless is one of the prominent topics in them. While creating a simple API using Serverless is quite simple and can be done in few minutes; important question to ask is whether it is production ready.</p><h3><strong>Background</strong></h3><p>Serverless technically does not mean “without servers”. It means although servers are used to provide compute resources for applications, the customer does not see, manage, govern the server, its infrastructure and Operating system. Customers are responsible for bringing their code and serverless will execute them on any server that it deems fit or fixed for it.</p><h4><strong>Serverless</strong></h4><p>Serverless brings numerous path breaking paradigm changes when compares to older deployment models. Some of the important ones are</p><p>1. <strong>Pay as you consume (PAYC) model </strong>— In this model, if a serverless application is not consumed at all or consumed within a given limit ( the limit differs between cloud providers and availability of their free limit) a customer do not incur any cost to cloud provider. This is especially very beneficial for start-ups and early stage companies that do not have super monetary monetary power to block compute, storage and network on monthly basis from cloud providers (as in case of IaaS as well as PaaS deployments) not ability to purchase hardware for On-premises.</p><p>2. <strong>Unlimited Scalability </strong>— This is again a big advantage for companies that have B2C model and at stroke of luck may see demand for their API’s in millions within hours. Although IaaS and PaaS provides this features using observability and automation, it is not free from delays and cost; moreover requires prior auto-scaling configuration, testing and at times manual intervention. Serverless provides true scalability in terms that it provides SLA in terms of serving all requests and throughput. If it needs to scale to hundreds of servers behind due to sudden spike in demand, it does so without even informing the customer.</p><p>3. <strong>Out-of-box High Availability </strong>— High Availability is one of the tenets customers are moving to Cloud and there are different ways to achieve High availability depending on the type of deployment — IaaS or PaaS. Serverless is highly available by default at cloud region level and there is no configuration required to achieve it. However, to achieve High availability across region, multiple Serverless instances can be created across regions connected by global load balancers.</p><h4><strong>Covid19</strong></h4><p>If there is anything that has impact any one of us the most this year or may be from the time we are born, it is the Coronavirus a.k.a. Covid19. It is caused such mass scale health and economic destruction across the globe and it has been unprecedented. There are lots of changes in statutory laws and public health procedures. So much so that people are under lock down and it is mandatory to wear Masks — no matter what kind if stepping out to public places.</p><p>The entire scientific community is spending days and nights to find a cure for this virus and technologies companies are creating applications in fortnight related to social-distancing, Contact tracing, people and vehicle movements, approvals from Government, tracking of patients and many more.</p><p>In this article, I have tried to provide the steps to create a simple REST API using Azure Functions (although any cloud provider can be used) to detect whether individuals within an image are wearing Masks or not. The Focus has been to create production ready Azure function based REST API by means of detecting and identifying Masks within images.</p><p><strong>Technology Used</strong></p><p>1. Azure functions</p><p>2. Azure Cognitive Services Custom Computer Vision API</p><p>3. Visual Studio 2019</p><p>4. POSTMAN</p><p><strong>Approach</strong></p><ul><li>Started with creating an instance of Cognitive Services Custom Vision on Azure.</li><li>Then identified more than 50 images from Bing/Google that has people wearing masks and another set of 50 images in which people are not wearing masks. The images were identified keep in view</li></ul><blockquote>Different backgrounds</blockquote><blockquote>Different shades, colour and lighting</blockquote><blockquote>People in Groups and individual</blockquote><blockquote>Different camera angles</blockquote><ul><li><strong>Uploaded </strong>the images to <strong>Customvision.ai</strong> portal and <strong>tagged </strong>all the images — mask or no mask</li><li><strong>Trained </strong>and <strong>published </strong>the model</li><li><strong>Created </strong>a new Azure Function project using Visual Studio 2019 and implemented the logic for the REST API</li><li><strong>Conducted </strong>unit testing using <strong>MOQ </strong>and <strong>xUnit</strong></li><li><strong>Deployed </strong>the API on Azure Function APP</li></ul><p><strong>Prerequisites</strong></p><ol><li>Access to Azure portal and RBAC (Role based access control) permissions to create resources. <a href="https://azure.microsoft.com/en-in/free/">docs here</a> and <a href="https://docs.microsoft.com/en-us/azure/role-based-access-control/overview">here</a>.</li><li>Visual Studio 2019 environment for implementation and local testing of code. <a href="https://visualstudio.microsoft.com/">docs here</a></li><li>Postman to invoke Function API. It can be downloaded from <a href="https://www.postman.com/">here</a></li></ol><h3>Configuration</h3><p>In order to use this application, there are some configurations you should do first. local.settings.json within the project:</p><pre>// local.settings.json</pre><pre>{</pre><pre>&quot;Values&quot;: {</pre><pre>&quot;cognitiveapi&quot;: &quot;{{url of Cognitive Services}}&quot;,</pre><pre>&quot;cognitivekey&quot;: &quot;{{Access Key of Cognitive Services}}&quot;</pre><pre>}</pre><pre>}</pre><p><strong>Developing the Application</strong></p><p>The first step is to create Cognitive Service Custom vision Service on Azure, upload images and tag them between “mask” and “nomask”. After Tagging the entire model should be trained and tested.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*YNq_9jElAi1giTtv1TbyMw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5mgQe-IB_dEurCSspSyMMQ.png" /></figure><p>After appropriate testing, it should be published. This will generate the url that should be consumed from Azure functions.</p><p>The next step in to create a function app using HTTP Trigger in visual Studio 2019. The Visual studio scaffolding will create a default function. We will remove the Get method and provide implementation for connecting to Cognitive Service and get appropriate response from it.</p><p>The settings file is updated with Cognitive Services URL and key.</p><p>The code for the function is upload and can be found <a href="https://github.com/RIteshSolidity/MaskIdentifier/tree/master/FunctionApp27">here</a>.</p><p>Write unit tests to test the function and upload the function to function app.</p><h3>Use the application</h3><p>The API has been deployed on Azure within Function App and can be invoked using postman.</p><p>The function accepts POST request in JSON format. The same can be configured within Postman.</p><p>The body of the request should contain the URL of the image that needs to be evaluated for mask identification. The payload should be send using JSON payload as shown here.</p><blockquote>{</blockquote><blockquote>“url” : “https://deststorage13.blob.core.windows.net/kokokokok/5e71267bc4854010b62f5925.jpg&quot;</blockquote><blockquote>}</blockquote><p>The postman should be configured as shown here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qg_UnAh8NGu_Tam7Fnr2UQ.png" /></figure><p>It would return</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*2-X8ch55enn2u9oH46y2Jg.png" /></figure><p><strong>To run in Azure</strong></p><ol><li>Right click in VS Code left menu and click Deploy to Function App…</li><li>Go to portal and add the following keys to the function app’s APP SETTINGS</li></ol><blockquote>“ cognitiveapi”: “&lt;&lt;COGNITIVE_URL&gt;&gt;”</blockquote><blockquote>“ cognitivekey”: “&lt;&lt;COGNITIVE_KEY&gt;&gt;”</blockquote><p><strong>Solution hosting options</strong></p><blockquote>Azure functions — this has been used for the solution</blockquote><blockquote>Azure Kubernetes services within Pods</blockquote><blockquote>Azure App Services</blockquote><blockquote>virtual machines</blockquote><blockquote>Containers on Virtual machines using images with Azure Function runtime</blockquote><p><em>Azure Functions was chosen as deployment target since it provides high availability and unlimited scalability out of the box. It is also cost effective (cost based on usage) compared to other options where there is fixed cost associated with underlying virtual machine. AKS will have fixed cost for worker nodes.</em></p><p><strong>Azure Function Plans Consideration</strong></p><p>Azure functions provides three plans:</p><p><strong>1. Consumption plan </strong>— this is ideal of most of scenarios for hosting functions. In this plan, the function can run on any server and it might not be dedicated to the function app completely. The server can be shared with other function apps as well. If the function is not consumed for some time, the function might get cold. The next time a request comes for the function, it might take some time for function to get compiled and deployed to a server. This is also known as Cold start.</p><p><strong>2. App Service Plan </strong>— this plan is very similar to App services plan for web apps. There are dedicated servers used for hosting the function app and the cost is on usage basis rather than consumption basis. The cost starts as soon as the servers are up and running. This plan should be used if the request patterns are already known for an application and an optimal amount of resources are already provisioned.</p><p><strong>3. Premium Plan</strong> — this plan is similar to consumption plan with an added advantage of no Cold starts. The application remains warm and there are no occasional delays. In this plan, the size of the servers can also be selected and it is billed based on resource consumption rather than both consumption and execution. It is ideal to host the current application on Premium plan because of advantages it provides from both App Service and Consumption plan.</p><p><strong>Assumptions</strong></p><ul><li>English as the language of communication</li><li>The response from API when greater than 75% probability for Mask is shown as “Mask” otherwise as “nomask”</li><li>the API uses HTTP POST method and did not use GET method — although it could have been used.</li><li>JSON is the choice of data serialization.</li><li>Instead of uploading the entire file to Cognitive services, URL of the images is passed as POST request to API. The Cognitive Services is able to download the image locally and provide its analysis.</li></ul><p><strong>steps to deploy</strong></p><ol><li>provision a Function APP in a region</li><li>Provision a storage account in same region. All resources should be in same region</li><li>Clone the solution in local environment</li><li>publish the function app project to Function APP. Please remember to update the Azure App Service settings in visual studio before publishing the function to function app. Also manually edit the function app configuration to add the connection string of table storage.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*rHPjO9B1__k6C4t8jSZwxw.png" /></figure><p>5. Update the Cognitive Services URL and key either in visual studio as shown in next image or from portal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pP5YwA0nOUtJpLeiL-w-xw.png" /></figure><p><strong>Resources/Tools</strong></p><ul><li><a href="https://visualstudio.microsoft.com/"><strong>Visual Studio</strong></a></li><li><a href="https://www.getpostman.com/downloads/"><strong>Postman</strong></a></li></ul><p><strong>Next Steps 🏃</strong></p><ul><li>Write more unit tests</li><li>Instead of just capturing whether mask is in picture or not, we can get all faces and whether mask it there or not on faces with probabilities</li></ul><p><strong>Important Resources ⭐️</strong></p><p>Here include all the important resources related to the article</p><p><a href="https://docs.microsoft.com/azure/azure-functions"><strong>Azure Functions documentation</strong></a></p><p><a href="https://docs.microsoft.com/azure/azure-functions/functions-develop-vs"><strong>Create your first Function app using Visual Studio</strong></a></p><p><a href="https://docs.microsoft.com/en-us/azure/cognitive-services/custom-vision-service/"><strong>Cognitive Services Custom Vision</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c40bb2726cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Blockchain, Ethereum and Smart Contracts — Chapter 1]]></title>
            <link>https://medium.com/coinmonks/https-medium-com-ritesh-modi-solidity-chapter1-63dfaff08a11?source=rss-95e9b4985f23------2</link>
            <guid isPermaLink="false">https://medium.com/p/63dfaff08a11</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[Ritesh Modi]]></dc:creator>
            <pubDate>Wed, 16 May 2018 06:56:37 GMT</pubDate>
            <atom:updated>2022-06-25T15:53:18.716Z</atom:updated>
            <content:encoded><![CDATA[<p>This decade has already witnessed an extraordinary evolution in the technology and computing ecosystem. Technology innovation and its impact is already running very high. From IoT to Artificial Intelligence to Blockchain. Each of them have a disruptive force within multiple industries and Blockchain is termed as one of the most disruptive technology of today. So much so, Blockchain has potential to change almost every industry today and its working. The applicability of Blockchain because of its advantages and pervasiveness has already picked up stream and seems like it will continue to long time to come. Blockchain is not a new technology however it has gained super momentum in last couple of years. It is a big leap forward in terms of things about decentralized and distributed applications. It is about thinking of current architectural landscape and strategize to move towards immutable distributed databases. The advantages and many and helping organisations reach out to their stakeholders without requiring any central authority and intermediaries.</p><p>In this first chapter, you will quickly learn understand the basic and foundational concepts of Blockchain and Ethereum. I will also discuss the important components and their interaction to make Blockchain and Ethereum work. It will also touch briefly on the topic of smart contracts and how to author them using solidity.</p><p>It is to be noted that this chapter explain important Blockchain and Ethereum concepts briefly for writing sound Solidity contracts. It does not explain concepts in details and complete book can be written for that purpose. Since, Ethereum is an implementation of Blockchain, they have been used interchangeable in this book.</p><p>This chapter will focus on</p><p>· Architecture of Blockchain · Understanding Storage</p><p>· Understanding Blocks</p><p>· Understanding Transactions</p><p>· Understand Mining</p><p>· Understanding Accounts</p><p>· Understanding Cryptography</p><p>· Gas</p><p>· Ether</p><p>· Sending transaction</p><p>· Smart Contracts</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*KwQtjLdt5WmcCXLBxIAECQ.png" /></figure><h3><strong>What is Blockchain?</strong></h3><p>Blockchain is essentially a decentralized distributed database or a ledger. There are some very important keywords like Decentralized, distributed, database and ledger used in defining a Blockchain.</p><p>Decentralization in simple term means that the application or service continues to be available and usable even if a server or a group of servers on a network crashes or are not available. The service or application is deployed on a network in a way that no server has absolute control over data and execution rather each server has current copy of data and execution logic with them.</p><p>Distributed means that any server or node on a network is connected to every other node on the network directly or indirectly. Rather than having one to one or one to many connectivity between servers, servers have many to many connections with other servers.</p><p>Database refers to location for storing durable data that can be accessed at any point in time. Database allows storage and retrieval of data and provides management functionalities to manage data efficiently like export, import, backup and restoration.</p><p>Ledger is an accounting term and think of it as specialized storage and retrieval of data. Think of ledgers that are available with banks. When a transaction is executed with a Bank say Tom deposits 100 dollars in his account, the bank enters this information in ledger as a credit. At some point in time in future Tom withdraws 25 dollars. The bank does not modify the existing entry and stored data from 100 to 75. Instead it adds another entry in the same ledger as a debit of 25 dollars. It means a ledger is a specialized database that do not allow modification of existing data. It allows creation and appending of new transaction to modify the current balance in ledger. Blockchain is a database that has the same characteristics of a ledger. It allows newer transaction to be stores in append only pattern without any scope to modify past transaction. It is important here to understand that existing data can be modified be using a new transaction, but past transactions cannot be modified. A balance of 100 dollar can be modified anytime by executing a new debit or credit transaction but previous transactions cannot be modified.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*Nui8F6lraH1pW750z9tbMg.png" /></figure><p>Blockchain as the word refers means a chain of Blocks. Blockchain means having multiple blocks chained together and each block stores transactions in a way that it is not possible to modify these transactions. We will discuss in later section about storage of transactions and how immutability is achieved in Blockchain.</p><p>Not being able to change and modify past transactions makes Blockchain solution highly trustworthy, transparent and incorruptible.</p><p>It is important to understand that blocks and its chain is just one of the facets of blockchain. There are other important concept like mining, miners, consensus and protocol that works along with chain of blocks to make blockchain work flawlessly.</p><p>Ethereum is an implementation of Blockchain and allows extending its functionality with the help of smart contracts. Smart contracts will be addressed in detail through out this book.</p><h3>Why Blockchain</h3><p>The main objective of Ethereum is to accept transactions from accounts, update their state and maintain this state as current state till another transaction updates it again. The whole process of accepting, executing and writing transactions can be divided into two phases in Ethereum. There is a decoupling between when a transaction is accepted by Ethereum and when the transaction is executed and written to the ledger. This decoupling is quite important for decentralization and distributed architecture to work as expected.</p><p>Blockchain helps primarily in three different ways</p><p>1. Trust — Blockchain helps in creating applications that are decentralized and collectively owned by multiple people. No body within this group has the power to change or delete previous transactions. Even if someone tries to do so, it will not be accepted by other stakeholders.</p><p>2. Autonomy — There is no single owner for Blockchain based applications. No one controls the blockchain, but everyone participates into its activities. This helps in creating solutions that cannot be manipulated or induce corruption.</p><p>3. Integrity — The state and transactions are secured cryptographically and cannot be modified easily.</p><p>4. Intermediaries — Blockchain based application can help remove the intermediaries from existing processes. Generally, there is a central body like Vehicle registration, licence issuing etc who acts as registrar for registering vehicles as well as issuing driver licences. Without Blockchain based systems, there is no central body and if a licence is issues or vehicle is registration after Blockchain mining process, that will remain a fact for epoch time-period without the need of any central authority vouching for it.</p><p>Blockchain is heavily depended on Cryptography technologies and next section is a brief on it.</p><h3>Cryptography</h3><p>There are primarily two types of cryptography in computing:</p><h4>Symmetric Encryption and Decryption</h4><p>Symmetric cryptography refers to process of using a single key both encryption and decryption. It means the same key should be available to multiple people if they want to exchange messages using this form of cryptography</p><h4>aSymmetric Encryption and Decryption</h4><p>Asymmetric cryptography refers to process of using two keys for encryption and decryption. Any key can be used for encryption and decryption. Messages encryption with public key can be decrypted using private key and messages encryption by private key can be decrypted using public key. Let’s understand this with the help of an example. Tom using Alice’s public key to encrypts messages and sends it to Alice. Alice can use her private key to decrypt the message and extract contents out of it. Messages encrypted with Alice’s public key can only be decrypted by Alice as she only holds her private key and no one else. This is the general use case of Asymmetric keys. There is another use which we will see while discussing Digital signatures.</p><h3>Hashing</h3><p>Hashing is the process of transforming string data into another fixed length string data and it is not possible to re-generate or identify the original data from resultant string data. Hashing ensures that even a slight change in input data will completely change the output data and no one can ascertain the change in the original data. There is another important property of hashing is that no matter the size of input string data the length of its output is always fixed. For example, using SHA256 hashing algorithm and function with any length of input will always generate 256-bit output data. This can especially become useful when large amount of data can be stored as 256-bit output data. Ethereum uses Hashing quite extensively. It hashes all the transaction data, hashes multiple transaction hashes to generate single root transaction hash and in fact the blocks in Ethereum are also represented as hash.</p><p>Another important property of hashing is that it is mathematically not feasible to identify two different input strings that will output the same hash. Similarly, it is not possible to computationally and mathematically find the input from the hash itself.</p><p>Ethereum uses SHA256 for all its hashing needs.</p><p>The next image shows an example of Hashing. The input Ritesh Modi generates a hash “b9fda68f334232a4c832ff355aef9949bf3229cd2f9be8dccf95c8ee1d2c2dbb”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*g_7GIr52Spex1OwK-XbJyA.png" /></figure><p>And even a small modification to input generates a completely different hash.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*lLInhtXVP521ulVyLKtRFw.png" /></figure><h3>Digital Signatures</h3><p>Earlier, we discussed cryptography using asymmetric keys. One of the important uses case of using Asymmetric keys in in creation and verification of Digital signature. Digital signatures are very similar to signature done by an individual on a piece of paper. Similar to a paper signature, digital signature helps in identifying an individual. It also helps in ensuring that messages are not tampered with in transit. Lets understand Digital signature with the help of an example.</p><p>Alice wants to send a message to Tom. How can Tom identify and ensure that the message has come from Alice only and that the message has not been changed or tampered with in transit? Alice takes the message she wants to send to Tom and generates a hash of it and then using her private key (yes, private key) encrypts the hash and appends the resultant cipher data to the original message.</p><p>Once the resultant message reaches to Tom, he segregates the messages into the original message and cipher data. He decrypts the cipher data using Alice’s public key and extracts the hash out of it. He further hashes just the original message and compares both the hashes. If the hashes are same, it means that the message is not tampered with. It also establishes the fact that the message is originated by Alice as only she can encrypt the hash with her private key.</p><p>Digital signatures are used to sign transaction data by the owner of asset or crypto-currency like ether.</p><h3>Ether</h3><p>Ether is the currency of Ethereum. Every activity on Ethereum that modifies its state costs Ether as fee and miners who are successful in generating and writing a block in chain are also rewards Ether. Ether can easily be converted to dollars or other traditional currencies through Crypto-exchanges.</p><p>Ethereum has a metric system of denominations used as units of ether. The smallest denomination aka base unit of ether is called Wei. Below is a list of the named denominations and their value in Wei. This information is available at <a href="https://github.com/ethereum/web3.js/blob/0.15.0/lib/utils/utils.js#L40">https://github.com/ethereum/web3.js/blob/0.15.0/lib/utils/utils.js#L40</a></p><p>‘wei’ : ‘1’</p><p>‘kwei’: ‘1000’,</p><p>‘ada’: ‘1000’,</p><p>‘femtoether’: ‘1000’,</p><p>‘mwei’: ‘1000000’,</p><p>‘babbage’: ‘1000000’,</p><p>‘picoether’: ‘1000000’,</p><p>‘gwei’: ‘1000000000’,</p><p>‘shannon’: ‘1000000000’,</p><p>‘nanoether’: ‘1000000000’,</p><p>‘nano’: ‘1000000000’,</p><p>‘szabo’: ‘1000000000000’,</p><p>‘microether’: ‘1000000000000’,</p><p>‘micro’: ‘1000000000000’,</p><p>‘finney’: ‘1000000000000000’,</p><p>‘milliether’: ‘1000000000000000’,</p><p>‘milli’: ‘1000000000000000’,</p><p>‘ether’: ‘1000000000000000000’,</p><p>‘kether’: ‘1000000000000000000000’,</p><p>‘grand’: ‘1000000000000000000000’,</p><p>‘einstein’: ‘1000000000000000000000’,</p><p>‘mether’: ‘1000000000000000000000000’,</p><p>‘gether’: ‘1000000000000000000000000000’,</p><p>‘tether’: ‘1000000000000000000000000000000’</p><h3>Gas</h3><p>In last section, it was mentioned that Ether is paid as fees for any execution that changes state in Ethereum. Ether is traded on public exchanges and its price fluctuate daily. If Ether is used for paying fees, then the cost of using the same service could be very high on certain days and low on other days. People will wait for price of Ether to fall to execute their transactions. This is not ideal for a platform like Ethereum. Gas helps in alleviating this problem. Gas is the internal currency of Ethereum. The execution and resource utilization cost is predetermined in Ethereum in terms of Gas units. This is also known as Gas Cost. There is also Gas price that can be adjusted to lower price when price of Ether increases and higher price when price of Ether decreases. For example, to invoke a function in a contract that modifies a string will cost Gas which is pre-determined, and Users should pay in terms of Gas to ensure smooth execution of this transaction.</p><h3>Blockchain and Ethereum Architecture</h3><p>Blockchain is an architecture comprising of multiple components and what makes Blockchain unique is the way these components function and interact with each other. Some of the important Ethereum components are Ethereum virtual machine, Miner, Blocks, Transactions, Consensus algorithm, Accounts, Smart contracts, mining nodes, Ether and Gas. We are going to discuss each of this component in this chapter.</p><p>A Blockchain network consists of multiple nodes belonging to miners and some nodes that do not mine but helps in execution of smart contracts and transactions. These are known as Ethereum virtual machines. Each node is connected to other node on the network. These nodes use peer-to-peer protocol to talk to each other. They by default use 30303 port number to talk among themselves.</p><p>Each miner maintains an instance of ledger. Ledger contains all blocks in the chain. With multiple miners it is quite possible that each miner’s ledger instance might have different blocks than other. The miners synchronize their blocks on an on-going basis to ensure that every miner’s ledger instance is same as other.</p><p>Details about ledger, Blocks and transactions are discussed in detail in subsequent sections in this chapter.</p><p>The EVM also hosts Smart contracts. Smart contracts help in extending Ethereum by writing custom business functionality into it. These smart contracts can be executed as part of transaction and it follows the process of mining as discussed earlier.</p><p>A person having an account on network can send a message for transfer of Ether from his account to another or he can send a message to invoke a function within a contract. Ethereum do not distinguish them as far as transactions are considered. The transaction must be digitally signed an account holder’s private key. This is to ensure that identity of sender can be established while verifying the transaction and changing balances of multiple accounts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*_uh1XcTwy_YpSSppKUL2pw.png" /></figure><h3>How are Blocks related to each other?</h3><p>In Blockchain and Ethereum every block is related to another Block. There is a parent-child relationship between two blocks. There can be only one child to a parent and a child can have a single parent. This helps in forming a chain in Blockchain. Blocks are explained in later section in this chapter. In next image, three blocks are shown — Block 51, Block 52 and Block53. Block 51 is the parent of Block 52 and Block 52 is parent of Block 53. The relationship is established by storing the parent block’s hash in child’s block header. Block 52 stores the hash of Block 51 in its header and Block 53 stored the hash of Block 52 in its header. So, the question arises — Who is the parent of the first Block. Ethereum has a concept of Genesis Block also known as first block. This block is created automatically when the chain is first initiated. You can say that a chain is initiated with the first block known as Genesis block and the formation of this block is driven through Genesis.json file. Next chapter will show how to use Genesis.json file to create first block while initializing the Blockchain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*oekizHF7gqb_UY0bku4Q4w.png" /></figure><h3>How are transactions and Blocks related to each other?</h3><p>Now that we know that Blocks are related to each other, You would be interested in known how transactions are related to Blocks. Ethereum stores transactions within Blocks. Each block has a upper Gas limit and each transaction needs certain amount of Gas to be consumed as part of its execution. The cumulative gas from all transactions that are not yet written in ledger cannot surpass the Block Gas limit. This ensures that all transactions do not get stored within a single Block. As soon as the Gas limit is reached, other transaction is removed from block and mining begins thereafter.</p><p>The transactions are hashed and stored in the block. The hashes of two transactions are taken and hashes further to generate another hash. This process eventually provides a single hash from all transactions stored within the block. This hash is known as Transaction Merkle root hash and stored in Block’s header. A change in any of a transaction will result in change in its hash and eventually change in root transaction hash. It will have cumulative effect because the hash of the block will change, and the child block has to change his hash because it stores its parent hash. This helps in making transactions immutable. This is also shown in next image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*kvirlNVkM33jHGG84v-KPw.png" /></figure><h3>Nodes</h3><p>There are two types of nodes in Ethereum.</p><p>· Ethereum virtual machines and</p><p>· Mining Nodes</p><p>It is to be noted that this distinction is made to clarify concepts of Ethereum. In most scenarios’ there is no dedicated EVM machines instead all nodes acts as miner as well as EVM node.</p><h3>Ethereum virtual machines (EVM)</h3><p>Think of EVM as the execution runtime for Ethereum network. EVM’s are primarily responsible to provide a runtime that can execute code written in smart contracts. It can access accounts — contract and externally owned, its own storage data. It does not have access to ledger but has limited information about current transaction.</p><p>EVM are the execution component in Ethereum. The purpose of EVM is to execute the code in smart contract line by line. However, when a transaction is submitted, the transaction is not executed immediately instead is it pooled in a transaction pool. These transactions are not yet executed and not yet written to the Ethereum ledger. EVM nodes are similar to Mining nodes however they do not do mining.</p><h3>Mining Nodes</h3><p>A miner is responsible for writing transactions to the Ethereum chain. A miner job is very similar to that of an accountant. As an accountant is responsible for writing and maintain the ledger similarly, a Miner is solely responsible for writing transaction to Ethereum ledger. A miner is interested in writing transactions to ledger because of the reward associated with it. Miners get two types of reward — reward for writing a block to the chain and cumulative gas fees from all transactions in the block. There are generally many miners available within a blockchain network each trying and competing to write transactions. However only one miner can write the block to the ledger and rest will not able to write the current block and determination of a miner who will write the block happens using a challenge. The challange is given to every node and every miner tries to solve the puzzle using its compute power. The miner who solves the puzzle first write block containing transactions to ledger and also receiver 5 ether as reward. Every Mining node maintains its own instance of Ethereum ledger and the ledger is same ultimately across all miners. It is job of miners to ensure that their ledger is updated with latest blocks. There are three important functions performed by Miners or Mining Nodes.</p><p>· Mine or create a new block with transaction and write the same to Ethereum Ledger</p><p>· Advertise and send a newly mined block to other miners.</p><p>· To accept new blocks mined by other miners and keep its own ledger instance up-to-date</p><p>Mining Nodes refers the nodes that belong to Miners. These nodes are part of the same network where EVM is hosted. At some point of time, the miners would create a new Block, collect all transaction from transaction pool and adds them to the newly created block. Finally, this Block is added to the chain. There are additional concepts like consensus, solving of target puzzle before writing the block and will be explained in section “How mining works”.</p><h3>How does mining works</h3><p>The process of mining explained here is applicable to every miner on the network and every miner keeps executing tasks mentioned here regularly.</p><p>Miners are always looking forward to mine new block and are also listening actively to receive new blocks from other miners. As mentioned before, at some point, the miner collects all transactions from the transaction pool. This activity is done by all miners.</p><p>The miner constructs a new block and adds all transactions to it. Before adding these transaction, it will check if any of the transaction is not already written in a block that it might receive from other miners. If so, it will discard those transactions.</p><p>The miner will add his own coinbase transaction for getting rewards of mining the block.</p><p>The next task for miner is to generate the Block header and performs following task.</p><p>· The miner hashes all the transactions in the block, these hashes are further combined in pairs to generate a new hash. The process continues until there is just one hash for all transactions in the block. The hash is referred as Root transaction hash or Merkel Root transaction hash. This hash is added to the block header.</p><p>· The miner also identifies the hash of the previous block. The previous block will become parent to the current block and its hash will also be added to the block header.</p><p>· The miner in similar way calculates the State and Receipts transaction root hashes and add them to the block header.</p><p>· A nonce and timestamp is also added to the block header.</p><p>The mining process starts where the miner keeps changing the nonce value and try to find a hash that will satisfy as an answer to the given puzzle. It is to be kept in mind that everything mentioned here is executed by every miner in the network.</p><p>Eventually, one of the miner would be able to solve the puzzle and advertise the same to other miners in the network. The other miners would verify the answer and if found correct would further verify every transaction while accept the block and append the same to their ledger instance.</p><p>This entire process is also known as Proof of Work wherein a miner provides proof that is has worked on computing the final answer that could satisfy as solution to the puzzle. There are other algorithms like Proof of Stake and Proof of authority and they are not used or discussed in this book.</p><p>The block header and its content is shown in next image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*E3W76A6NNYiO7inwRPTHIg.png" /></figure><h3>Accounts</h3><p>Accounts are main building block for Ethereum ecosystem. It is the interaction between accounts that Ethereum wants to store as transaction in its ledger. Ethereum supports two types of accounts. Each account has a balance property that returns the current value stored in it.</p><h3>Externally owned accounts</h3><p>Externally owned accounts are accounts that are owned by people on Ethereum. Accounts are not referred by names in Ethereum. When an externally owned account is created on Ethereum by an individual, a public-private key is generated. The private key is kept safe with the individual while the public key becomes the identity of this externally owned account. This public key is generally of 256 characters however Ethereum uses the first 160 characters to represent the identity of an account.</p><p>If Bob creates an account on Ethereum network — whether private or public, he will have his private key available to himself while his first 160 characters of public key will become his identity. Other accounts on the network can then send ether or other crypto-currencies based on ether to this account.</p><p>An account on Ethereum looks like the one shown here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*OFHJroCmTHaR8kGDhHlmuA.png" /></figure><p>An externally owned account can hold Ether in its balance and do not have any code associated with them. This of these accounts like a Bank account. They can execute transactions with other externally owned accounts and they can also execute transactions by invoking functions within contracts.</p><h3>Contracts Accounts</h3><p>Contracts accounts are very similar to externally owned accounts. They are identified using their public address. They do not have any private key. They can hold ether similar to externally owned accounts however they contain code — code for smart contracts consisting of functions are state variables.</p><h3>Transaction</h3><p>A transaction is an agreement between a buyer and seller, a supplier and a consumer or a provider and a consumer that there would be exchange of assets, products or services in lieu of currency, crypto-currency or some other asset either in present or in future. Ethereum helps in executing transaction. There are four types of transaction that can be executed in Ethereum.</p><p>1. Transfer of Ether from one account to another. The accounts can be externally owned accounts or contract account. Following are the possible cases</p><p>a. An externally owned account sending ether to another externally owned account in a transaction.</p><p>b. An externally owned account sending ether to a contract account in a transaction.</p><p>c. A contract account sending ether to another contract account in a transaction.</p><p>d. A contract account sending ether to an externally owned account in a transaction</p><p>2. Deployment of Smart contract — An externally owned account can deploy a contract using a transaction in Ethereum virtual machine.</p><p>3. Using or invoking a function within a contract — Executing a function in a contract that changes state are considered as transactions in Ethereum. If executing a function does not change state, it does not require a transaction</p><p>A transaction has some important properties related to it.</p><p><strong>From</strong> Account property denotes the account that is originating the transaction and represents an account who is ready to send some gas or ether. We will consider concepts related to Gas and Ether later section in this chapter. From account can be externally owned or a contract account.</p><p><strong>To</strong> account property refers to an account that is receiving ethers or benefits in lieu of an exchange. In case of transaction related to deployment of contract, the To field is empty. It can be externally owned or a contract account.</p><p><strong>Value</strong> refers to the amount of ether that is transferred from one account to another.</p><p><strong>Input</strong> refers to the compiled contract bytecode and is used during contract deployment in EVM. It is also used for storing data related to smart contract function calls along with its parameters.</p><p>A typical transaction in Ethereum where a contract function is invoked is shown here. Notice the input field containing the function call to contract along with its parameters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*znTEZewEzhpt5VdMFn5qXg.png" /></figure><p><strong>Blockhash</strong> refers to the hash of Block to which this transaction belongs to.</p><p><strong>BlockNumber</strong> is the block in which this transaction belongs to.</p><p><strong>Gas</strong> refers to amount of gas supplied by sender which executing this transaction</p><p><strong>GasPrice</strong> refers to the price per gas the sender was willing to pay in Wei ( Wei is explained in section related to Ether). Total Gas is computed at Gas units * Gas price</p><p><strong>Hash</strong> refers to the hash of transaction</p><p><strong>Nonce</strong> refers to number of transactions made by the sender prior to current transaction.</p><p><strong>TransactionIndex</strong> refers to the serial number of current transaction in block</p><p><strong>Value</strong> refers to amount of ether transferred in Wei</p><p><strong>V, R and S</strong> relates to digital signature and signing of transaction.</p><p>A typical transaction in Ethereum where an externally owned account sends some ether to another externally owned account is shown here. Notice the input field is not used here. Since 2 ethers were send in transaction, the value field is showing the value accordingly in Wei.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*fX828QJbZZUFaEPcw2_ALQ.png" /></figure><p>One of the way to send ether from an externally owned account to another externally owned account is shown here using web3 which will be covered extensively in this book in rest of the chapters.</p><p>web.eth.sendTransaction({from: web.eth.accounts[0], to: “0x9d2a327b320da739ed6b0da33c3809946cc8cf6a”, value: web.toWei(2, ‘ether’)})</p><p>A typical transaction in Ethereum where a contract is deployed is shown here.</p><p>Notice the input field containing the bytecode of contract.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*YUrpaPeMbrfhdUW_GmUA7w.png" /></figure><h3>Block</h3><p>Block is an important concept in Ethereum. Block are containers for transaction. A block contains multiple transactions. Each block has different number of transactions based on Gas limit. Gas limit will be explained in detail in later sections. The blocks are chained together to form blockchain. Each Block has a parent and it stored the hash of parent block in its header. Only the first Block known as Genesis block does not have a parent.</p><p>A typical Block data in Ethereum is shown here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*IAjANR4IfTJTgGaF8mj3Hg.png" /></figure><p>The <strong>Difficulty</strong> property determines the complexity of the puzzle/challenge given to miners for this block.</p><p><strong>GasLimit</strong> determines the maximum gas allowed. This helps in determining how many transaction can be part of the block.</p><p><strong>GasUsed</strong> refers to the actual gas used for this block for executing all transactions in it.</p><p><strong>Hash</strong> refers to the hash of the block.</p><p><strong>Nonce</strong> refers to the number that helping in solving the challenge.</p><p><strong>Miner</strong> property is the account identifier of miner also known as coinbase or Etherbase</p><p><strong>Number</strong> is the sequential number of this block on the chain</p><p><strong>ParentHash</strong> refers to parents blocks hash.</p><p><strong>ReceiptsRoot, StateRoot and transactionRoot</strong> refers to Merkel trees discussed during mining process.</p><p><strong>Transactions</strong> refers to array of transactions that are part of this block.</p><p><strong>TotalDifficulty</strong> refers to total difficulty of the chain until this block</p><h3>An end to end Transaction</h3><p>Armed with the understanding of foundational concepts of Blockchain and Ethereum, it time to see a complete end to end transaction and how it flows through multiple components and get stored in the ledger.</p><p>In this example, Sam wants to send few dollars to Mark. Sam generates a transaction message as shown before containing From, To, Value fields and sends it across to Ethereum network. The transaction is not written to the ledger immediately and instead it is placed in a transaction pool.</p><p>The mining node creates a New Block and takes all transactions from the pool honouring the Gas limit criteria and adds them to the block. This activity is done by all miners on the network. Sam’s transaction will also be part of this process.</p><p>The miners compete trying to solve the challenge thrown to them. The winner is a miner who can solve the challenge first. After a period (10 seconds in Ethereum) one of the miner will advertise that he has found solution to the challenge and that he is the winner and should write the block to the chain. The winner sends the challenge solution along with the new Block to all other miners. Rest of the miners validates and verifies the solution and once satisfied with the solution, they accept the new Block containing Sam’s transaction to append in their instance of ledger. This generates a new block on the chain that is persisted across time and space. During this time the accounts of both the parties are updated with new balance. Finally, the Block is replicate across every node in the network.</p><p>The same process is also shown in next image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*zBpCXbdcEXOKcCvP0hE9ZQ.png" /></figure><h3>What is a contract</h3><p>A contract is a legal document that binds two or more parties who agrees to execute a transaction immediately or in future. Since Contracts are legal documents, they are enforced and implemented by law. Examples of contract are an individual getting into a contract with Insurance company for covering his health or an individual buying a piece of land from another individual or a company selling its shares to another company.</p><h3>What is a smart contract</h3><p>A smart contract is a contract implemented, deployed and executed within Ethereum environment. Smart contracts are digitization of the legal contracts. Smart contracts are deployed, stored and executed within the Ethereum Virtual machine. Smart contracts can store data. The data stored can be used to record information, fact, associations, balances and any other information needed to implement logic for real world contracts. Smart contracts are very similar to Object oriented classes. A smart contract can call another smart contract just like an Object-oriented object to create and use objects of another class. Think of smart contract as a small program consisting of functions. You can create an instance of the contract and invoke functions to view and update contract data along with execution of some logic</p><h3>How to write Smart Contracts</h3><p>There are multiple smart Contract authoring tools including Visual Studio. However, the easiest and fastest way to develop smart contracts is to use a browser based tool known as Remix. Remix is available at <a href="http://remix.ethereum.org">http://remix.ethereum.org</a>. Remix is a new name and was earlier known as browser solidity. Remix provides a rich integrated development environment on browser for authoring, developing, deployment and troubleshooting of contracts written using solidity language. All Contract management related activities like authoring, deployment and troubleshooting can be performed from the same environment without moving to other windows or tabs.</p><p>Since Remix is on internet and not everybody would be comfortable to author their smart contracts, Remix is an open source tool that can be downloaded from GitHub at <a href="https://github.com/ethereum/browser-solidity">https://github.com/ethereum/browser-solidity</a> and compiled to run a private version sing browser. Another advantage of running remix locally is that it can connect to local private chain networks directly otherwise users will first have to author the contact at online Remix and then copy the same in a file and compile and deploy manually to private network.</p><p>Navigate to remix.ethereum.org and the site will open in browser with a default contract as shown in next figure. This contract can be deleted. Delete this contract as we won’t be using it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*Es1WqA4goOKJtxq4eOvGSQ.png" /></figure><p>The first thing we need to do is to create a new contract by selecting “+” from Remix left menu bar. Then provide a name for new solidity file that has an extension .sol. Name the contract “HelloWorld” and click OK to continue. This will create a blank contract.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*nHGGHikkgJd2olrnNeMPyw.png" /></figure><p>Type the following code in the empty authoring pane to create your first contract. This contract will be explained in detail in third chapter. For now, it is sufficient to understand that contract is created using contract keyword, you can declare global state variables and functions and contracts are saved with .sol file extension. The HelloWorld contracts returns “HelloWorld” string when GetHelloWorld function is called.</p><p><em>pragma solidity ^0.4.18;</em></p><p><em>contract HelloWorld</em></p><p><em>{</em></p><p><em>string private stateVariable = “Hello World”;</em></p><p><em>function GetHelloWorld() public view returns (string){</em></p><p><em>return stateVariable;</em></p><p><em>}</em></p><p><em>}</em></p><p>Look at the action window to the right of Remix. It has got several tabs — Compile, Run, Settings, debugger, analysis and support. The action tabs helps in compiling, deploying, troubleshooting and invoking contracts. The compile tab compiles the contract into bytecode — code that is understood by Ethereum. It displays warnings and errors as you author and edit the contract. These warnings and errors are to be taken seriously and they really help in creating robust contracts.</p><p>Run tab is the place where you would spend maximum time apart from writing the contract. Remix comes bundled with Ethereum runtime within the browser. Run tab allows to deploy the contract to this runtime using “Javascript VM” environment option. “Injected Web3” is used along with tools like Mist and MetaMask which will be covered in next chapter and “Web3 provider” can be used when using Remix in a local environment connecting to private network. In our case for this chapter, the default, “Javascript VM” is sufficient. Rest of the options will be discussed later in chapter 3. However the important action is deployment of contract and that can be done using the “Create” button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*XbGS_XCtx7Is0P4vgiUc8g.png" /></figure><p>Click on create button to deploy the contract to browser Ethereum runtime and this will list all the functions available within the contract below the create button. Since, we only had a single function GetHelloWorld, the same is displayed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*LQHOlDNeHBhqmSadnWi_Iw.png" /></figure><p>Click on GetHelloWorld button to invoke and execute the function. The lower pane of Remix will show the results of execution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*OnTNB4QccTowK54lPq4wfg.png" /></figure><p>Congratulations, you have created, deployed and also executed a function on your first contract. The code for HelloWorld contract is accompanied with this chapter and can be used in Remix if you are not interested in typing the contract.</p><h3>How the contracts are deployed</h3><p>Remix makes deployment of contracts a breeze however it is performing a lot of steps behind the scenes. It is always useful to understand the process of deploying contracts to have more finer control over deployment process.</p><p>The first step is compilation of contracts. The compilation is done using solidity compiler. Next chapter will show how to download and compile a contract using solidity compiler.</p><p>The compiler generates two major artifacts</p><p><strong>· ABI definition and</strong></p><p><strong>· Contracts byte code</strong></p><p>Think of ABI (application binary interface) as an interface consisting of all external and public function declarations along with their parameters and return types. The ABI defines the contract and any caller wanting to invoke any contract function can use the ABI to do so.</p><p>The bytecode is what represents the contract and is deployed in Ethereum ecosystem. The bytecode is needed during deployment and ABI is needed for invoking functions in contract.</p><p>A new instance of contract is created using the ABI definition.</p><p>A new transaction is created that utilizes the newly instance of contract passing in the contract bytecode and appropriate quantity of gas for execution of transaction. After the transaction is mined, the contract is available at an address determined by Ethereum.</p><p>Now, that contract is deployed within the Ethereum virtual machine, its time to invoke the contract.</p><p>Using the newly generated address, an instance of contracts can be created and its functions can be invoked.</p><h3>Summary</h3><p>This was the first chapter of the book and we have already covered lot of ground. This chapter was an introduction to Blockchain and more specific to Ethereum. Having a good understanding of the big picture about how Blockchain and Ethereum works will go a long way in understanding and Writing robust, secure and cost effective smart contracts using solidity. This chapter covered the basics of blockchain, explained what is Blockchain, why is Blockchain important and how does it help in building decentralized, distributed applications. The architecture of Ethereum was discussed in brief along with some of the important concepts like Transactions, Blocks, Gas, Ether, Accounts, cryptography and Mining. This chapter also touched briefly on the topic of Smart contracts, using Remix to author smart contracts and how to execute them using Remix itself. I’ve kept this chapter brief since the rest of the book will explain these concepts further and allow you to quickly develop Solidity based smart contracts. You’ll notice that this chapter does not contain any mention of Ethereum tools and utilities. This is what we will cover in the next chapter, by diving straight in and installing Ethereum and its toolset.</p><blockquote>Join Coinmonks<a href="https://t.me/coincodecap"> Telegram Channel</a> and<a href="https://www.youtube.com/c/coinmonks/videos"> Youtube Channel</a> get daily <a href="http://coincodecap.com/">Crypto News</a></blockquote><h4>Also, Read</h4><ul><li><a href="https://medium.com/coinmonks/top-10-crypto-copy-trading-platforms-for-beginners-d0c37c7d698c">Copy Trading</a> | <a href="https://medium.com/coinmonks/crypto-tax-software-ed4b4810e338">Crypto Tax Software</a></li><li><a href="https://coincodecap.com/grid-trading">Grid Trading</a> | <a href="https://medium.com/coinmonks/the-best-cryptocurrency-hardware-wallets-of-2020-e28b1c124069">Crypto Hardware Wallet</a></li><li><a href="http://Top 4 Telegram Channels for Crypto Traders">Crypto Telegram Signals</a> | <a href="https://medium.com/coinmonks/crypto-trading-bot-c2ffce8acb2a">Crypto Trading Bot</a></li><li><a href="https://coincodecap.com/koinly-review">Koinly Review</a> |<a href="https://coincodecap.com/binaryx-review"> Binaryx Review</a> |<a href="https://coincodecap.com/hodlnaut-vs-cakedefi-vs-celsius"> Hodlnaut vs CakeDefi</a></li><li><a href="https://coincodecap.com/bybit-binance-moonxbt">MoonXBT vs Bybit vs Binance</a> |<a href="https://medium.com/coinmonks/hardware-wallets-dfa1211730c6">Hardware Wallets</a></li><li><a href="https://coincodecap.com/huobi-trading-bot">Huobi Trading Bot</a> |<a href="https://coincodecap.com/buy-ada-cardano">How to buy ADA</a> |<a href="https://coincodecap.com/geco-one-review">Geco.One Review</a></li><li><a href="https://coincodecap.com/binance-vs-bitstamp">Binance vs Bitstamp</a> |<a href="https://coincodecap.com/bitpanda-coinbase-coinsbit"> Bitpanda vs Coinbase vs Coinsbit</a></li><li><a href="https://coincodecap.com/buy-ripple-india">How to buy Ripple (XRP)</a> |<a href="https://coincodecap.com/crypto-exchange-africa"> Best Crypto Exchanges in Africa</a></li><li><a href="https://medium.com/coinmonks/crypto-exchange-dd2f9d6f3769">Best Crypto Exchange</a> | <a href="https://medium.com/coinmonks/bitcoin-exchange-in-india-7f1fe79715c9">Best Crypto Exchange in India</a></li><li><a href="https://medium.com/coinmonks/best-crypto-apis-for-developers-5efe3a597a9f">Best Crypto APIs</a> for Developers</li><li>Best <a href="https://medium.com/coinmonks/top-5-crypto-lending-platforms-in-2020-that-you-need-to-know-a1b675cec3fa">Crypto Lending Platform</a></li><li>An ultimate guide to <a href="https://medium.com/coinmonks/leveraged-token-3f5257808b22">Leveraged Token</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63dfaff08a11" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/https-medium-com-ritesh-modi-solidity-chapter1-63dfaff08a11">Introduction to Blockchain, Ethereum and Smart Contracts — Chapter 1</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Want to learn Solidity from ground up??]]></title>
            <link>https://medium.com/coinmonks/https-medium-com-ritesh-modi-solidity-5d8d2a30e778?source=rss-95e9b4985f23------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d8d2a30e778</guid>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[Ritesh Modi]]></dc:creator>
            <pubDate>Wed, 16 May 2018 05:59:32 GMT</pubDate>
            <atom:updated>2018-05-16T18:21:23.485Z</atom:updated>
            <content:encoded><![CDATA[<p>Well, you have landed at the right place !!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*KwQtjLdt5WmcCXLBxIAECQ.png" /></figure><p>I have been working with Blockchain especially Ethereum, Smart Contracts and Solidity for quite sometime now. As being active member of Blockchain communities, I also conducted numerous meetup on these topics. As part of this exercise and also while mentoring Blockchain based start-ups, I came across many individuals who wanted to learn Solidity as a language from start. According to them, there are text available on internet on Solidity but they do not have complete information about the language.</p><p>They felt they neither comfortable not confident writing smart contracts using Solidity.</p><p>I also saw multiple implementation of smart contracts on Solidity that were not built using the right practices. They also lacked constructs that would optimize gas usage and make robust smart contracts. We all know how bugs can make smart contracts vulnerable to attacks and also migrating data between contracts is a nightmare.</p><p>In this endeavor, I have authored one of the first book exclusively on Solidity “<strong>Solidity programming essentials</strong>” for developers and architects that are or want to build smart contracts using Solidity.</p><p><strong>This book will teach you,</strong></p><ul><li>The basics and foundation concepts of Solidity and Ethereum</li><li>Explore the Solidity language and its uniqueness in depth</li><li>Create new accounts and submit transactions to blockchain</li><li>Get to know the complete language in detail to write smart contracts</li><li>Learn about major tools to develop and deploy smart contracts</li><li>Write defensive code using exception handling and error checking</li><li>Understand Truffle basics and the debugging process</li></ul><p><strong>The book has been divided into following chapters.</strong></p><ol><li>Introduction to Blockchain, Ethereum, and Smart Contracts</li><li>Installing Ethereum and Solidity</li><li>Introducing Solidity</li><li>Global Variables and Functions</li><li>Expressions and Control Structures</li><li>Writing Smart Contracts</li><li>Functions, Modifiers, and Fallbacks</li><li>Exceptions, Events, and Logging</li><li>Truffle Basics and Unit Testing</li><li>Debugging Contracts</li></ol><p>The book is available globally and can be bought from amazon @ <a href="https://www.amazon.com/Solidity-Programming-Essentials-beginners-blockchain/dp/1788831381/">https://www.amazon.com/Solidity-Programming-Essentials-beginners-blockchain/dp/1788831381/</a></p><p>I look forward hearing from you and your journey learning Solidity and implementing smart contracts!</p><p>I will be posting the first chapter of the book as well in my next post!</p><p>Stay tuned and happy learning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d8d2a30e778" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/https-medium-com-ritesh-modi-solidity-5d8d2a30e778">Want to learn Solidity from ground up??</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>