Use data from DataTable in all forms - c#

In the class I execute a stored procedure and return a DataTable.
public DataTable getUserInfo(int abid)
{
DataTable tbl = new DataTable();
string constring =ConfigurationManager.ConnectionStrings["myconn"].ConnectionString;
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("getUserInfo", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#ABID", abid);
SqlDataAdapter adap = new SqlDataAdapter(cmd);
adap.Fill(tbl);
}
}
return tbl;
}
Then in the code behind of the default.aspx.cs page I call the class and using a foreach loop I get all the data I need.
DataTable tbl = new DataTable();
tbl = u.getUserInfo(abid);
foreach (DataRow row in tbl.Rows)
{
string firstName = row["firstName"].ToString();
string lastName = row["lastName"].ToString();
string fullname = row["fullname"].ToString();
string Phone = row["phone"].ToString();
}
This solution works if I only had to use the data in this page only. I need the same data to use in different pages in the project. Of course, I could call the class every time and create different data tables and store them in different variables, but I know it's not very efficient. I'm sure there's a better way to do this.
Is there a way that I could create global variables? For instances I load the datatable into those variables and I can use them throughout the project? Or any other solution?
Thanks

If that data is shared among different users then use Cache object. See: ASP.NET Caching: Techniques and Best Practices.
But if that data is unique to each user then store that information in a Session object. But remember, Sessions are maintained for each user on Server, If you keep too much data in Session then it will require more resources from the Server.
See: ASP.NET Session State Overview
To store information in Session
//To store
Session["UserInfo"] = tbl;
To retrieve
DataTable tbl = Session["UserInfo"] as DataTable;
if (tbl != null)
{
//Datatable found;
}
Session object can be accessed on multiple pages.
You also have other options to maintain state across pages in ASP.Net, like Cookies. See
ASP.NET State Management Overview

Web is stateless, which means a new instance of a web page class is re-created each time the page is posted to the server. As we all know, HTTP is a stateless protocol, it can't hold client information on a page.
If the user inserts some information and move to the next page, that data will be lost and the user would not be able to retrieve that information. We need to store information. Session provides a facility to store information on server memory. It can support any type of object to store along with our own custom objects. For every client, session data is stored separately, which means session data is stored on a per client basis. Have a look at the following diagram:
State management using session is one of the best ASP.NET features, because it is secure, transparent from users, and we can store any kind of object in it.
Advantages:
It helps maintain user state and data all over the application.
It is easy to implement and we can store any kind of object.
Stores client data separately.
Session is secure and transparent from the user.
Disadvantages:
Performance overhead in case of large volumes of data/user, because session data is stored in server memory.
Overhead involved in serializing and de-serializing session data, because in the case of StateServer and SQLServer session modes, we need to serialize the objects before storing them.
Reference:
1.http://www.codeproject.com/Articles/32545/Exploring-Session-in-ASP-Net

I suggest that you implement a lazy-loading solution to this.
Since static member are shared across all requests to the application, you can cache data that you know isn't going to change. Obviously you have to be careful about caching too much or for too long, or you're going to run int RAM issues. You'll also have to consider concurrency.
Here's a simplified example: create a class that represents a user, and then create a static method, LoadByID(int id), and a static Dictionary to stored already-loaded users. Then, when a page requests a user, serve them the item from the cache if it already exists.
//... user instance fields ...
private static Dictionary<int, User> cache = new Dictionary<int, User>();
private static object lockObj = new object();
public static User LoadByID(int id)
{
lock (lockObj) //Prevent double-adding items
{
if (cache.ContainsKey(id))
{
return cache[id]; //We've already loaded the record.
}
else
{
//Some function that actually calls the database
//and constructs user objects
User loaded = LoadUserInternal(id);
cache.Add(id, loaded)
return loaded;
}
}
}
private static User LoadUserInternal(int id)
{
//Load and construct the user
}

Related

Asp.net Mvc c# dynamic Session

I have one application with multi-database login I want to use dynamic session where I can save the user name and his connection string then I could realize session data for the special one in the case log off and also to void sometimes mixed between session data values in saving user data as sometimes when I save data for example for database 1 I find it saved in another database while another user is login for the second one
my trial is
List<String> ConnectionSessions = new List<string>();
List<String> usernamevalue= new List<string>();
ConnectionSessions.Add(query[0].ConnString);
usernamevalue.Add(x.Split('-').First());
foreach (string section in ConnectionSessions)
{
foreach (var uname in usernamevalue)
{
Session[uname] = section;
}
}
My question how can I call this section and use it is valued in different controles and is my idea right as i know each user has his own session

How to loop through multiple connection strings in a db and query them?

I don't know how to loop through my local database and add the values to this string:
string credentials = #"server = 127.0.0.1;
user id = system;
port = 3308;
Password = 975315";
https://i.imgur.com/6B4YFw7.png
I kind of need something like this:
string credentials = #"server = IDindb;
user id = IDindb;
port = Portindb;
Password = Pwindb";
foreach(rowofdata in localdb)
{
MySqlConnection con = new MySqlConnection(credentials);
con.Open(); //Opens the connection
MySqlCommand cmd = new MySqlCommand(sqlQuery, con); //Sends the
query to "show slave status"
Create a new table in browser that shows if server is running or not.
}
This is quite a good homework assignment - It touches frontend, database, networking and middleware, and importantly it forces you to properly think through all the little decisions of what might go wrong, e.g.
what do you do when the server doesn't respond (write "server down
into your html table)
how do you trap this without your own code failing.
What if the servers take a really long time to respond? Timeout?
Should you be doing this to each server in succession, or
all at once, adding their responses into the table as you go?
What I'm saying is you should think about your overall solution some more before diving into the code.
To answer the question, assuming you have some code to connect to the local db and query the table, rowofdata will be a recordset, with each row populated per the row in your image.
Extract the server, user, password etc credentials from it:
var masterHost = rowofdata["Master_Host"].ToString();
and create the connection string inside the for-loop.
var credentials = $"server={masterHost};user id={userId}; port={portId}; Password={password}";
The Create new Table in browser part will depend on which platform/language you're writing in. And in any case shouldn't be done here, unless you're intent on mixing db access with html (#Razor? classic asp?).
Store the server / status values in a list (of server object, with status etc), then subsequently use them to populate the html.
(Or build the html table and render that, and use ajax to request the status of each).
(unrelated - how do you plan on implementing the stop/start/fix button code?)

ASP.NET Web API: How to create a persistent collection across requests?

I have a Web API providing a backend to an Angular.JS web application. The backend API needs to track the state of user activities. (Example: it needs to note which content ID a user last retrieved from the API)
Most access to the API is authenticated via username/password. For these instances, it works fine for me to store the user state in our database.
However, we do need to allow "guest" access to the service. For guests, the state does need to be tracked but should not be persisted long-term (e.g. session-level tracking). I'd really like to not have to generate "pseudo users" in our user table just to store the state for guest users, which does not need to be maintained for a significant period of time.
My plan is to generate a random value and store it in the client as a cookie. (for guests only - we use bearer authentication for authenticated users.) I would then store whatever state is necessary in an in-memory object, such as a Dictionary, using the random value as a key. I could then expire items off the dictionary periodically. It is perfectly acceptable for this data to be lost if the Web API is ever relaunched, and it would even be acceptable for the dictionary to be reset say, every day at a certain time.
What I don't know how to do in WebAPI is create the dictionary object, so that it will persist across Web API calls. I basically need a singleton dictionary object that will maintain its contents for as long as the server is running the Web API (barring a scheduled clearing or programmatic flushing)
I had the idea of dumping the Dictionary off to disk every time an API call is made, and then reading it back in when it's needed, but this does not allow for multiple simultaneous in-flight requests. The only method I can think of right now is to add another database table (guest_state or something) and replicate the users table, and then setup some sort of manual method to regularly clean out the data in the guest table.
Summary: what I need is
a way to store some data persistently in a Web API backend without having to go off to a database
preferably store this data in a Dictionary object so I can use randomly-generated session IDs as the key, and an object to store the state
the data is OK to be cleared after a set period of time or on a regular basis (not too frequently, maybe a minimum of a 6 hour persistence)
I figured out a solution using the Singleton pattern:
public static class Services
{
private static Dictionary<string, string> cache;
private static object cacheLock = new object();
public static Dictionary<string,string> AppCache
{
get
{
lock (cacheLock)
{
if (cache == null)
{
cache = new Dictionary<string, string>();
}
return cache;
}
}
}
}
public class testController()
{
[HttpGet]
public HttpResponseMessage persist()
{
HttpResponseMessage hrm = Request.CreateResponse();
hrm.StatusCode = HttpStatusCode.OK;
Services.AppCache.Add(Guid.NewGuid().ToString(), DateTime.Now.ToString());
string resp = "";
foreach (string s in Services.AppCache.Keys)
{
resp += String.Format("{0}\t{1}\n", s, Services.AppCache[s]);
}
resp += String.Format("{0} records.", Services.AppCache.Keys.Count);
hrm.Content = new StringContent(resp, System.Text.Encoding.ASCII, "text/plain");
return hrm;
}
}
It seems the Services.AppCache object successfully holds onto data until either the idle timeout expires or the application pool recycles. Luckily I can control all of that in IIS, so I moved my app to its own AppPool and setup the idle timeout and recycling as appropriate, based on when I'm ok with the data being flushed.
Sadly, if you don't have control over IIS (or can't ask the admin to set the settings for you), this may not work if the default expirations are too soon for you... At that point using something like a LocalDB file or even a flat JSON file might be more useful.

