Fill Dropdown in asp dotnet from Caching - asp.net

I have a dropdown in asp.net which fills with Agent list. now agent list is 30,000. So I want to keep all the data in cache as we dont need to fill the dropdown again and again from database. How to achieve this by caching. Please guide

Suppose you have Cache varriable, then you have to convert it to DataTable,
DataTable tblCategories = (DataTable) Cache["Categories"];
and , then check, if still Datatable empty, then fetch from database using LoadCategoryInDropDownList() function which takes data from databse.
if (tblCategories == null)
{
tblCategories = new DataTable();
tblCategories=objDac.LoadCategoryInDropDownList();
// It inserts new row in filled datatable.
//This new row contains static data for user
//instruction Text such as" Select the Item"
DataRow dr=tblCategories.NewRow();
dr["CategoryID"]=0;
dr["CategoryName"]="--Select Item--";
tblCategories.Rows.InsertAt(dr,0);
//Cache The DataTable in a Cache Memory for duration of one hour...
Cache.Insert("Categories", tblCategories, null,
DateTime.Now.AddHours(1), Cache.NoSlidingExpiration);
}
then bind dropdown to datatable
DropDownList1.DataSource = tblCategories
DropDownList1.DataTextField ="A Descriptive Field from Table";
DropDownList1.DataValueField="A key / Value Field from Table";
DropDownList1.DataBind();
You can refer here http://www.codeproject.com/Articles/10033/A-generic-loading-of-data-in-a-DropDownList-using

Do you use particular cache framework?
.Net 4.5 has MemoryCache class you can use.
Example:
ObjectCache cache = MemoryCache.Default;
public Object GetCacheItem(string key)
{
return cache[key] as Object;
}
public void SaveCache(string key, Object value)
{
cache[key] = value;
}
public void RemoveCacheItem(string key)
{
if (cache.Contains(key))
cache.Remove(key);
}
Once you have your caching setup in a class, you can use it to cache your Agent lists. Then, load it to drop down list.
WARNING : Be very careful when using caching. Make sure you clear the cache at the end of certain life cycle. I have seen a case where IIS application pool using all of the memory in a server, so app pool has to be restarted every now and then.

Related

FluentMigrator create password protected SqlLite DB

I use FluentMigrator to create a SqlLite DB in C# using FluentMigrator.Runner.MigrationRunner. I wonder is there any way to use the SetPassword command o the SqlConnection only when the DB needs to be created ? There's a SqLiteRunnerContextFactory object but it don't seem to be a property that I can use to specify password.
public MigrationRunner CreateMigrationRunner(string connectionString, string[] migrationTargets, Assembly assembly, long version)
{
var announcer = new TextWriterAnnouncer(Console.WriteLine) { ShowSql = true };
var options = new ProcessorOptions { PreviewOnly = false, Timeout = 60 };
var runnerContext = new SqLiteRunnerContextFactory().CreateRunnerContext(connectionString, migrationTargets, version, announcer);
var sqlLiteConnection = new SQLiteConnection(connectionString);
//If the DB has already been created, it crashes later on if I specify this
sqlLiteConnection.SetPassword("ban4an4");
return new MigrationRunner(assembly,
runnerContext,
new SQLiteProcessor(sqlLiteConnection,
new SQLiteGenerator(),
announcer,
options,
new SQLiteDbFactory()));
}
I would like to avoid having to look if the file exists before setting password on connection.
Well, finally the code below works perfectly by using SetPassword everytime you create de runner. No need to check if the file exists or not. First time it creates it with the password and second time it opens it with it seems to use it to open DB. Which is exactly what I was looking for.

Using Auto Increment ID with ASP.NET checkbox list

