I have real time data coming from energy meters and I have to render this data to a table. I am a beginner and do not know how to append data to a Session. When I add data to the Session the old data gets lost.
public void Get_Real_Time_Values(Real_Time_Values values)
{
//please any guidance for appending data
Session["values"] = values;
}
if (datList.Count >= 100)
{
datList.RemoveRange(1, 20);
}
the data in Session is identified with a key. You cannot simply append data to it, but what you can do is append data to it in an indirect manner:
How?
Well, first read the data from the session into an object, list of object whatever you have, then append your new data to it then store the data back in the session.
An example would look like this:
Real_Time_Values currentSessionData = (Real_Time_Values )Session["values"];
currentSessionData.Add(newData)
Session["values"] = currentSessionData;
Be careful with how much data you store in the session though. If you have too much data you might want to start using a database or some sort of caching layer.
Related
I'm working on rewriting an MVC application that currently utilizes cookies to hold data between multiple pages such as a date. I have tried to come up with an option that would hold the data in the controller by using something like this:
public DateTime HoldDate {get; set;}
The problem that I'm facing is that this is overwritten on each page load. I have also considered using Vue to store the variable and then sending the date to the controller on page load, but I'm not sure how to perform this.
Any help is appreciated and thank you in advance!
You can use TempDataDictionary to pass data from the controller to the view and back. It's a Dictionary, so you can access it with a key:
TempData["HoldDate"] = new DateTime(2020, 2, 13);
When you read data normally from TempData, it is automatically marked for deletion with the next HTTP request. To avoid that, since you want to pass this data around, use the .Peek() method, which lets you read the data but does not mark it for deletion.
var date = TempData.Peek("HoldDate");
If you need data to persist during the entire user session, you can use Session. For example user id or role id.
if(Session["HoldDate"] != null)
{
var holdDate= Session["HoldDate"] as DateTime;
}
If you need data only persist a single request - TempData. Good examples are validation messages, error messages, etc.
if (TempData.ContainsKey("HoldDate"))
{
var holdDate = TempData["HoldDate"] as DateTime;
}
TempData and Session, both required typecasting for getting data and check for null values to avoid run time exception.
I have followed tutorial on how to write content part in Orchard CMS.
http://docs.orchardproject.net/Documentation/Writing-a-content-part
So, my content part writes the data from the backend to the record table that I wanted to, but the backend isn't reading saved custom content from the same table, i.e. when I manually change the record value in the database and refresh orchard admin, I don't see it changed.
How to change this?
That documentation article is slightly misleading because while the code it provides does store your data in the table you created in the database, it also stores the data within Orchards document storage (xml stored in the ContentVersionRecord table, column called data I believe). So basically for fetching data it will use the document storage, for any querying/filtering it will use the data stored in your record. You can change your code so it will only store it in your table if you'd prefer.
public double Latitude
{
get { return Record.Latitude; }
set { Record.Latitude = value; }
}
So yeah, I shall try to update the documentation tonight because that article is particularly confusing. Have a look at Bertrand's article on Orchard's document storage model: The Shift. Useful read
And I know it's annoying to hear this, but when you are playing with Orchard, it's best to play by its rules. Is there a particular reason you need to modify data directly in the db? Or just playing around?
I have a Session in my Controller as follow
Session["Fulldata"] = data;
Which stores data like Name,Id,City etc;
It stores multiple rows of such data.
How how do I access or check if any row has particular Name in it, in the View?
eg :
#if(Session("Fulldata").has("ABC"))
{
//Do Something
}
I want to check Name for each row in Session. Any help will be appreciated
First you need to cast the Session("Fulldata") back to you type as session store your collection as object type.
List<CustomClass> data = (List<CustomClass>)Session("Fulldata");
If data is a collection you can use linq Enumerable.Any to Search
#if(data.Any(d=>d.YourAttr1 == 'ABC' || d.YourAttr2 == 'ABC'))
{
//Do Something
}
As a additional note please do not use session unnecessarily especially for big data as session will need space on your server and as user/session increase it could adversely effect the performance.
currently we are using Sessions to store datatables in our pages so that we don't have to make Database hits to get the same datatable again and again. But my worry is that it is using the server memory and if large number of users login some day, the response of the server will become slow and our application might crash as well.
Please tell me is it a good idea to store datatables into Sessions or should we get the datatables from DB everytime?
As a general rule of thumb I would say don't use session. I haven't had to use session for a long time. As soon as you move into a web farm situation session either gets a lot slower or a lot more complicated or both.
Whether you will get away with it or not really depends on how much data you are storing in session, and how many users will be active within the session timeout period.
There are a lot of caching and in memory database options available today that may be a better option. Finally, while the solution as described sounds questionable, I wouldn't optimize the existing solution until you have actually measured a problem.
This is dependent on what is being stored in the datatables. In any case, I would use the ASP.NET Cache to store these datatables for the following reasons.
Cache has an expiry, which means you can automatically remove it based upon a sliding or absolute expiry timed value
Cache will automatically be removed if the processes memory "pressure" is too high.
You can make a cached item specific to one user, or global to all users based upon its key
for example:
// personalized cache item
string personalCacheKey = string.Format("MyDataTable_{0}", (int)Session["UserID"]);
DataTable myPersonalDataTable = (DataTable)Cache[personalCacheKey];
if (myPersonalDataTable == null)
{
myPersonalDataTable = database.dosomething();
Cache.Insert(personalCacheKey, myPersonalDataTable, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, 30, 0)); // 30 minutes
}
// global (non user specific) cached item
string globalCacheKey = "MyDataTable";
DataTable globalDataTable = (DataTable)Cache[globalCacheKey];
if (globalDataTable == null)
{
globalDataTable = database.dosomething();
Cache.Insert(globalCacheKey, globalDataTable, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, 30, 0)); // 30 minutes (again)
}
The issue that you have now, however, is if the underlying data gets updated, and whether it is acceptable for your application to present "old" cached data. If it is not acceptable, you will have to forcibly remove an item from cache, there are a few mechanisms for that.
You can setup a SqlCacheDependency (which I have never personally used), or you can just clear out the cached object yourself using Cache.Remove(cachekey).
It is preferable to store "commonly used" data in Memory; that's good logic. However "Session" means that it exists for the life of that Session, and hence that user. Secondly, pending the user "Session" life, as you already said, this could be consume valuable resources on the Server Side.
What you may want to consider using is the "Cache" object, as it serves the same purpose with "Expiration".
DataTable users = new DataTable();
if (Cache["users"] == null)
{
// users = getUsers(customer);
Cache.Add(“users”, users, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, 60, 0), System.Web.Caching.CacheItemPriority.Default, null);
}
else
{
sers = (DataTable)Cache["users"];
}
There are many ways to re-use memory in .NET
(1) ViewState
(2) Cache
(3) Session
(4) Cookies
But I would go for the "Cache" object.
If you can't increase memory on the web server then the obvious answer is to not store it in session state and get it from the database every time.
The problem with this is what impact will it have on your database? Are you just moving the problem from the web server to the database server?
It is much easier to scale out web servers than it is to scale up/out Databases (and often cheaper if you're using something like SQL Server)
If your datatable has smaller number of records and it does not contain sensitive data then you can use ViewState as well but data should be smaller as this approach will serialize the data and store it at client side and then gets the data from client side to store at server side.
I am working on a website and I want a drop-down to display the list of cities. Where should I store the list of cities for faster access? I do not want to store this data in DB.
Is it a good idea to store it in XML file?
I would store it in Cache, possibly with a Sql Dependency or File Dependency.
public DataTable GetCities(bool BypassCache)
{
string cacheKey = "CitiesDataTable";
object cacheItem = Cache[cacheKey] as DataTable;
if((BypassCache) || (cacheItem == null))
{
cacheItem = GetCitiesFromDataSource();
Cache.Insert(cacheKey, cacheItem, null,
DateTime.Now.AddSeconds(GetCacheSecondsFromConfig(cacheKey),
TimeSpan.Zero);
}
return (DataTable)cacheItem;
}
If you want to store it in XML, that's fine too but you'll have to publish the file to all servers in the farm each time there is a change.
Store it in a text file. This avoids the overhead of XML parsing. Load using File.ReadAllLines().
You can store the list in an XML file or other flat file format, but I guess it depends on what your reasons are for not wanting to store it in the database.
You mentioned faster access, but you might want to expound on that. If you mean you don't want the overhead of accessing the database on every request, then have you thought about storing it in the database and caching the list on application start-up instead? This way, you get the benefits of a database, yet only pay the overhead once.
For small applications, however, an XML file would be just fine.
If the list will never change, then just declare it as a const array of strings in your code.
If it may change occasionally, then put it in an xml file or a database table, but cache it when you have read it so it only needs to be read once in any session.
I believe XML is the best solution, and it would be better to use DOM parser rather than SAX.
You can also load the file into the session whenever it is not loaded to decrease the number of reads of the XML, but this will use more RAM on the server, be sure not to load unnecessary data because it will be loaded into the server's RAM for each session. You can load it only for logged in users if it makes sense.
What I'm about to suggest is HORID style, but I think the quickest you can get and with the smallest "footprint":
public static readonly string [] CityList = new string []
{
"Sydney",
"New York",
"London"
};
Now, I hope you don't like the solution, and can give us all a little more context so that we might be able to offer an elegant and maintainable solution to your problem; but if all your after is speed...