6 Replies - 366 Views - Last Post: 13 May 2021 - 07:45 AM Rate Topic: -----

#1 Exceedinglife   User is offline

  • D.I.C Regular

Reputation: 7
  • View blog
  • Posts: 250
  • Joined: 01-July 12

.Net Core Create Object to hold data in controller, like a global vari

Posted 09 May 2021 - 04:24 PM

Hello All,
In my WPF app I would normally create a global variable at the top of a class to hold data that is coming in on my websocket.
What should I do for a .Net Core Application? Web Application.
I would like to store all my data in a object that I can access it throughout my controller.
Currently when I try this the object gets set to null each time I call it.
What is the best way to do something like this? I was looking at a memorycache I think it was called. Maybe something like that or what are my options?
    public class HomeController : Controller
    {
        public List<SocketResult> lstTrades { get; set; } = new List<SocketResult>();
        
public HomeController(ILogger<HomeController> logger, IHttpClientFactory httpClient, IHttpContextAccessor httpContextAccessor, IMarketFeed marketFeed, IBinanceSocketClient binanceSocketClient)
        {
            _logger = logger;
            _httpClient = httpClient;
            _httpContext = httpContextAccessor;
            _marketFeed = marketFeed;
            _binanceSocketClient = binanceSocketClient;
            
        }

[HttpPost]
        public async Task<IActionResult> AddDataToMemory(string model)
        {
            if (model != null)
            {
                lstTrades.Add(new SocketResult() {Price = model.p });
            }

            return NoContent();
        }




Is This A Good Question/Topic? 0
  • +

Replies To: .Net Core Create Object to hold data in controller, like a global vari

#2 Skydiver   User is offline

  • Code herder
  • member icon

Reputation: 7788
  • View blog
  • Posts: 26,018
  • Joined: 05-May 12

Re: .Net Core Create Object to hold data in controller, like a global vari

Posted 09 May 2021 - 04:47 PM

That is because o f the object lifetime rules surrounding the ASP.NET web request handling. Look at the dependency injection and inversion of control containers provided by .NET Core to give more long lived objects.
Was This Post Helpful? 0
  • +
  • -

#3 modi123_1   User is online

  • Suitor #2
  • member icon



Reputation: 16253
  • View blog
  • Posts: 64,719
  • Joined: 12-June 08

Re: .Net Core Create Object to hold data in controller, like a global vari

Posted 09 May 2021 - 05:11 PM

I do believe you need to add in the using 'websockets' middleware to accomplish this.

https://docs.microso...=aspnetcore-5.0

https://radu-matei.c...ets-middleware/
Was This Post Helpful? 0
  • +
  • -

#4 Sheepings   User is offline

  • D.I.C Lover
  • member icon

Reputation: 246
  • View blog
  • Posts: 1,340
  • Joined: 05-December 13

Re: .Net Core Create Object to hold data in controller, like a global vari

Posted 10 May 2021 - 08:21 AM

View PostExceedinglife, on 09 May 2021 - 11:24 PM, said:

What should I do for a .Net Core Application? Web Application.

What is the best way to do something like this?


Personally, I wouldn't recommend .NetCore at all. I think its over-rated as hell, broken, and awfully troublesome. And I can say that after writing a number of apps in C# using .NetFrameworks/.NetCore. You will have nothing but issues going this route using Microsoft technologies.

I rewrote my own API in Python, and I am still working on it, and when I finish, I will port my other apps into Python too. Anyone who has programmed as much as I have committed to building apps in C# with .NetCore; would also be advising you to jump ship before you get too deep into your project and regret it later on.

Most of the Project solutions provided by Microsoft each come with their own set of problems. I know this first-hand. Some project types have problems with DI (dependency injection), Cookies not setting in .NetCore "apparently" due to a "Chrome bug". (I blame Microsoft personally, others may blame the tech war going on between the two tech giants.) This is just one example of what I can provide out of a multitude of issues you will experience.

And what you will often see a lot of; is people pointing you to documentations which do not bloody work. (I've often directed people to the docs, only to later test and find the docs to be misleading or inaccurate.) I've proven this to Skydiver before on many of occasion. (off and on other boards.) And we've seen that the documentation isn't always workable, as different project solutions come with their own set of issues.

Albeit. C# is considered to be a enterprise type language, .NetFrameworks/Core is not near as good as its promoted to be. It's also riddled with bloat-code, and often uses irrelevant classes, clunky methods for things that are very easily done with less code in other platforms/languages. I'll stop here, as I literally can go on and on addressing issues of why you shouldn't be using Microsoft projects to build web apps. I think the main reason people use Microsoft based web projects; is mainly because of the simplicity to learning the language and easily adapting.

While this doesn't answer your questions above, It does give warning for the types of issues you will face along the way such as dependency injection not working.

Edited/Added clarity & typo fixed.

This post has been edited by Sheepings: 10 May 2021 - 03:50 PM

Was This Post Helpful? 0
  • +
  • -

#5 Exceedinglife   User is offline

  • D.I.C Regular

Reputation: 7
  • View blog
  • Posts: 250
  • Joined: 01-July 12

Re: .Net Core Create Object to hold data in controller, like a global vari

Posted 12 May 2021 - 07:01 PM

lol
I may do some research on some other languages in the future.
My project is pretty close to be released into production so I am going to continue with it.

I have another question.

I ended up using an IMemoryCache for my global object with my .Net Core Web application.


I have my memory cache with my data.

I call it with ajax to add data to it.

I have a partial view in my main view. The partialview is just a select html element.

Is there a way I can update my select element as the cache updates without adding the elements manually with ajax.

I was hoping to possibly add my list of objects toto a viewbag and call my partial and have it all be updated. Idk if that is even possible.

My Partial - ShowCache.cshtml

@model TestVM


<select class="form-control" id="testBox" size="5" style="width:400px;" asp-for="TradeID" 
        asp-items="@(new SelectList(ViewBag.Cache ?? string.Empty, "TradeID", "Price"))">
</select>


My Main View
-------------------------
<div class="container row">
    <div class="col-6">
        <input id="connectionUrl" />
        <a class="btn btn-secondary" id="connectButton">button</a>

        <h1 id="lblLabel">Label</h1>

        <a class="btn btn-danger" id="stopButton">button2</a>
    </div>
    <div id="divadd col-6">
        <partial name="ShowCache.cshtml" />
    </div>
</div>
@section Scripts {
        var connectionUrl = document.getElementById("connectionUrl");
        var connectButton = document.getElementById("connectButton");
function updateState() {
            if (!socket) {

            } else {
                switch (socket.readyState) {
                    case WebSocket.CLOSED:
                        stateLabel.innerHTML = "Closed";
                        // disable();
                        connectionUrl.disabled = false;
                        connectButton.disabled = false;
                        break;
                    case WebSocket.CLOSING:
                        stateLabel.innerHTML = "Closing...";
                        //disable();
                        break;
                    case WebSocket.CONNECTING:
                        stateLabel.innerHTML = "Connecting...";
                        // disable();
                        break;
                    case WebSocket.OPEN:
                        stateLabel.innerHTML = "Open";
                        //enable();
                        break;
                    default:
                        stateLabel.innerHTML = "Unknown WebSocket State: " + socket.readyState;
                        //disable();
                        break;
                }
            }
        }

        connectButton.onclick = function () {
            stateLabel.innerHTML = "Connecting...";
            socket = new WebSocket(connectionUrl.value);
            socket.onopen = function (event) {
                stateLabel.innerHTML = "Connected";
            }

            socket.onclose = function (event) {
                stateLabel.innerHTML = "Closing...";

                $("#divadd").innerHTML += "Closed";
            };

            socket.onerror = function (e) {
                $("#divadd").innerHTML += "Errored";
            };

            socket.onmessage = function (event) {
                //$("#divadd").innerHTML += "event.data.p";
                var obj = JSON.parse(event.data.replace('\\', ''));
                var trade = event.data.replace('\\', '');

                $("#divadd").html += "<p>" + obj.p + "</p>";
                //$('#lstBox').innerHTML += "<option>" + obj.p + "</option>";
               // $("#divadd").insertAfter += "<span>" + obj.p + "</span>";
                updatePrice(obj);
                addData(obj);
                updateTrade(trade);
            }
        };
 function addData(data) {
            if (data != null) {
                var element = document.getElementById("lstBox")
                var opt = document.createElement("option");
                opt.text = data.s + "\t\t" + data.p + "     " + data.q ;
                opt.value = data;
                element.options.add(opt);

                $.ajax({
                    url: '@Url.Action("AddDataToMemory", "Home")',
                    type: 'GET',
                    //contentType: 'text/plain',
                    data: { model: JSON.stringify(data) },
                    //contentType: "application/json",
                    //dataType: "json",
                    dataType: "json",

                    traditional: true,
                    //data: { model: data },
                    //data: data ,

                   //contentType: type of data your sending
                    //dataType: what you're expecting back from the server: json, html, text, etc
                    //dataType: 'JSON',
                    //'application/x-www-form-urlencoded',
                })
                    .done(function (e) {
                        $.ajax({
                            url: '@Url.Action("ShowCache", "Home")',
                            type: 'GET',

                        })
                        //alert('done');
                    })
                return false;
            }
        }
}

HomeController
[HttpGet]
        public async Task<IActionResult> AddDataToMemory(string model)
        {
            if (model != null)
            {                
                var fixedModel = model.Replace(@"\", " ");
                Console.WriteLine("fixed " + fixedModel);
                //SocketResult socketResult = JsonSerializer.Deserialize<SocketResult>(fixedModel);
                //Console.WriteLine("S " + socketResult);
                //var resultA = JsonSerializer.Deserialize<string>(model);
                //Console.WriteLine("A " + resultA);

                AddToMemoryCache(fixedModel);

                AddToMemoeryCacheP(model);
                //SocketResult socketResult = JsonSerializer.Deserialize<SocketResult>(fixedModel);

                //JsonSerializerOptions jso = new JsonSerializerOptions();
                // jso.Encoder = System.Text.Encodings.Web.JavascriptEncoder.UnsafeRelaxedJsonEscaping;
                // var fixedModel = JsonSerializer.Serialize(model, jso);
                //jsoncontentstring
                //SocketResult socketResult2 = JsonSerializer.Deserialize<SocketResult>(fixedModel);
                //lstTrades.Add(new SocketResult() {Price = 100 });
                // var number = await GetMemoryCache("Data");
                //var memorycache = GetMemoryCache("Data");
                var memorycache = GetListCache();

                if (memorycache.Count == 1)
                {
                    Console.WriteLine("1 Record");
                }
                else if (memorycache.Count == 2)
                {
                    Console.WriteLine("2 Records");
                }
                else
                {
                    Console.WriteLine(memorycache.Count + " Records");

                }
            }

            return NoContent();
        }

        public void AddToMemoryCache(string data)
        {
            var cache = GetListCache(); 

            if (cache==null || cache.Count == 0)
            {
                List<string> listdata = new List<string>();
                listdata.Add(data);
                //var cache = GetMemoryCache("Data");

                //if (!_memoryCache.TryGetValue("Data", out data))
                //{
                //_memoryCache.Set("Data", listdata, new MemoryCacheOptions
                //{
                //    SizeLimit = 10
                //}); 
                //}
                //var options = new MemoryCacheEntryOptions().SetSize(10);
                //_memoryCache = new MemoryCache(new MemoryCacheOptions
                //{
                //    SizeLimit = 10
                //});

                _memoryCache.Set("Data", listdata);


            }
            else if (cache.Count <= 5)
            {
                var count = 3;
                if (cache.Count > 3)
                {
                    cache.RemoveRange(0, count);
                }
                cache.Add(data);

                _memoryCache.Set("Data", cache);
            }
            else
            {
                cache.Add(data);
                // List<string> listdata =  new List<string>();
                // listdata.Add(data);
                var options = new MemoryCacheEntryOptions().SetSize(10);
                var opt = new MemoryCacheOptions().SizeLimit = 10;
                //_memoryCache.Set("Data", cache, new MemoryCacheEntryOptions
                //{
                //    Size = 10
                //});
                //_memoryCache = new MemoryCache(new MemoryCacheOptions
                //{
                //    SizeLimit = 10
                //});

                _memoryCache.Set("Data", cache);
            }
        }

        public MemoryCache GetMemoryCache(string key)
        {
            return _memoryCache.Get<MemoryCache>(key);
            //if (_memoryCache.Get(key) != null)
            //   return (MemoryCache)_memoryCache;

            //!= null)
            //{
            //    return (MemoryCache)_memoryCache.Get(key);
            //}
           // return null;
        }
  public IActionResult ShowCache()
        {
            if (_memoryCache.TryGetValue<List<string>>("Data", out List<string> cache))
            {
                List<TestVM> lstTest = new List<TestVM>();
                foreach (string model in cache)
                {
                   if (!string.IsNullOrWhiteSpace(model))
                   {
                        var jsonDoc = Jsondocument.Parse(model);
                        var price = jsonDoc.RootElement.GetProperty("p");
                        var id = jsonDoc.RootElement.GetProperty("t");
                        var symbol = jsonDoc.RootElement.GetProperty("s");


                        TestVM testVM = new TestVM
                        {
                            Price = Convert.ToDecimal(price.ToString()),
                            TradeID = Convert.ToInt64(id.ToString()),
                            Symbol = symbol.ToString()
                        };
                        lstTest.Add(testVM);
                   }
                }
                //ViewBag.Cache = cache;
                ViewBag.Cache = lstTest;

            }
            return PartialView();
        }


Was This Post Helpful? 0
  • +
  • -

#6 Exceedinglife   User is offline

  • D.I.C Regular

Reputation: 7
  • View blog
  • Posts: 250
  • Joined: 01-July 12

Re: .Net Core Create Object to hold data in controller, like a global vari

Posted 13 May 2021 - 07:34 AM

so I figured out the answer to both of my questions.

Thank you all!

I used an IMemoryCache for a global variable on a web application.
And to update my partialview in real time I used the javascript .load function.
Was This Post Helpful? 1
  • +
  • -

#7 modi123_1   User is online

  • Suitor #2
  • member icon



Reputation: 16253
  • View blog
  • Posts: 64,719
  • Joined: 12-June 08

Re: .Net Core Create Object to hold data in controller, like a global vari

Posted 13 May 2021 - 07:45 AM

Thanks for the follow up!
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1