Posts By Chris Tesene

HttpContext and MVC TDD / Unit Testing

I’ve been working in and out of TDD, but I keep hitting roadblocks. HttpContext is just another roadblock. I was lucky enough to find this post from Scott Hanselman, and the MVC HttpContext Helper for MOQ. The problem is that since the posting, MOQ has changed its API, so I updated the code and posted it below. Hope it helps someone :)

public static class MvcMockHelpers
    {
        public static HttpContextBase FakeHttpContext()
        {
            var context = new Mock();
            var request = new Mock();
            var response = new Mock();
            var session = new Mock();
            var server = new Mock();

            context.Setup(ctx => ctx.Request).Returns(request.Object);
            context.Setup(ctx => ctx.Response).Returns(response.Object);
            context.Setup(ctx => ctx.Session).Returns(session.Object);
            context.Setup(ctx => ctx.Server).Returns(server.Object);

            return context.Object;
        }

        public static HttpContextBase FakeHttpContext(string url)
        {
            HttpContextBase context = FakeHttpContext();
            context.Request.SetupRequestUrl(url);
            return context;
        }

        public static void SetFakeControllerContext(this Controller controller)
        {
            var httpContext = FakeHttpContext();
            ControllerContext context = new ControllerContext(new RequestContext(httpContext, new RouteData()), controller);
            controller.ControllerContext = context;
        }

        static string GetUrlFileName(string url)
        {
            if (url.Contains("?"))
                return url.Substring(0, url.IndexOf("?"));
            else
                return url;
        }

        static NameValueCollection GetQueryStringParameters(string url)
        {
            if (url.Contains("?"))
            {
                NameValueCollection parameters = new NameValueCollection();

                string[] parts = url.Split("?".ToCharArray());
                string[] keys = parts[1].Split("&".ToCharArray());

                foreach (string key in keys)
                {
                    string[] part = key.Split("=".ToCharArray());
                    parameters.Add(part[0], part[1]);
                }

                return parameters;
            }
            else
            {
                return null;
            }
        }

        public static void SetHttpMethodResult(this HttpRequestBase request, string httpMethod)
        {
            Mock.Get(request)
                .Setup(req => req.HttpMethod)
                .Returns(httpMethod);
        }

        public static void SetupRequestUrl(this HttpRequestBase request, string url)
        {
            if (url == null)
                throw new ArgumentNullException("url");

            if (!url.StartsWith("~/"))
                throw new ArgumentException("Sorry, we expect a virtual url starting with "~/".");

            var mock = Mock.Get(request);

            mock.Setup(req => req.QueryString)
                .Returns(GetQueryStringParameters(url));
            mock.Setup(req => req.AppRelativeCurrentExecutionFilePath)
                .Returns(GetUrlFileName(url));
            mock.Setup(req => req.PathInfo)
                .Returns(string.Empty);
        }
    }

, ,

Windows Server 2008 – Backup to USB Drive == FAIL

So if you purchase a newer USB 2.0/3.0 drive and try to use Windows Server 2008 backup, it might fail, stating there is an IO error.

The reason is due to the sector size of the drives. The OS expects 512, and most of the new drives are 4096.

Tried the HotFix below, didn’t work.

http://support.microsoft.com/kb/982018

