Issue facing in using logger in asp.net web application - asp.net-mvc-4

Actually in my web project i am using logger concept to save user operations. it is working but my where i am facing the problem is when a user-A is loggedin means it is saving properly his operations in database but at the same time when another user-B is logged in means it is overlaping the information by saving User-B with User-A Details in database. is there any solution. below is my sample code
GlobalDiagnosticsContext.Set("PageViewed", "mInbox Page");
GlobalDiagnosticsContext.Set("PageType", "Mob");
GlobalDiagnosticsContext.Set("TimeStamp", DateTime.Now.ToString());
GlobalDiagnosticsContext.Set("UserId", Session["UserID"].ToString());
logger.Info("*** mInbox Page ***");

Related

How to extend authentication lifetime for TFS access?

I use the following code to access TFS:
using (var tfs = new TfsTeamProjectCollection(uri))
{
tfs.EnsureAuthenticated();
...
If my authentication is still valid it simply goes on. When it is not and my program runs under VS I am asked for login/password and after logging in I can proceed (when running my program from desktop it just throws an exception, another oddity).
The problem is that for some months now the lifetime of authentication shrunk to something like a week, so now I log in, and log in, and log in, and... which is super annoying.
So, is there a way to extend the lifetime of positive authentication?

MVC4 Getting Migrations to Run when publishing app through visual studio 2012

I created a visual studio 2012 MVC4 App. I am testing the "publish" functionality by right clicking the project and choosing publish. I followed the instructions here. I can connect to the remote web server and the folders get published to the correct folder, except the content folder for some reason.
When I run browse to the remote web server it prompts me for login so the app is working. However, the migrations never happened. The only tables created are the simplemembership tables, so I know the web server is connecting to the remote db server. No other tables are created and the seed method doesn't run. I seed the roles and a default user.
I checked the box in publish settings that says "Execute Code First Migrations (runs on application start)"
Everything works fine on my localdb connection string for local testing. Just can't figure out how to create db from existing migrations and seed when I publish to live site, note I will only seed once. Is there a way to specify which migrations to run again? I can copy the migrations and run on the database server but why the extra step?
EDIT:
When adding the database.setinilizer to my context I now get an error saying some of my fields in my userprofile table are not there, I use simple membership. This error occurs on the first page load after web publish, then on proceeding page loads I get an error The "WebSecurity.InitializeDatabaseConnection" method can be called only once.
HOwever, it does create my simplemembership tables now but my migration for all other tables never runs, that is why I am missing the additional user profile fields.
EDIT:
Basically I am not checking if websecurity is initialized prior to calling WebSecurity.InitializeDatabaseConnection so that resolved that issue. Now I have it partially working. The app creates the simplemembership tables fine but since I added tables to the UserProfile table I can't seed until I change them. So instead I manually create the userprofile table and have the app create the rest of the tables. Then I comment out the userprofile table in my initial migration. After this when I sign in it will then create the rest of my tables.
Open issue is how to get my database migration to run prior to the simplemembership initialization?
To get migration work on remote server, you need to add use SetInitializer in you Context class first :
static MyDatabaseContext()
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyProjectContext, Migrations.Configuration>());
}
And in you Migration Configuration you need to add this code :
public Configuration()
{
AutomaticMigrationsEnabled = false;
AutomaticMigrationDataLossAllowed = false;
}
I don't select the "Execute Code First Migrations (runs on application start)", and just after setting initialization in MyProjectContext, it does the migration for me.
If you have done by here, for seed your data, you can do same as below in your Migration configuration class:
protected override void Seed(MyProject.Models.MyProjectContextcontext)
{
DoSeed(context);
}
private void DoSeed(MyProjectContext context)
{
var users = new List<User>
{
new Site { UserId = 1, Name = "TestUser", IsDeleted = false },
new Site { UserId = 2, Name = "TestUser2", IsDeleted = false }
};
users.ForEach(s => context.Users.AddOrUpdate(s));
context.SaveChanges();
}
I have not selected the "Execute Code First Migrations (runs on application start)" on deploy Profile.
For some more details on this see this:
This link
and
This link
Hope this helps(as it worked for me), otherwise please add any error if there is, when you deploy you app.
I think the issue is ,Because of the fact that as long as you have not tried to access data
or create any data from/in site, which needs to connect to database, the migration and seeding
will not run"
And the reason for running migration on your site after logging into the site,
would be because your site need to be authorised in all pages, or the page that you want
to see data in.
If you have a page example home page, that does not authorization to access to the page,
you will see the page and if in this page there is some data that needs to be fetched from
data base, you may see the migration runs.
I found this from this Deploy it to IIS, but not sure if it is the reason.
Please let me know if your migration still has not ran if you browse your home page that
has data and no authentication needed for this data access.

SQL Network Interfaces, error: 26 only on solution rebuild