First and foremost, I'm pretty new to programming, so attention to detail is appreciated.
I've currently got an asp checkbox list that receives data from an SQL table. I'm encountering a problem where if there's 2 items that are exactly the same, my remove function will remove both items. The following is the code for that:
protected void btn_remove_Click(object sender, EventArgs e)
{
for (int i = 0; i < UPCList.Items.Count; i++)
{
if (UPCList.Items[i].Selected)
{
var item = UPCList.Items[i];
var frcID = item.Value;
_itemNumberRepository.Delete(frcID);
}
}
Response.Redirect("WebForm2.aspx");
Response.End();
}
public string Delete(string itemCode)
{
string connectionString = foobar
Int32 returnDeleted = 0;
string deleteUpcCode =
"DELETE FROM compare1 "
+ string.Format("WHERE itemcode = '{0}'",itemCode);
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(deleteUpcCode, connection);
command.Connection.Open();
returnDeleted = command.ExecuteNonQuery();
command.Connection.Close();
}
return returnDeleted.ToString();
}
I've been told to use Auto Incrementing ID from SQL so that each row will have a unique ID so I can delete only the selected lines. However, I don't even have a clue how to do that. I've already turned on the identity option in SQL for the itemcode column, but aside from that, I'm lost. How do I go about using that ID to delete only selected items from the checkbox list in asp?
When you say the items are "exactly the same", do you mean that they have the same item code? And item codes are allowed to be duplicated in your system (i.e. is that the correct business rule)?
If so, that's why you need a auto-generated ID for each line, so that each row is unique. Which means that you need to use that ID in your DELETE query instead of the item code.
Typically, in a (ASP.NET) web app, this sort of thing is done with a "grid". You can use a GridView with two columns: one is a checkbox and another column is just a label showing the item code. Each row is bound to the ID field.
So, I recommend that you start by checking out GridView (there's lots of examples out there on the web): MSDN documentation for GridView

ASP.net any way to cache things like this?

I have a function called on every single page:
/// <summary>
/// Gets the date of the latest blog entry
/// </summary>
public static DateTime GetNewestBlogDate()
{
DateTime ReturnDate = DateTime.Now.AddDays(30);
using (var db = new DataClassesDataContext())
{
var q = (from d in db.tblBlogEntries orderby d.date descending select new {d.date}).FirstOrDefault();
if (q != null)
ReturnDate = q.date;
}
return ReturnDate;
}
It works like this website, it gets the latest blog entry date and if it's greater than the users cookie value it displays a new icon next to the blog link.
It seems rather wasteful to keep calling this function per page request, called 1:1 on the number of page requests you have. Say you have 30,000 page views per day, that's 1,250 database queries per hour.
Is there any way I can cache this results, and have it expire say every hour?
I'm aware it's a bit of a micro optimisation, but given 10 or so similar functions per page it might add up to something worthwhile. You could denormalise it into a single table and return them all in one go, but I'd rather cache if possible as it's easier to manage.
Since it's not based on the user (the cookie is, but the query doesn't seem to be) - you can just use the standard ASP.NET Cache.
Just insert the result with an expiration of 1 hour. If you like, you can even use the callback to automatically refresh the cache.
Assuming you've stored it into MS-SQL, you could even use a SqlCacheDependency to invalidate when new data is inserted. Or, if your inserting code is well-factored, you could manually invalidate the cache then.
Just use the ASP.NET Cache object with an absolute expiration of 1 hour. Here's an example of how you might implement this:
public static DateTime GetNewestBlogDate()
{
HttpContext context = HttpContext.Current;
DateTime returnDate = DateTime.Now.AddDays(30)
string key = "SomeUniqueKey"; // You can use something like "[UserName]_NewestBlogDate"
object cacheObj = context.Cache[key];
if (cacheObj == null)
{
using (var db = new DataClassesDataContext())
{
var q = (from d in db.tblBlogEntries orderby d.date descending select new { d.date }).FirstOrDefault();
if (q != null)
{
returnDate = q.date;
context.Cache.Insert(key, returnDate, null, DateTime.Now.AddHours(1), Cache.NoSlidingExpiration);
}
}
}
else
{
returnDate = (DateTime)cacheObj;
}
return returnDate;
}
You haven't indicated what is done with the returned value. If the returned value is displayed the same way on each page, why not just place the code along with the markup to display the result in a user control (ASCX) file? You can then cache the control.
Make it a webmethod with a CacheDuration?
[WebMethod(CacheDuration=60)]
public static DateTime GetNewestBlogDate()