Tried to backup to the same drive but via Network share, same issue. :(

Found the link below that has drive compatibility.

http://social.technet.microsoft.com/wiki/contents/articles/1780.aspx

 

 

 


Visual Studio 2010 : Issue with moving solution from a TFS server you cannot connect to

So I searched for a little while, and finally found the solution below. Lifesaver!

http://gregdoesit.com/2009/01/tfs-deleting-old-workspaces/


TFS 2010 running on a machine that was promoted to Domain Controller

After upgrading my tfs box to DC, my dev machine would no longer connect to TFS. The solution was to connect to the url https://servername:8080/tfs via Internet Explorer and enter my credentials. Then I was able to use TFS as usual inside of Visual Studio.


Web Listings Inc = FRAUD

I recently had a customer receive an envelope in the mail that seemed to be an invoice for one of their domains.

When they opened it up they found what appeared to be a bill for $65.00 from a company called Web Listings Inc., offering domain name submission to 20 established search engines, up to eight keyword/phrase listings, and a quarterly search engine position and ranking reports for 1 year.

As you can see in the images below, the intent here is to fool the reader into thinking that it is, in fact, an invoice that needs to be paid. Web Listings Inc. is sadly preying on unsuspecting domain owners in hopes they can get you to part with $65.00 of your hard earned money.

Web Listings Inc. states that they will submit your domain to 20 top search engines. Sorry to break it to you guys, there are only 3 top search engines! If you received one of these fake invoices, our advice is to just throw it in the trash! Their phony invoices are actually sign-up forms for a service that has absolutely no valid purpose for existing.


I am now a member of Elance.com’s Joomla Experts.

I recently passed the test to become a member of the Elance.Com’s Joomla! Experts Group. There are less than 700 members of the group world-wide.

To become a member of this group, Elance providers must pass the Joomla! Programming and the Joomla! 1.5 skill test offered by Elance.


Joomla article PDF Icon displays blank page

There has been numerous threads on this issue, with no solid resolution. I found a FREE component/plugin that will allow the PDF feature of Joomla to work, and has some great customization features.

The component is called PhocaPDF, and was created by Phoca you can view a demo here.


ASP.NET MySQL Role Provider Issues

So while attempting to configure another MySQL powered ASP.NET site, I encountered an issue with the Role provider. I was able to add roles via the ASP.NET Web Site Administration Tool, but they would not show up. Also the Roles.Count was 0.

After some searching, I found that in my Web.Config, the providers type was only set as below :

type=MySql.Web.Security.MySQLRoleProvider, MySql.Web

and was missing the version, culture, and publickeytoken. After I added the info below, everything worked great.   

type=MySql.Web.Security.MySQLRoleProvider, MySql.Web, Version=6.3.2.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d

 

 

 


ASP.NET VB Web Application Profile Provider Fix

I recently stumbled into an issue while attempting to use the built in ASP.NET Profile Provider with a MySQL database. The issue is that Web Applications do NOT create the ProfileCommon class. But you can create it. Below is a sample taken from steeleprice.net

[codesyntax lang="vbnet"]

Public Class UserProfile
Inherits ProfileBase
Public Shared Function GetUserProfile(ByVal username As String) As UserProfile
Return CType(Create(username), ProfileBase)
End Function
Public Shared Function GetUserProfile() As UserProfile
Return CType(Create(Membership.GetUser().UserName), ProfileBase)
End Function
_
Public Property Description() As String
Get
Return TryCast(MyBase.GetPropertyValue("Description"), String)
End Get
Set(ByVal value As String)
MyBase.SetPropertyValue("Description", value)
End Set
End Property
_
Public Property Location() As String
Get
Return TryCast(MyBase.GetPropertyValue("Location"), String)
End Get
Set(ByVal value As String)
MyBase.SetPropertyValue("Location", value)
End Set
End Property
_
Public Property FavoriteMovie() As Integer
Get
Return CInt(MyBase.GetPropertyValue("FavoriteMovie"))
End Get
Set(ByVal value As Integer)
MyBase.SetPropertyValue("FavoriteMovie", value)
End Set
End Property
End Class

[/codesyntax]

When using this approach in VB, I still get some occasional errors in the designer when using SplitView, a recompile makes these go away and the code does indeed run fine.  It seems to be something in the background compiler… I wish Microsoft would fix this silly 4 year old bug.

Anyway, I really like this approach MUCH better than placing the profile data in web.config.  If you are relying on the code and some genius decides to add a field or change the name it will cause any dependent code to go haywire anyway when the CodeSpit is regenerated.

When I am controlling the Fields in Code (where it should be anyway…) That is not a major concern since we know what we are doing when the code changes and its not in an editable file by someone not actually Testing the code.

Therefore, all the other methods have many problems that just aren’t worth dealing with when this is simple, elegant, effective and safe.

I also find it much easier to just use an instance rather than some other suggestions of using a Property in a BasePage.

i.e

Dim prof = UserProfile.GetUserProfile()
or
Dim prof = UserProfile.GetUserProfile(username)

I also found that turning off Automatic updates seems to help with the errors for some reason, with it turned off, I don’t seem to get them any more and thus you need to do your saves with an instance or you will have to perform a save after changing any item since getuserprofile will overwrite any unwritten changes to the object because it is creating a new instance every time.

So my resulting web.config looks like this:

<profile automaticSaveEnabled=”false”
enabled=”true”
inherits=”ProfileUtility.UserProfile”>

This is for the Default Provider, if you use  Custom Provider as well, use the following:
<profile defaultProvider=”<YourProviderName>”
automaticSaveEnabled=”false”
enabled=”true”
inherits=”ProfileUtility.UserProfile”>


ASP.NET Delete Forms Authentication Schema – MySQL

When using MySQL as your membership provider for an ASP.NET project, you often want to reset the users db. To do this, simply run the MySQL query below, and ensure that the autoGenerateSchema=true in your web.config.

DROP TABLE my_aspnet_applications;
DROP TABLE my_aspnet_membership;
DROP TABLE my_aspnet_profiles;
DROP TABLE my_aspnet_roles;
DROP TABLE my_aspnet_schemaversion;
DROP TABLE my_aspnet_users;
DROP TABLE my_aspnet_usersinroles;
Note, this will delete all of the tables, and they will be re-created by the autogenerateschema, if you do not want to delete the tables, you can run the query below, which will truncate the tables.
TRUNCATE TABLE my_aspnet_applications;
TRUNCATE TABLE my_aspnet_membership;
TRUNCATE TABLE my_aspnet_profiles;
TRUNCATE TABLE my_aspnet_roles;
TRUNCATE TABLE my_aspnet_schemaversion;
TRUNCATE TABLE my_aspnet_users;
TRUNCATE TABLE my_aspnet_usersinroles;