Skip to main content

Store Data in to Micro-Services Static class using c# dot net core (Key Based API for Reduce Database hit)

1*KH-i7gZC9UEUELeMhnAugg.jpeg (1024×768)
Find Code From Here : Code

Testing : 1. 1st Time Entry with Null key value and Adding New Value into Class


Testing : 2 . 2nd Time Entry with unique key value and updating existing entry into Class


Testing : 3. Same Time Another Hit Came From different User for for update Data 



Testing 4: If Step is 4 then we are inserting data into our database and Deleting data from class


using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace AppForStaticCls.Controllers
{
    [Route("api/[controller]")]
    public class MutiplePostController : Controller
    {
        // GET: api/<controller>
        [HttpGet]
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }


        // POST api/<controller>
        [HttpPost]
        public List<TestDataRes> Post(string key, string step, string name, string address, string country)
        {
            string newKey = "";
            List<TestDataRes> testDataResList = new List<TestDataRes>();
            if (TestData.count == 0)
            {
                newKey = Guid.NewGuid().ToString();
                DataColumn nme = new DataColumn("name");
                DataColumn adrs = new DataColumn("address");
                DataColumn cntry = new DataColumn("country");
                DataColumn createdDate = new DataColumn("dateTime");
                DataColumn dtKey = new DataColumn("key");

                TestData.Dt = new DataTable();
                TestData.Dt.Columns.Add(nme);
                TestData.Dt.Columns.Add(adrs);
                TestData.Dt.Columns.Add(cntry);
                TestData.Dt.Columns.Add(createdDate);

                TestData.Dt.Columns.Add(dtKey);
                TestData.count = TestData.count + 1;

                DataRow row = TestData.Dt.NewRow();
                row["key"] = newKey;
                row["dateTime"] = DateTime.Now;
                TestData.Dt.Rows.Add(row);
                UpdateData(newKey, name, address, country);
            }
            else
            {
                if (!UpdateData(key, name, address, country))
                {
                    newKey = Guid.NewGuid().ToString();
                    DataRow row = TestData.Dt.NewRow();
                    row["dateTime"] = DateTime.Now;
                    row["key"] = newKey;
                    TestData.Dt.Rows.Add(row);
                    UpdateData(newKey, name, address, country);
                }
            }
            if (step == "4")
            {
                //will call database
                IEnumerable<DataRow> rows = TestData.Dt.Rows.Cast<DataRow>().Where(r => r["key"].ToString() == key);
                rows.ToList().ForEach(r => r.Delete());
            }
            if (key != null)
            {
                testDataResList = AddData(key);
            }
            else
            {
                testDataResList = AddData(newKey);
            }
            Flush();
            return testDataResList;
        }


        public bool Flush()
        {
            IEnumerable<DataRow> rows = TestData.Dt.Rows.Cast<DataRow>().Where(r => Convert.ToDateTime(r["dateTime"]) <= DateTime.Now.AddMinutes(-30));
            rows.ToList().ForEach(r => r.Delete());
            return true;
        }

        public List<TestDataRes> AddData(string key)
        {
            List<TestDataRes> testDataResList = new List<TestDataRes>();

            foreach (DataRow item in TestData.Dt.Rows.Cast<DataRow>().Where(r => r["key"].ToString() == key))
            {
                testDataResList.Add(new TestDataRes { name = item["name"].ToString(), address = item["address"].ToString(), country = item["country"].ToString(), key = key });
            }
            return testDataResList;
        }

        public bool UpdateData(string Key, string name, string address, string country)
        {
            if (!string.IsNullOrEmpty(Key))
            {
                IEnumerable<DataRow> rows = TestData.Dt.Rows.Cast<DataRow>().Where(r => r["key"].ToString() == Key);

                if (!string.IsNullOrEmpty(name))
                {
                    rows.ToList().ForEach(r => r.SetField("name", name));
                }
                if (!string.IsNullOrEmpty(address))
                {
                    rows.ToList().ForEach(r => r.SetField("address", address));
                }
                if (!string.IsNullOrEmpty(country))
                {
                    rows.ToList().ForEach(r => r.SetField("country", country));
                }
                return true;
            }
            else
            {
                return false;
            }
        }

    }



    public static class TestData
    {
        public static DataTable Dt { get; set; }
        public static int count { get; set; }
    }
    public class TestDataRes
    {
        public string name { get; set; }
        public string address { get; set; }
        public string country { get; set; }
        public string key { get; set; }

    }
}

Comments

Popular posts from this blog

MVC Interview Questions

MVC Interview Questions What is MVC Application life cycle ? What is default route in MVC? What is Output Caching ? What are Route Constraints in MVC? What are the Benefits of Area in MVC? How do you implement Forms authentication in MVC? What are the Main Razor Syntax Rules? Define attribute based routing in MVC? What are HTML helpers in MVC? What does the MVC pattern define with 3 logical layers? What are the advantages of MVC? List the various return types of a controller action method. What are the types of filters? What are the Filters in MVC? What are the three segments for routing important? What is Route in MVC? what is the difference between ViewData and ViewBag? attribute based routing in MVC? What is GET and POST Actions Types? What is MVC (Model view controller)? What is Validation Summary in MVC? What’s new in the latest version of MVC? How to render html in Asp.net MVC view? Explain the concept of MVC Scaffolding? What is Bundling and Mini...

Azure Service Bus Vs Azure Web Job

MENU Home SUBSCRIBE Today, we will be talking about Azure service bus and how to use them with Webjobs. Azure Service Bus  is a messaging infrastructure that sits between applications allowing them to exchange messages for improved scale and resiliency. It offers the following capabilities: Queues: offers simple first in, first out guaranteed message delivery. When to use Azure Service Bus? Service Bus queues are a general-purpose technology that can be used for a wide variety of scenarios: Communication between web and worker roles in a multi-tier Azure application Communication between on-premises apps and Azure hosted apps in a hybrid solution Communication between components of a distributed application running on-premises in different organizations or departments of an organization There are also Topics and Relay capabiliteis but we will talk about them in the future. A figure that illustrates how Azure Service Bus works. There is a sender who send a mes...

Angular Step By Step Installation Process

# Angular Step By Step  Hello Techies,        In this post i am going to guide you to install Angular and create and run your first app. Please follow bellow steps.. Step 1 (Node NPM Installation) Node Js ( NPM)  should be installed on system. So for installation of Node Js follow bellow steps. Open  https://nodejs.org/en  .  Download stable Version (LTS) of Node js. After complete the installation open CMD and check the version. Step : 2 (Install Angular by NPM) Type " npm install -g @angular/cli "  2.  Select folder where you are going to create Angular Project.  3. Type ng new 'your app-name' EX:  ng new my-dream-app And Relax it will take some couple of minute to create app , because its downloading all the package from server by npm in you local system. Type : " cd my-dream-app " to select project which is created.  Now Type " ng serve " to run the project...