I have a site built using MVC4 which is getting content out of a database and it all works fine.
If I then rebuild the solution and try to refresh the page to check my changes, I will always get the SQL Network Interfaces, error: 26 saying that I cannot connect to the server.
However, if I then browse to my homepage and then back to the page I was looking at it will work fine.
Does anyone know what could cause this problem as it is really annoying
EDIT
Further to this I have found it is when the AuthorizationContext filterContext is being loaded after the rebuild that it cannot connect to the db
EDIT 2
As with neil below I have found that I only get the problem if I try to access a page that has had a role assigned to it
I'm seeing the exact same problem and can trace it to the .ASPXAUTH session cookie in the browser. Delete that cookie and the database error goes away until the next rebuild.
The error occurs regularly if you are authenticated and then rebuild the project and try to browse any page that either:
Requires authentication
Makes a call to the User object (e.g. #if (User.IsInRole("Administrators")))
If you have the AuthorizeAttribute filter set in App_Start/FilterConfig.cs you'll get this on every page.
This seems to be new behavior following the most recent Patch Tuesday updates. Previously, I was seeing weird behavior where I would remain logged in but I would loose my roll membership. After the most recent patches, it seems Simple Membership chokes when it gets a bad .ASPXAUTH cookie (invalid because of the rebuild).
I've got the correct connection string in InitializeSimpleMembershipAttribute.cs but it's like Simple Membership is defaulting to something else in this one instance.
Note that I've moved the Simple Membership databases from the original (localDb) to a full-fledged (local) SQL Server instance. Don't know why that would matter, and it works fine in all other cases.
Update:
I've also tried making the connection string name the same as the EF context name (e.g. "ProjectContext") on the theory that it is defaulting to the standard convention, but that made no difference. I am explicitly identifying the connection string name in all my context class constructors (using the : base("connectionString") syntax) and Simple Membership is able to find the right connection string all other times.
Update 2:
The problem only occurs after rebuild when accessing a page protected by role. A simple [Authorize] won't trigger it. You need something like [Authorize(Role="Admin")]. I've replicated this on a new MVC 4 project with no other modifications, using the default (localDb) database. Clear the cookie and that same user can access the protected content w/o any problems. I believe this is a core .NET or MVC bug and needs to be reported as such.
This happened to me while rebuilding the application when I was logged in the browser.
Deleting cookies fixed the problem for me.
When using SimpleMembership, this bug occurs with any use of Roles-not just in the controller, but also when I use:
if(Roles.IsUserInRole(rolename){...
I am late to the game with this answer, but I added [InitializeSimpleMembership] to my home controller and I think that fixed it.

ASPNET out-of-proc session is mysteriously reset

I'm facing a very peculiar issue with sessions being reset without any apparent reason. This happens randomly, once every few tens or hundreds of requests.
My web application is running on windows 2003, IIS 6.0, .NET 1.1. The application has a webpage which populates a bunch of Session variables during its Page_Load event. The data is stored out of process in ASPNET State Service.
After the Page_load event exits and the page is displayed, the user clicks on a button, which retrieves the session data and does some work with it.
And this Button_click is where the issue occurs. On some occasions, the session variable is null, raising a nullRefException.
Our traces show that the sessionID during the Button_click event is a brand new session, with a different ID than the session of the Page_Load event. Thus, the application fails to retrieve the data that was stored during Page_Load. Our event log shows that the session variables for the problematic requests are indeed populated during the Page_load event, and the response is sent without issue, which normally would persist the data.
We have ruled out session timeouts; although a timeout would still result in the same nullRefException, the same session ID from Page_load would be used to retrieve non-existing data. In this case, the sessionID is different than the original.
We are not messing with the ASPNET cookie in any way, we do not use session.abandon, nor do we inadvertedly remove items from the session.
My question is: what server-side factors could cause the cardholder's session to be reset like that? The Application event log does not contain any useful info.
Also, is there anything client-side (e.g. cookie tampering) that could force IIS to assign a new session upon subsequent postbacks of the page?
Many thanks in advance.
I'm not sure if this applies to your situation, but it might help others.
I was designing a website and I found out the hard way, meaning I had to redesign a portion of this site I was working on. When you create or delete a folder (from an asp.net page) within the active IIS folder it resets all sessions for the website. This means every user currently on the site gets their sessions instantly deleted.
If you have control of your the server, store files outside the IIS folder and stream them in as needed. If you don't have control of the server, you will have to remove any work with folders.

Stateful session with nhibernate and asp.net

Let's say I have a client who is filling up a data from a website. the underlying persistence used is Nhibernate.
Now the series of events goes like this
user fills up the form .
he submits the form .
the nhibernate sessionfactory is created and via customer object its is saved to database .
the database commits the session object using a native generator for nhibernate
but a mishap happens before the response from the server reaches the client . the connection to the client goes off .
the client gets to see a page not found error or request time out error . and has a dilemma that he isnt registered yet .
so he again presses the refresh button . and the same set of data (although that is committed to database ) has been send to server for database commit.
the server sees the data and again registers the same customer with different id .
so the problem goes like . now the same customer entry has been duplicated two times cause the connection has got cut off .
Now can someone tell me how to proceed into this scenario. So that even if the customer submits he just recognizes only one entry and submits it, even if the response has got cut off and he presses the refresh button?
Thoughts:
1) You don't want to create the NHibernate SessionFactory on every request. This should be created once and then used by all future requests. It's a heavy-weight operation. Only the Sessions need to be created each request.
2) Manage the transaction in a high level method - to reduce the likelihood of something going wrong AFTER you've committed the transaction, but BEFORE the client has a response.
3) Guard against the "Refresh" method resubmitting, by having the submit function return a different page which presents the information. This page should not submit anything.
4) Guard against a resubmit server side by validating the submission against previously submitted credentials. Inform the client if they've previously registered and provide them with a means to access the saved details (Password recovery for example.)
so for example if your users are keyed by email address then in the page load event perform the following steps: