MVC :: RhinoMock + Mocking The Httpcookie?
Jun 1, 2010I have a cookie which my controller uses.
How should i mock the cookie?
I have a cookie which my controller uses.
How should i mock the cookie?
I am creating some cookies in my ASP.NET application. These cookies expire 10 minutes after they have been created. I follow the approach described on MSDN as shown here:[URL]
My question is, when a cookie "expires", what happens? Does the browser automatically delete the cookie? Is it our responsibility as developers to remove the cookies if they exist and have expired?
A web site was developed and deployed to client. In some cases, I need to set the flag HttpCookie.HttpOnly = true. Okay - I have done it. Next question:
Is Cookie available after setting flag in JavaScript?
or maybe some restriction when I am using JavaScript?
or do I need to make some changes in existing JavaScript?
I'm creating an HttpCookie, setting only the name and value and not the expires property, then adding it to the response. Simple enough. The cookie is created (but not persisted) as expected. The problem is when the session changes for some reason (like the website was rebuilt, or I rebuilt my app when debugging) then the cookie stays around. I want the cookie to be valid for only the original session it was created on.
According to MSDN it says: "If you do not specify an expiration limit for the cookie, the cookie is not persisted to the client computer and it expires when the user session expires." I guess I don't know exactly what "session expires" encompasses. I figure the cookie gets deleted after 20 min when the session expires. But should the cookie get deleted if the session it was created on doesn't exist anymore for any number of reasons? The only time I've seen the cookie get deleted is when the user closes all browser windows and opens a new one.
If this is all true, I may have to store the original session id ("ASP.NET_SessionId") in the cookie, then check it against the current session id, if they're different, then delete the cookie or create a new one.
Here's the code (the only difference between my cookie and the one in the MSDN examples is I'm storing multiple values in the cookie):
private void SaveValuesToCookie(string[] names, string[] values)
{
HttpCookie cookie = new HttpCookie("MyCookie");
for (int i = 0; i < names.Length; i++)
{
string name = names[i];
cookie.Values[name] = values[i];
}
Response.Cookies.Add(cookie);
}
private string GetValueFromCookie(string name)
{
HttpCookie cookie = Request.Cookies["MyCookie"];
if (cookie == null)
return null;
return cookie.Values[name];
}
I'm trying to write cookies from my website and I'm trying to figure out what implications timezones has over the HttpCookie.Expire property. Should I be passing DateTime.Now.AddDays(1) or DateTime.UtcNow.AddDays(1) or the users's timezone plus a day?
View 1 RepliesI have a web application developed using VB .Net 2003, and is running ASP Net 1.1.
The application is running fine on all browser, except for the login/authentication control that doesn't work properly on Chrome.
We have different types of users using the website, and each user type has different menu items displayed for.
The problem is, if a user logs on with let's say Admin account, and logs off and later logs on again using student account, the user still gets the Admin menu, and of course vice versa.
I'm not sure if I'm doing something wrong, or there is something I'm missing here.
On more thing, if the timeout period reached, and the session was timed out , and the user (regardless of the type) tries to log on again, he is successful on all browser except on Chrome again!, where it keeps telling the session was timed out, and never logs on again until clearing the cookies.
This is what i have in my application web.config
<!-- Authentications -->
authentication mode="Forms">
<forms loginUrl="index.aspx" name="authCookie" protection="All" timeout="60" path="/"></forms>
</authentication>
[Code]....
This has been a nagging issue for some time, but very sporadic and difficult to isolate.
From time to time, browsers that have authenticated on a web application, have been open for a while, have logged in and out of the same web application multiple times, have multiple tabs, are pretty much any browser (Chrome, IE, Firefox, Safari), and seemingly at random, lose their ability to retain an AuthCookie after being set and followed by a redirect. Closing the browser and starting a new session resolves the issue, as does opening up a different browser and attempting to authenticate.
Our team uses forms authentication for all of our websites and web application. This is a pretty typical setup where a login form is displayed, the user enters credentials and a cookie is set on the click event of the postback, then a redirect occurs to the same page where the cookie is then referenced and used to complete authentication.
In this situation
FormsAuthentication.FormsCookieName = ".WebAuth"
Within Event:
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, Username, DateTime.Now, DateTime.Now.AddMinutes(SessionTimeout), false, Username); HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket));
Response.Cookies.Add(faCookie);
Response.Redirect(Request.RawUrl, true);
After the redirect, on PreInit:
HttpCookie authCookie = Request.Cookies[cookieName];
At this point, the authCookie variable is typically not null, but in these isolated circumstances that I've outlined above, the cookie comes back null after the redirect.
This happens very randomly, sometimes weeks before affecting one of our developers. As I said, restarting the browser resolves the issue.
Today I had it happen on our dev server while using Chrome. I had logged into the application, allowed the application to session timeout, and then attempted to login again. The attempted login then failed to set the cookie. I remotely attached Visual Studio to the process on the server to begin debugging. The entire time I could step through my code, even deploy new code versions to the server with updates, restart the app, restart IIS on the server, attach and reattach to the project, and the issue persisted in Chrome. In Firefox, I was able to authenticate without issue.
From Chrome, the login would validate, attempt to set a Response Cookie as outlined above. Prior to redirect, I could see the properly set Response Cookie, as well as its counterpart in the Request Cookies. However, on each redirect after a seemingly successful login, the Response and Request Cookie are gone.
I enabled Trace on the application to view the cookie collection:
There is a .WebAuth in the Request Cookies Collection, as well as ASP.NET_SessionId and several ASPSESSIONIDxxxxxxxx, but when the page loads, only the ASP.NET_SessionId and ASPSESSIONIDxxxxxxxx cookies are available in the Request.Cookies scope, no sign of the .WebAuth. However, in the page's Trace information after render, there multiple .WebAuth cookies listed, it is just that the page seems to have no access to them.
Primarily, on a working version after authentication there is both a .WebAuth Response and Request Cookie in the page's Trace info. But on a non functioning browser window, the Response Cookie is absent.
Has anyone else had any experience with this? It is such a nagging issue, and so sporadic, but I would love to be able to resolve it. My concern is that it may be affecting users and we would have no knowledge since the description of the issue is so convoluted.
I have a site that is using Forms Auth. The client does not want the site session to expire at all for users. In the login page codebehind, the following code is used:
// user passed validation
FormsAuthentication.Initialize();
// grab the user's roles out of the database
String strRole = AssignRoles(UserName.Text);
// creates forms auth ticket with expiration date of 100 years from now and make it persistent
FormsAuthenticationTicket fat = new FormsAuthenticationTicket(1,
UserName.Text, DateTime.Now,
DateTime.Now.AddYears(100), true, strRole,
FormsAuthentication.FormsCookiePath);
// create a cookie and throw the ticket in there, set expiration date to 100 years from now
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName,
FormsAuthentication.Encrypt(fat)) { Expires = DateTime.Now.AddYears(100) };
// add the cookie to the response queue
Response.Cookies.Add(cookie);
Response.Redirect(FormsAuthentication.GetRedirectUrl(UserName.Text, false));
The web.config file auth section looks like this:
<authentication mode="Forms">
<forms name="APLOnlineCompliance" loginUrl="~/Login.aspx" defaultUrl="~/Course/CourseViewer.aspx" />
</authentication>
When I log into the site I do see the cookie correctly being sent to the browser and passed back up: However, when I walk away for 20 minutes or so, come back and try to do anything on the site, the login window reappears. This solution was working for a while on our servers - now it's back. The problem doesn't occur on my local dev box running Cassini in VS2008.
I'm trying to unit test the logOn method of my .Net 4.0 MVC application. I'm pretty sure I need to mock a bunch of objects because I don't want to hit the actual database and I only want to simulate an HTTPcontext in a limited and specific way (if I have to do it at all). All the examples I've found online use mocking frameworks like Moq, RinoMocks or nMock. MVC is all about Test Driven Development, there must be some way to do simple tests without using third party software.
The specific problem,The basic problem is that the controller I'm testing calls Response.Cookies.Add(...) but since the unit test is not in an HTTPContext, Response is null and I get an exception.
My research so far,I understand there is a layer of abstraction which will help me somehow. For example HttpResponse inherits from HttpResponseBase. I think I'm supposed to make a class that inherits from one of the MVC base classes, overload some of the members and then
call the method I want to test in a way that gives it my object instead of one it would normally use.
The question is how to do that. One would need to set up existing code with the ability to construct future versions of objects. Intuitively however, it would seem that existing code could only be and use functionality that existed at the time it was written.
Fortunately, a dynamic runtime means that the code which is actually run can be determined things that change after it is written like config files and HTTP headers.
One way to do that is for the existing code to use some method typically referred to as a factory that takes a string and returns an instance of an object.I conclude that I should look through the code for this factory and figure out how to manipulate it.
My background,I've recently graduated with a degree in Computer Science. Now at my new job, I've been assigned to write unit tests for a large project. Admittedly, I'm new to MVC, many aspects of C# and large projects in general. I may have made simple mistakes or incorrect assumptions in my analysis of this problem. I will do my best to stay active on this post and make it useful for others in situations similar to mine.
I am looking for some guidance
\
-Rhino.Mocks
-Moq
-NMock
-TypeMock (not free)
I am new to testing.I have to test some C# classes.Kindly let me know what is mocking and why some mocking framework like Rhino mock is preferred over nUint?
View 1 RepliesI need to create Unit Tests for an ASP.NET MVC 2.0 web site. The site uses Windows Authentication.I've been reading up on the necessity to mock the HTTP context for code that deals with the HttpContext. I feel like I'm starting to get a handle on the DI pattern as well. (Give the class an attribute of type IRepository and then pass in a Repository object when you instantiate the controller.)
What I don't understand, however, is the proper way to Mock the Windows Principal object available through User.Identity. Is this part of the HttpContext? have a link to an article that demonstrates this (or a recommendation for a book)?
I'll be starting a complete re-write of a system in the coming weeks. I'll be using ASP.NET MVC 2.I'm still trying to determine what I should be using as far as TDD, mocking, and IOC is concerned. I was thinking:
VSTEST for writing my TDD tests (or possibly nUnit) Moq as my mocking framework (for creating doubles and fakes) Moq for IOC development Not sure exactly what the ideal setup should be and I'm continuing to research what's available. I'd like some feedback from the community on the most optimal toolsets for TDD, mocking, and IOC.
I'm looking for as comprehensive as possible of a mock replacement and wrapper for the ASP.NET HttpContext in my applications. A comprehensive mock replacement could potentially increase the testability of my ASP.NET web applications substantially, without necessitating migrating every application to more-testable frameworks such as MVC.
Some of the features I am most interested in seeing in an HttpContext wrapper and mock framework include:
Serialized session storage (e.g., .Session).
Serialized application-scoped storage (e.g., .Application).
Per-request item storage (e.g., .Items).
HttpRequest data, such as referrers, request Uri, server variables, post data, etc.
HttpResponse data, such as status codes and content.
Local file resolution (e.g. Server.MapPath)
VirtualPathUtility for application-relative URL path resolution, which has a dependency on the ASP.NET runtime.The identity and principal (e.g., .User) for validating authentication/authorization rules.The AllErrors collection for testing error resolution in HttpModules and Global.asax.I considered writing my own interface, wrapper, and mock; however, I believe such must already exist. The variety of mock frameworks is a little overwhelming for a first-timer to absorb.
What is the most comprehensive HttpContext wrapper and mock?
I've see n a lot of discussions surrounding HttpSessionState and asp.net MVC.I'm trying to write tests for an asp.net application and to mock the HttpSessionState and if so, how?I'm currently using Rhino Mocks and Nunit
View 1 RepliesMicrosoft Ajax can expose webservices which respond with json or xml depending on configuration. I would like to mock these services using soap ui. Using the wsdl I can do this to mock the services in the case where xml is returned, however how can I mock the response when JSON is returned?
View 1 RepliesI have a class which I store in session. Lets say Class A, having an attribute theList. I have a member function that adds an item to theList and returns the count of my list.So I mock my class and set theList to "1,2,3" for my unit test, and test my add function by adding "4".
It returns count "3" instead of "4".
here Im trying to write a test can I mock a HttpRequestBase to return post values like this? please help as its quite urgent, how can I acheive this?
var collection = new NameValueCollection();
collection.Add("Id", "1");
collection.Add("UserName", "");
[code]...
Since I'm having problem with unit testing RenderPartialViewToString() with Moq framework [URL] I'm thinking about getting my controller directly, without using Moq for these particular test, however, how do I mocks (or set) the HttpContext for my test without using any Moq framework?
I need to able to do something similar to this, without Moq of course:
var mockHttpContext = new Mock<ControllerContext>();
mockHttpContext.SetupGet(p => p.HttpContext.User.Identity.Name).Returns("n1\test");
mockHttpContext.SetupGet(p => p.HttpContext.Request.IsAuthenticated).Returns(true);
So I've got this method called LoginUser:
public void LoginUser(out SystemUser userToLogin, string username)
Having just started with Rhino Mocks, I'm having a little trouble mocking a call and return value from this method while testing my Presenter code. What's the correct syntax in this instance?
I'm writing unit tests in ASP.NET 4.0 web application (ASP.NET Forms, not MVC). There are several spots in the code where I call the ServerVariables collection to call variables like REMOTE_ADDR. Since my unit tests do not actually initiate HttpRequests when executing my code, things like ServerVariables are Null and therefore error when I try to call HttpContext.Current.Request.ServerVariables("REMOTE_ADDR")
All the solutions I've found to address this issue refer to MVC and so they assume that HttpRequest derives from HttpRequestBase, which it does in MVC but not in ASP.NET Forms.I tried using Moq but you can't mock a sealed class, and HttpRequest is unfortunately sealed with no interface.