Load data from database in _layout.cshtml

I am creating a web application using ASP.NET MVC 4.
I want to display the user's nickname on all of pages, so I have to load it in _layout.cshtml.
Please note that I'm storing user's nickname manually. (In my own database and my own tables.)
I can add user's User name by Membership.GetUser().UserName, but I want to load his nickname from database and show it in _layout.cshtml.
How to do that?
Let me give a simple solution for what you want:
write an action in a controller (mine is CommonController):
public ActionResult NickName()
{
SqlConnection cn = new SqlConnection(cnstr);
SqlCommand cmd = new SqlCommand(cmdStr, cn);
cn.Open();
SqlDataReader dr = cmd.ExecuteReader();
string nickName = string.Empty;
while (dr.Read())
{
nickName = dr["nick_Name"].ToString();
}
dr.close()
return Content(nickName);
}
put the below line in everywhere you want in _Layout:
nickname = #{Html.RenderAction("NickName", "Common");}
Finished!
Thanks to #SergRogovtsev for recommending:
nickname = #Html.Action("NickName", "Common")
first asked:
Are you using entity framework?
You can use partial views in _Layout either using EF or ADO.
If you mean you can't access aspnet_membership table by using entity framework, you should ask your question in another way!
let me know more about your problem by giving some sample of your code.
I would advise you to upon logging in, store the username in a session variable (which is done by accessing the Session object, which implements a key=value pair architecture allowing you to store and retrieve your data at will). It's a drag on performance to have to make a database call for EVERY page that loads, and a single nickname string variable in session won't take up that much space on your server.
As far as loading the variable you could use the code posted by Vahid, but I would recommend you if your site is still in its infancy to take the extra time to learn and implement Entity Framework. It is cleaner, easier and Microsoft is really pushing data connection management in that direction.
I have used a combination of Mr_Creostoe and Vahid answers.
I am saving nickname in a session (as Mr_Cresotoe said), and if there isn't such session (for example, if user ticked remember me checkbox and is visiting after many time), I'll create that session using RenderAction. (As Vahid said).
Thank you guys!

Correct way to handle Caching of DB-Data

I always wondered how exactly you'd handle caching of database-values (in C#, ASP.NET) so you e.g. don't reload several DataSource-Bound ASP-Controls or don't have to reload them everytime you use a certain backend method.
Let's just take the following example:
aspx.cs-File:
List<FormElement> elements = FormElement.GetForForm(Session["FormName"].ToString());
Backend-Method:
public static List<FormElement> GetForForm(string fName)
{
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand("select Rank, Control, Variable from inspire.dbo.formelement where formid=(select id from inspire.dbo.form where name=#name)", Database.Conn);
cmd.Parameters.Add(new SqlParameter("#name", fName));
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
return dt.Rows.ToList<FormElement>(item => new FormElement(item));}
How exactly would I handle caching here?
Thanks,
Dennis
what we have done for the caching:
in page side, use a global container (eg. dataset) to store all the required data, each data add a time flag for it
in backend side, use a same container to store the data, and also with the time flag
when page refresh, compare the time flag with current datetime, get data from that container;
or send a refresh_fetch to backend side, backend will get data from db and update caching content for its container, then send back the updated data to page
page update its container and display out
the flow is simply like this, however, based on real situation, the container, the refresh strategy... maybe different

Categories