Written by

Ravishankar

Share

  

Category

see all categories
intranet as a service

How To Store Data In Azure Table Storage Using Rest API in ASP.NET Core - Part Two

n this article, we are going to see how to store data in Azure tables using Rest API in ASP.NET core. The ASP.NET core is an open source web framework which can be run on MAC, Windows, and Linux. Azure Tables is a NoSQL cloud database and it is not a relational database. It can store, just without any other kind of relations like foreign keys. Read the previous part of the article before continuing with this one: How To Access Data From Azure Table Storage Using Rest API in ASP.NET Core - Part One

Adding a new MVC Razor View: 

Open the Solution Explorer. 

Solution Explorer-1

 

Open Views/Home  and right click Home -> Add -> View  

Open the Add.cshtml file and replace the code given below it. Here we use strongly typed synchronous forms because it is easy to maintain the forms in cshtml. HTML helpers like (@Html.BeginForm(..)) create the <form> tag when rendering the web page and (@Html.Textbox(..)) create the <input> tag when rendering the webpage.

@model DemoAzureTableRest.Models.MaterialUsageDetails

<div class="container">

    <h2>Add New Device</h2>

    @using (Html.BeginForm("Add", "Home", FormMethod.Post))

    {

        <table>

            <tr>

                <th colspan="2" align="center"></th>

            </tr>

            <tr>

                <td>Device ID: </td>

                <td>

                    @Html.TextBoxFor(m => m.deviceId)

                </td>

            </tr>

            <tr>

                <td>Furnace: </td>

                <td>

                    @Html.TextBoxFor(m => m.furnace)

                </td>

            </tr>

            <tr>

                <td>Material: </td>

                <td>

                    @Html.TextBoxFor(m => m.material)

                </td>

            </tr>

            <tr>

                <td>Weight: </td>

                <td>

                    @Html.TextBoxFor(m => m.weight)

                </td>

            </tr>

            <tr>

                <td></td>

                <td><input type="submit" value="Submit" /></td>

            </tr>

        </table>

    }

</div>

@if (ViewBag.Message != null)

{

    <script type="text/javascript">

            window.onload = function () {

                alert("@ViewBag.Message");

            };

    </script>

}

<style>

    table {

        border-spacing: 8px 2px;

    }

    td {

        padding: 6px;

    }

</style>

Now open the Controllers/HomeController.cs  and replace the code given below it. Here we will get materialUsageDetails model data and pass it to the AzureTable helper class. Azure Table InsertEntity Method requires storage name, storage key, Table name and model data so we need to pass the following data while calling the InsertEntity method.

 public IActionResult Add(MaterialUsageDetails materialUsageDetails)

        {

            string response ="";

            if (materialUsageDetails.deviceId != null)

            {

                materialUsageDetails.PartitionKey = materialUsageDetails.deviceId;

                materialUsageDetails.RowKey = materialUsageDetails.furnace;

                response = AzureTables.InsertEntity(StorageName, StorageKey, TableName, JsonConvert.SerializeObject(materialUsageDetails));

            }

            if (response == null)

            {

                ViewBag.Message = "Saved Successfully";

            }

            return View(materialUsageDetails);

        }

 And open the Helpers/AzureTables.cs file and add below code in it. Here we will create a new entity in Azure Tables using HttpWebRequest. To create the web request we need the URI and Headers, the required headeris given in getRequestHeader() method, the required parameters are HTTP method name ("POST"), request(Http Request), Storage account(storage account name), access key(storage secret key), resource(table name), jsonData.length(model data length). To write a model JSON data into the request body we use StreamWriter class and execute the request using GetRequestStream().

 public static string InsertEntity(string storageAccount, string accessKey, string tableName, string jsonData)

        {

            string jsonResponse = "";

            string host = string.Format(@"https://{0}.table.core.windows.net/", storageAccount);

            string resource = string.Format(@"{0}", tableName);

            string uri = host + resource;

            // Web request

            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);

            request = getRequestHeaders("POST", request, storageAccount, accessKey, resource, jsonData.Length);

            // Write Entity's JSON data into the request body

            using (var streamWriter = new StreamWriter(request.GetRequestStream()))

            {

                streamWriter.Write(jsonData);

                streamWriter.Flush();

                streamWriter.Close();

            }

            // Execute the request

            try

            {

                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())

                {

                    using (System.IO.StreamReader r = new System.IO.StreamReader(response.GetResponseStream()))

                    {

                        jsonResponse = r.ReadToEnd();

                        // return (int)response.StatusCode;

                    }

                }

            }

            catch (WebException ex)

            {

                // get the message from the exception response

                using (System.IO.StreamReader sr = new System.IO.StreamReader(ex.Response.GetResponseStream()))

                {

                    jsonResponse = sr.ReadToEnd();

                    // Log res if required

                }

                // return (int)ex.Status;

            }

            return jsonResponse;

        }

That's it. Now run the web application , go to Debug menu and click on Start without Debugging , or press F5. To add new form change the url to https://localhost:44392/Home/Add

Now fill the form and click submit button.

We hope you have learned how to store data in Azure table storage using Rest API in an ASP.NET core web application. Feel free to fill up the comment box below if you need any assistance.