C# – Copying HTTP request parameters in call to RedirectToAction

I have been learning C# over the past year and today I encountered a situation with Controller.RedirectToAction() that I took awhile to find a solution to so I wanted to write down my solution.

In my case, I was in a method in a Controller (accessed from a HTTP GET) and needed to invoke RedirectToAction().  However, as part of the call to RedirectToAction() I needed to send along all the HTTP request parameters.

First of all, this is the method in the class FirstController that handled the initial GET request:

[HttpGet]
public ActionResult HandleRequest1() 
{
  // Create a dictionary containing the query string parameters
   var queryStringParams = this.Request.QueryString.AsRouteValueDictionary();
  // Pass the queryStringParams dictionary to RedirectToAction
   return this.RedirectToAction<SecondController>(x => x.HandleRequestTwo(), queryStringParams);
}

Second, this is the method in the class SecondController that was redirectedTo:

public ActionResult HandleRequestTwo() 
{
  string urlParamsStr = HttpContext.Request.Params.ToString();
  NameValueCollection queryParams = HttpUtility.ParseQueryString(urlParamsStr);
  string value1= queryParams["paramKey1"];
  //...
  return new View("SecondView");
}

In the end, it was creating a Dictionary that solved the problem.

Posted in C# | Tagged | Leave a comment

Unit Test Stubs – Returning different values on consecutive calls

I have been learning C# these past few months.  The other day I had to write a unit test in C# that would return different results on consecutive calls from a mocked method where the inputs were the same.  With my Java background, I was familiar with how to do this with the Java mocking libraries such as JMock and Mockito.

For example, in JMock:

String someInput = "test input";
atLeast(1).of (myMockObject).myMethod(someInput);
  will(onConsecutiveCalls(  
  returnValue("one"),
  returnValue("two"),
  returnValue("three")));

And using Mockito:

String someInput = "test input";
when(myMockObject.myMethod(someInput ))
  .thenReturn("one", "two", "three");

But in C# using Moq, it is not nearly as concise.  A few different steps need to be taken.

  1. Create a variable to track the number of time the method has been invoked.
  2. Create an instance of a Func that will determine what to return each time it is invoked.
  3. In the call to Setup(), hand it the Func instance you just created and then also create a Callback to increment the counter created in step 1.

Here is an example:

var numCalls = 0;
Func<string> determineResponse = () =>
{
  if (numCalls == 0) {
    return "one";
  }  else {
    return "two;
  }
};
string someInput = "test input";
myMockObject.Setup(r => r.myMethod(someInput)).Returns(determineResponse).Callback(() => numCalls++);

Perhaps there is a simpler way in C# and Moq, but I have not found it.

Posted in C#, Moq | Tagged , | Leave a comment

Visual Studio 2010 – error: Unable to open the Web site

I was setting up Visual Studio 2010 to hook up with an existing .NET project that existed in source control.  When I tried to open the solution file in VS 2010, I received the following error (My .sln file exists in D:\data\AppName directory):

D:\data\Static\website : error  : Unable to open the Web site 'D:\data\AppName\website'.  The Web site 'D:\data\AppName\website' does not exist.

In this case, the “website” directory is a project with Javascript, CSS and images.  It is not a .NET project.

After searching and searching, I finally found a suggestion that I needed to delete the .suo file in the same directory as my solution file (.sln file), which I did  Then I re-opened the solution in VS 2010 and the path was resolved correctly to the Web site project.

The error was even more confusing as the path D:\data\Static\website is correct.  I still don’t know why VS 2010 was trying to find it in D:\data\AppName\website.  But deleting the .suo file worked and I am moving forward now!

Posted in Visual Studio | Tagged , | 1 Comment

Error running unit tests in Eclipse

I was using Eclipse to run my project’s unit tests and I received this error right away:

The project: MyDependantProject which is referenced on the classpath, does not exist.

I took a look at my projects Java Build Path configuration, and “MyDependantProject” was listed there.

Next, I took a look at the JUnit Run Configuration.  This was more alarming as look at the blank line.  That was where I should have saw “MyDependantProject” listed:

run_config

I went back to my Java Build Path and I removed “MyDependantProject” in attempt to force a different error (as I thought once I re-added it, that blank line above would go away).  This time when I ran my unit tests, I received this error:

org.eclipse.jdt.internal.core.JavaModel cannot be cast to org.eclipse.jdt.core.IJavaProject

The combination of these two errors made me reflect upon my workspace.  I knew I had just created this Eclipse workspace the other day.  I looked a little closer and I realized that  the name of my workspace was the same as the name of one of my projects in the workspace.

