Is profile data for current user retrieved just once - asp.net

a) When current user accesses Profile object for the first time, does Asp.Net
retrieve a complete profile for that user or are profile properties retrieved one at the time as they are called?
b) In any case, is profile data for current user retrieved from DB each time it is called or is it retrieved just once and then saved for the duration of current request?
thanx

You don't specify if this is a Website Project or a Web Application Project; when it comes to profiles there is a big difference as they are not implemented out of the box for the Web Application Project template:
http://codersbarn.com/post/2008/07/10/ASPNET-PayPal-Subscriptions-IPN.aspx
http://leedumond.com/blog/asp-net-profiles-in-web-application-projects/
Have you actually implemented it yet or are you just in the planning stage? If the latter, then the above links should provide some valuable info. As regards the caching issue, I would go with Dave's advice.

If you want to save a database call, you can use a utility method to cache the profile or you can implement your own custom MembershipProvider which handles the caching.
The utility method is probably the simplest solution in this case unless you have other functionality you want to implement which would be served by implementing a custom MembershipProvider.
You can refer to this link for more details:
How can I access UserId in ASP.NET Membership without using Membership.GetUser()?
Here's an example of a utility method to do caching. You can pass a slidingMinutesToExpire to make it expire from the cache after some duration of time to avoid consuming excess server memory if you have many users.
public static void AddToCache(string key, Object value, int slidingMinutesToExpire)
{
if (slidingMinutesToExpire == 0)
{
HttpRuntime.Cache.Insert(key, value, null, System.Web.Caching.Cache.NoAbsoluteExpiration, System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.NotRemovable, null);
}
else
{
HttpRuntime.Cache.Insert(key, value, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(slidingMinutesToExpire), System.Web.Caching.CacheItemPriority.NotRemovable, null);
}
}

Related

How can I open database connection at runtime?

I am working on ASP.Net MVC project. I am making my database transactions with;
using (ISession session = FluentNHibernateHelper.OpenSession())
{
var user = session.Query<User>()
.FirstOrDefault(x => x.UserEmail == email && x.UserPassword == password); }
Instead of using this type of code block which is like open-close connection everytime, I want to open connection at runtime and I want to use that session variable everywhere. Maybe some codes in Application_Start()in Global.asax.cs?
I am open to your valuable ideas. Thank you for your help!
It's poor practice to leave a connection open nor maintain the state in the ORM across multiple transactions as state issues can crop up rather quickly as you make multiple requests against the same object & connection.
However, if you must, you could inject it as a Singleton service which would live longer than a single request. This is problematic for scaling and not recommended.
services.AddSingleton<ISession>(provider =>
{
return FluentNHibernateHelper.OpenSession()
});
More information: What is the difference between services.AddTransient, service.AddScoped and service.AddSingleton methods in ASP.NET Core?

Create Database If Not Exist Without Restarting Application

I am creating dynamic connection strings in my project. They're created on the fly with the information provided specifically for every user. When the application first fires off, if a database doesn't exist (first time user logs on), a new database is created without problems with this initializer:
public DataContext() : base()
{
// ProxyCreation and LazyLoading doesn't affect the situation so
// comments may be removed
//this.Configuration.LazyLoadingEnabled = false;
//this.Configuration.ProxyCreationEnabled = false;
string conStr = GetDb();
this.Database.Connection.ConnectionString = conStr;
}
The problem is, with this method, I have to restart the application pool on the server and the new user should be the first accessor to the application.
I need the same thing without a requirement of restarting the app. Is that possible?
(This is a SPA using AngularJS on MVC views and WebApi as data provider - May be relevant somehow, so thought I should mention)
I already tried this, but this creates an error for EF and the application doesn't start at all...
You could try a little bit different approach to connect directly (and create) the right database.
public class DataContext : DbContext
{
public DataContext(DbConnection connection) : base(connection, true) { }
}
Here you create the DbContext already with the right connection.
Take also care because you need to specify to migrations that the right connection should be used (not the Web.Config connection but the connection that raised the database creation).
See the second overload here https://msdn.microsoft.com/en-US/library/hh829099(v=vs.113).aspx#M:System.Data.Entity.MigrateDatabaseToLatestVersion.

How to invalidate ASP.NET cache if data changes in PostgreSql database

ASP.NET/MONO MVC2 application standard ASP.NET Web cache is used to speed up database access:
string GetName() {
// todo: dedect if data has changed and invalidate cache
var name = (string)HttpContext.Current.Cache["Name"];
if (name!=null)
return name;
name = db.Query("SELECT name from mydata");
HttpContext.Current.Cache.Insert("Name", name);
return name;
}
mydata can changed by other application.
In this case this method returns wrong data.
How to detect if data is changed and return fresh data from PostgreSql database in this case ?
It is OK to clear whole Web cache if mydata has changed.
The best way to do this is likely with LISTEN and NOTIFY.
Have your app maintain a background worker with a persistent connection to the DB. In that connection, issue a LISTEN name_changed, then wait for notifications. If npgsql supports it it might offer a callback; otherwise you'll have to poll.
Add a trigger to the name table that issues a NOTIFY name_changed.
When your background worker gets the notification it can flush the cache.
You can even use the NOTIFY payload to invalidate only changed entries selectively.

fetching and updating data from web service

Data can be fetched into an application through web service can it be possible to update data in web service from our application ..
In general a Web Service implementation can be any arbitrary code, so insert/update/delete is nothing special.
I suspect that there's something behind your question, some specific issue in mind? You may want to explain why you think there's a problem.
Of course create a web method that takes parameters and then save the data as required
[WebMethod]
public bool UpdateData(string firstName, string lastName, int id)
{
// do some data access code here
}
Then use in your code in a similar way as to when your are acquiring data from the web service:
MyWebServiceClient client = new MyWebServiceClient();
bool updated = client.UpdateData("Jon", "Skeet", 1);

How to clear SQL session state for all users in ASP.NET

I use SQLServer SessionState mode to store session in my ASP.NET application. It stores certain objects that are serialized/deserialized every time they are used.
If I make any changes in code of the structure of those objects and I put a new version live, any logged user will get an error, as their session objects (the old version ones) do not match the structure that the new version expects while deserializing.
Is there a way to clear all sessions at once in DB so that all active sessions expire and users are forced to log in again (and therefore all session objects are created from scratch)?
Or... Is there any other way to solve this situation?
You may try using stored procedure in SQL Server to clear all the sessions:
CREATE PROCEDURE [dbo].[DeleteSessions]
AS
DELETE [ASPState].dbo.ASPStateTempSessions
RETURN 0
You can call Session.Abandon, or Clear for every user when they hit the invalid Session object.
You can also loop through the per-user Session collection, and clear the keys that can contain "old" objects. Maybe you have a login ticket and such that you don't want to clear.
foreach (string key in Session.Keys)
{
if (!key.Equals("login"))
{
Session.Remove(key);
}
}

Resources