ASP.NET Cache - circumstances in which Remove("key") doesn't work?

I have an ASP.NET application that caches some business objects. When a new object is saved, I call remove on the key to clear the objects. The new list should be lazy loaded the next time a user requests the data.
Except there is a problem with different views of the cache in different clients.
Two users are browsing the site
A new object is saved by user 1 and the cache is removed
User 1 sees the up to date view of the data
User 2 is also using the site but does not for some reason see the new cached data after user 1 has saved a new object - they continue to see the old list
This is a shortened version of the code:
public static JobCollection JobList
{
get
{
if (HttpRuntime.Cache["JobList"] == null)
{
GetAndCacheJobList();
}
return (JobCollection)HttpRuntime.Cache["JobList"];
}
}
private static void GetAndCacheJobList()
{
using (DataContext context = new DataContext(ConnectionUtil.ConnectionString))
{
var query = from j in context.JobEntities
select j;
JobCollection c = new JobCollection();
foreach (JobEntity i in query)
{
Job newJob = new Job();
....
c.Add(newJob);
}
HttpRuntime.Cache.Insert("JobList", c, null, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Default, null);
}
}
public static void SaveJob(Job job, IDbConnection connection)
{
using (DataContext context = new DataContext(connection))
{
JobEntity ent = new JobEntity();
...
context.JobEntities.InsertOnSubmit(ent);
context.SubmitChanges();
HttpRuntime.Cache.Remove("JobList");
}
}
Does anyone have any ideas why this might be happening?
Edit: I am using Linq2SQL to retreive the objects, though I am disposing of the context.
I would ask you to make sure you do not have multiple production servers for load balancing purpose. In that case you will have to user some external dependency architecture for invalidating/removing the cache items.
That's because you don't synchronize cache operations. You should lock on writing your List to the cache (possibly even get the list inside the lock) and on removing it from the cache also. Otherwise, even if reading and writing are synchronized, there's nothing to prevent storing the old List right after your call to Remove. Let me know if you need some code example.
I would also check, if you haven't already, that the old data they're seeing hasn't been somehow cached in ViewState.
You have to make sure that User 2 sent a new request. Maybe the content it saws is from it's browser's cache, not the cache from your server

TreeView manipulation, saving adding etc

Here is what I am trying to do. I have a TreeView server side control (asp.net 2.0) and I need the user to be able to add nodes to it, then after all the nodes desired are added, the data should be saved to the database.
Here are some things I would like to pay attention to:
1) I don't want to save the tree data each time the new node is added, but rather keep the data in session until the user decides to save the entire tree. The question here is: can I bind the tree to ArrayList object and keep that object in session (rather than keeping the whole tree in session)? Then each time the node is added I will have to rebind the tree to the ArrayList rather than database.
2) I wish to minimize ViewState, any tips? What works best: compressing viewstate or keeping it all on the server at all times?
Thanks!
Use TreeNodeCollection as your internal array to hold in either ViewState or Session. Here's a rough mock-up of an approach you can use; far from perfect, but should set you on the right track.
TreeView tv = new TreeView();
// Button click event for 'Add Node' button
protected void AddNode(object sender, EventArgs e)
{
if (SaveNodeToDb(txtNewNode.Text, txtNavUrl.Text))
{
// Store user input details for new node in Session
Nodes.Add(new TreeNode() { Text = txtNewNode.Text, NavigateUrl = txtNavUrl.Text });
// Clear and re-add
tv.Nodes.Clear();
foreach (TreeNode n in Nodes)
tv.Nodes.Add(n);
}
}
public bool SaveNodeToDb(string name, string url)
{
// DB save action here.
}
public TreeNodeCollection Nodes
{
get
{
if (Session["UserNodes"] ! = null)
return (TreeNodeCollection) Session["UserNodes"];
else
return new TreeNodeCollection();
}
set
{
Session["UserNodes"] = value;
}
}

Resources