Searching Google, you will find doing this will cause a myriad of problems that manifest in different ways.   So my solution was just to rename my workspace to something that was not the name one of the projects.

Posted in Miscellaneous | Tagged | Leave a comment

Eclipse and Tomcat start up error – Error configuring application listener

Since it is now the second time I have encountered this problem while starting up Tomcat, I thought I would write down the solution so I actually remember it.

First of all, here is the error I received when starting up a Tomcat 6 server from within Eclipse:

Jan 29, 2013 12:27:39 PM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Error configuring application listener of class com.wall.steve.infrastructure.logging.LoggingInitializerServletContextListener
java.lang.ClassNotFoundException: com.wall.steve.infrastructure.logging.LoggingInitializerServletContextListener

       at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1680)
       at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1526)
       at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4149)
       at org.apache.catalina.core.StandardContext.start(StandardContext.java:4705)
       at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057)
       at org.apache.catalina.core.StandardHost.start(StandardHost.java:840)
       at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057)
       at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:463)
       at org.apache.catalina.core.StandardService.start(StandardService.java:525)
       at org.apache.catalina.core.StandardServer.start(StandardServer.java:754)
       at org.apache.catalina.startup.Catalina.start(Catalina.java:595)
       at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
       at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
       at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
       at java.lang.reflect.Method.invoke(Method.java:597)
       at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
       at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
Jan 29, 2013 12:27:39 PM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Error configuring application listener of class org.springframework.web.context.ContextLoaderListener
java.lang.NoClassDefFoundError: org/springframework/context/ConfigurableApplicationContext
       at java.lang.Class.getDeclaredConstructors0(Native Method)
       at java.lang.Class.privateGetDeclaredConstructors(Class.java:2389)
       at java.lang.Class.getConstructor0(Class.java:2699)
       at java.lang.Class.newInstance0(Class.java:326)
       at java.lang.Class.newInstance(Class.java:308)
       at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4150)
       at org.apache.catalina.core.StandardContext.start(StandardContext.java:4705)
       at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057)
       at org.apache.catalina.core.StandardHost.start(StandardHost.java:840)
       at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057)
       at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:463)
       at org.apache.catalina.core.StandardService.start(StandardService.java:525)
       at org.apache.catalina.core.StandardServer.start(StandardServer.java:754)
       at org.apache.catalina.startup.Catalina.start(Catalina.java:595)
       at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
       at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
       at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
       at java.lang.reflect.Method.invoke(Method.java:597)
       at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
       at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)

To fix the issue, in Eclipse’s Servers view, right click on the server you are trying to start and choose “Clean…”.

Once that completes, re-start your server and the problem should go away.

Posted in Tomcat | Tagged , | 3 Comments

File Not Found Error Installing Android Support Library

I was going through the Google Android tutorial for creating your first Android project when I came to the final step (Step 5) in “Creating a Project with Eclipse”.  I was at the final step in the Eclipse wizard to create an Android project and when I clicked finish I found out I did not have the Android Support Library installed.  I tried, and failed, to install it from withing Eclipse.  This was the error I received in the console:

Downloading Android Support Library, revision 10
File not found: C:\Program Files (x86)\Android\android-sdk\temp\support_r10.zip (Access is denied)

Done. Nothing was installed.

Next, I tried to install it using the Android SDK Manager (Extras -> Android Support Library).  I received the same error.

I looked a little closer at the error and saw the “Access is denied” error.  I restarted the Android SDK Manager, this time though I ran it as Administrator.  This time the Android Support Libary installed without any problems.

Posted in Android | Tagged | Leave a comment

Using Echo in Ant to see the classpath

In trying to run unit tests (using JUnit) from Ant some tests were failing due to what appeared to be classpath issues.  I needed to see what all my classpath property contained.  I discovered the pathconvert Ant task.

Here is how I used it in my build file:

<!-- junit.classpath is what I want to see -->
<path id="junit.classpath">
  <fileset dir="lib">
    <include name="**/*.jar"/>
  </fileset>
  <path refid="test.mockinputfiles"/>
  <pathelement path="${dir.binaries}" />
</path>

<!-- Use pathconvert to put the output in to the echo.classpath property -->
<pathconvert pathsep="${line.separator}| |-- "
  property="echo.classpath"
  refid="junit.classpath">
</pathconvert>

<echo message="|-- JUnit Classpath"/>
<echo message="| |"/>
<echo message="| |-- ${echo.classpath}"/>

<junit fork="on" forkmode="once" haltonfailure="false" showoutput="on" printsummary="on" failureproperty="tests.failed">
  <classpath>
    <path refid="junit.classpath"/>
  </classpath>
  <!-- Other junit properties -->
</junit>
Posted in Ant | Tagged | Leave a comment