NancyFx not reaching module using Owin Hosting - nancy

I am trying to create a really simple NancyFx project using OWIN hosting.
Nancy appears to be running because I get the 404 that comes with Nancy by default, but none of my modules are ever reached.
Here is what I have so far.
It is probably something really obvious.
Startup.cs
public class Startup
{
public void Configuration(IAppBuilder builder)
{
builder.UseNancy();
}
}
Program.cs
class Program
{
static void Main(string[] args)
{
using (WebApplication.Start<Startup>("http://+:8080"))
{
Console.WriteLine("Press enter to exit");
Console.ReadLine();
}
}
}
HelloWorld.cs
class HelloWorld : Nancy.NancyModule
{
public HelloWorld()
{
Get["/"] = parameters =>
{
return "Hello World!";
};
}
}
Thanks for the help in advance!

You need to make your module public, right now it's private

Related

Issue when using Salesforce ConnectAPI.CommerceSearchSettings

I got requirement to recalculate B2B Webstore index programatically.
Found documentation here: https://developer.salesforce.com/docs/atlas.en-us.232.0.apexref.meta/apexref/apex_ConnectAPI_CommerceSearchSettings_static_methods.htm#apex_ConnectAPI_CommerceSearchSettings_postCommerceSearchIndex_2
But when trying to save class (API 52.0) :
public with sharing class B2B_SearchRecalculation {
public static void recalculate() {
ConnectApi.CommerceSearchIndex xyz = ConnectApi.CommerceSearchSettings.postCommerceSearchIndex('XYZ');
}
}
I am getting an error:
B2B_SearchRecalculation.cls Method does not exist or incorrect signature: void postCommerceSearchIndex(String) from the type ConnectApi.CommerceSearchSettings (5:80)
Please support.
public with sharing class B2B_SearchRecalculation {
public static void recalculate()
{
ConnectApi.CommerceSearchIndex xyz =
ConnectApi.CommerceSearchSettings.createCommerceSearchIndex('webstoreid');
}
}

Selenium Webdriver C# - Running more than one test case in VS 2017 from Test Suite

I have been working on Page Object Framework which will have categorized test suites depending on the page. I have followed all steps in order to build a decent framework.
My each Unit Test, contains one method which follows simple steps. So far I have been able to create a few automated test cases. The issue began when I wanted to run more than one test case from the test suite. I have one chrome web driver instance which is in a separate class. Below is an example:
using System;
using System.Dynamic;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
namespace SystemUiAutomationTestFramework
{
public static class Browser
{
private static readonly IWebDriver _webDriver = new ChromeDriver(Properties.Settings.Default.ChromePathDriver);
public static IWebDriver WebDriver {
get { return _webDriver; }
}
public static ISearchContext Driver
{
get { return _webDriver; }
}
public static string Url
{
get { return _webDriver.Url; }
}
public static string Title
{
get { return _webDriver.Title; }
}
public static void Goto(string url)
{
_webDriver.Manage().Window.Maximize();
_webDriver.Url = url;
}
public static void Close()
{
_webDriver.Quit();
}
}
}
Each test case when it is run is independent and as good practice shows, there should be no test order implementation because it generates flows. I will place two examples which check simple login operation and login validation.
Below you can find a class for the login page:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.AccessControl;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.PageObjects;
using OpenQA.Selenium.Support.UI;
namespace SystemUiAutomationTestFramework
{
public class LoginPage
{
static string Url = "http://..";
private static string LoginUrl = "http://...";
private static string PageTitle = "System title page";
private static string LoginPlaceholder = "Login";
private static string PswdPlaceholder = "Password";
private static string ButtonText = "Sign in";
private static string ErrorMessage = "Wrong login or password";
/* LoginPage Elements */
[FindsBy(How = How.Id, Using = "inputLogin")]
private IWebElement inputLogin;
[FindsBy(How = How.Id, Using = "inputPassword")]
private IWebElement inputPassword;
[FindsBy(How = How.TagName, Using = "button")]
private IWebElement loginButton;
[FindsBy(How = How.ClassName, Using = "errorMsg")]
private IWebElement errorMessage;
/*----------------------------------------*/
public void Goto()
{
Browser.Goto(Url);
}
public bool IsAtLoginPage()
{
return Browser.Url == LoginUrl;
}
public bool IsAtLoginPageTitle()
{
return Browser.Title == PageTitle;
}
public bool IsAtLoginField()
{
return inputLogin.GetAttribute("placeholder") == LoginPlaceholder;
}
public bool IsAtPswdField()
{
return inputPassword.GetAttribute("placeholder") == PswdPlaceholder;
}
public bool IsAtLoginButton()
{
return loginButton.Text == ButtonText;
}
public void InputCredentials(string userName, string userPassword)
{
inputLogin.SendKeys(userName);
inputPassword.SendKeys(userPassword);
loginButton.Click();
}
public void WaitErrorMessage()
{
WebDriverWait wait = new WebDriverWait(Browser.WebDriver, TimeSpan.FromSeconds(10));
wait.Until(ExpectedConditions.VisibilityOfAllElementsLocatedBy(By.ClassName("errorMsg")));
}
public bool IsAtErrorMessage()
{
return errorMessage.Text == ErrorMessage;
}
public void ReportPageSuccessLogin()
{
Console.WriteLine("Application Url checked");
Console.WriteLine("Application Title checked");
Console.WriteLine("Login Field present");
Console.WriteLine("Password Field checked");
Console.WriteLine("Sign in button checked");
Console.WriteLine("Login ssuccess");
}
public void ReportPageValidationTest()
{
ReportPageSuccessLogin();
Console.WriteLine("Fake Credentials entered");
Console.WriteLine("Login Button Pressed");
Console.WriteLine("Login or Password validation message displayed: " + errorMessage.Displayed);
}
}
}
I also have an API class for Pagefactoring. As an example:
public static class Pages
{
public static LoginPage LoginPage
{
get
{
var loginPage = new LoginPage();
PageFactory.InitElements(Browser.Driver, loginPage);
return loginPage;
}
}
Now for the test cases, below an example when a user is on the login page, all elements are displaed, logs into the system, system checks if the user has logged into and closes the instance.
using System;
using System.Runtime.Remoting.Channels;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using SystemUiAutomationTestFramework;
namespace TestSuite.LoginPage
{
[TestClass]
public class LoginPageTest
{
[TestMethod]
public void Can_Go_LoginPage()
{
Pages.LoginPage.Goto();
Assert.IsTrue(Pages.LoginPage.IsAtLoginPage());
Assert.IsTrue(Pages.LoginPage.IsAtLoginPageTitle());
Assert.IsTrue(Pages.LoginPage.IsAtLoginField());
Assert.IsTrue(Pages.LoginPage.IsAtPswdField());
Assert.IsTrue(Pages.LoginPage.IsAtLoginButton());
Pages.LoginPage.InputCredentials(SettingsService.Username, SettingsService.Userpassword);
Pages.HomePage.IsAtHomePage();
Pages.LoginPage.ReportPageSuccessLogin();
}
[TestCleanup]
public void CleanUp()
{
Browser.Close();
}
}
}
The other one just validates the login page by providing fake login and password and if the error message is correctly displayed the test case finishes also by closing the instance.
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using SystemUiAutomationTestFramework;
namespace TestSuite.LoginPage
{
[TestClass]
public class LoginPageValidationTest
{
[TestMethod]
public void Can_Validate_LoginPage()
{
Pages.LoginPage.Goto();
Assert.IsTrue(Pages.LoginPage.IsAtLoginPage());
Assert.IsTrue(Pages.LoginPage.IsAtLoginPageTitle());
Assert.IsTrue(Pages.LoginPage.IsAtLoginField());
Assert.IsTrue(Pages.LoginPage.IsAtPswdField());
Assert.IsTrue(Pages.LoginPage.IsAtLoginButton());
Pages.LoginPage.InputCredentials("abcd.efgh", "test123");
Pages.LoginPage.WaitErrorMessage();
Assert.IsTrue(Pages.LoginPage.IsAtErrorMessage());
Pages.LoginPage.ReportPageValidationTest();
}
[TestCleanup]
public void CleanUp()
{
Browser.Close();
}
}
}
Now the issue happens when I try those two test cases from the Login Page Test Suite, one finishes as passed the other one as failed. From the error message, I understand that it is because the other test case is trying to use an instance of the Webdriver which is already running.
I would like to know your opinion/guides/solution how can I solve this problem. I apologize for the long post but I thought that if I place my code it will be easy for you to understand my issue.
Best regards and thank you for your answers or linking me to the topic which either a duplicate of my issue or there is a solution already for it.
I was able to solve the issue on my own. I have created an
property for my driver class and an Initialize method which is called each time a test class is called. Also refactored my code to be more flexible.

Camel blueprint testing and cucumber

Is it possible to combine cucumber with CamelBlueprintTestSupport? I have my runner class:
#RunWith(Cucumber.class)
#CucumberOptions(monochrome=true,
format={ "pretty", "html:target/cucumber"},
features = "C:/Users/Developer/workspace_camel/SRV002_PatronInformation/src/test/resources/cucumber/asynchronousErrorHandling.feature")
public class RunFeature_SRV002_PatronInformationTest {
}
and my blueprint test class with the scenarios:
public class SRV002_PatronInformationScenarioTest extends CamelBlueprintTestSupport {
#Override
protected String getBlueprintDescriptor() {
return "/OSGI-INF/blueprint/blueprint.xml";
}
#Given("^client communicates asynchronous via socket$")
public void client_communicates_asynchronous_via_socket() throws Throwable {
System.out.println("test");
}
#When("^client posts message$")
public void an_error_occurs_inside_the_integration() throws Throwable {
String endpoint = "netty4:tcp://localhost:5000?sync=false&textline=true";
template.sendBody(endpoint, "test");
}
#Then("^the integration should not return response to the client$")
public void the_integration_should_not_return_the_error_to_the_client() throws Throwable {
System.out.println("test");
}
}
The problem now is that, when I run this I run into nullpointerexception at template.sendbody because the context, bundle and routes haven't started. For some reason it seems adding #RunWith(Cucumber) prevents the camel routes from starting.
Anyone knows how this can be solved? Thanks
Souciance
Ok so I managed to solve this.
For reference look here:
http://camel.465427.n5.nabble.com/How-to-test-routes-when-using-another-TestRunner-td5772687.html
Thanks to Gregor Lenz for the help.
Essentially the key here is that in your Camel BlueprintTestSupport class, inside the test method, that starts the given scenario you need to add this.setUp(). See the code below:
In Cucumber
SRVXXX_FileTransferCamelRunner filetransfer = new SRVXXX_FileTransferCamelRunner();
#Given("^an input file$")
public void an_input_file() throws Throwable {
endpoint.append("file:C:/Camel/input?fileName=input.txt");
}
#When("^client puts the file in the input directory$")
public void client_puts_the_file_in_the_input_directory() throws Throwable {
filetransfer.testPutFile(fileData.toString(), endpoint.toString());
}
#Then("^the integration should move the file to the output directory$")
public void the_integration_should_move_the_file_to_the_output_directory() throws Throwable {
String outputPath = "C:/Camel/output/input.txt";
filetransfer.testFileHasMoved(outputPath);
}
In Camel
#Test
public void testPutFile(String body, String endpoint) throws Exception {
this.setUp();
template.sendBody(endpoint,body);
Thread.sleep(2000);
assertFileNotExists(endpoint);
}

"Authentication Failure" when calling a method on Remote Object in wpf

I am developing an application which uses WindowsFormsApplicationBase to enforce Single Instance. I get the following error when calling a method on a Remote object. It works fine if I don't use Single Instance approach.
System.Runtime.Remoting.RemotingException: Authentication failure ---> System.IO.IOException: Unable to read data from the transport connection: The connection was closed.
at System.Net.Security.NegoState.ProcessAuthentication(LazyAsyncResult lazyResult)
at System.Net.Security.NegotiateStream.AuthenticateAsClient(NetworkCredential credential, String targetName, ProtectionLevel requiredProtectionLevel, TokenImpersonationLevel allowedImpersonationLevel)
at System.Runtime.Remoting.Channels.Tcp.TcpClientTransportSink.CreateAuthenticatedStream(Stream netStream, String machinePortAndSid)
Here is my Code:
public class EntryPoint
{
[STAThread]
public static void Main(string[] args)
{
SingleInstanceManager sim = new SingleInstanceManager();
sim.Run(args);
}
}
public class SingleInstanceManager : WindowsFormsApplicationBase
{
private App app;
public SingleInstanceManager()
{
IsSingleInstance = true;
}
protected override bool OnStartup(Microsoft.VisualBasic.ApplicationServices.StartupEventArgs eventArgs)
{
app = new App();
app.InitializeComponent();
app.Run();
return false;
}
protected override void OnStartupNextInstance(StartupNextInstanceEventArgs eventArgs)
{
base.OnStartupNextInstance(eventArgs);
app.Activate();
}
}
This is how I am invoking the Remoting object:
public Hashtable GetData(string[] arg1, string[] arg2)
{
IDataProvider dataProvider = (IDataProvider )Activator.GetObject(typeof(IDataProvider ), "tcp://.....");
Hashtable data = dataProvider.GetData(arg1, arg2);
return data;
}
Thanks in advance.
I found the solution myself.
I used the following to implement single instance(http://www.ai.uga.edu/mc/SingleInstance.html).
[STAThread]
static void Main() // args are OK here, of course
{
bool ok;
m = new System.Threading.Mutex(true, "YourNameHere", out ok);
if (! ok)
{
MessageBox.Show("Another instance is already running.");
return;
}
Application.Run(new Form1()); // or whatever was there
GC.KeepAlive(m); // important!
}

Google app engine JRE Class "Black List"

There is a "JRE Class White List" for the Google App Engine.
What I would really like is a "Black List" -- in other words, Java APIs that will not work on GAE. Does such a list exist? Have any developers run into problems with Java APIs on GAE?
It seems that they've taken more of a white-list approach: http://code.google.com/appengine/docs/java/jrewhitelist.html.
There is also more detail about the sandbox (what files it can access and so on) here: http://code.google.com/appengine/docs/java/runtime.html#The_Sandbox
The restrictions seem to be pretty intuitive (like restricted filesystem access, no JNI, etc).
I got a card advertising this service at Google I/O:
LTech AppEngine Compatibility Analyzer
Sounds like it might be of use to you. I have not tried it, if you do try it, please come back and comment. Thanks!
i use Servlet in my GAE project, however it is not in the whitelist even when it will work without any problem. In fact, Google mention how to use Servlet but it is not in the whitelist
import javax.servlet.http.*;
Mentioned here:
http://code.google.com/appengine/docs/java/runtime.html
but not included here:
http://code.google.com/appengine/docs/java/jrewhitelist.html
I love GAE (because the free quota) but the documentation is a mess.
I use IntelliJ and it mark as an error when the import not in the whitelist. However, it is possible to disable it.
I was looking for something when i came across this query and so thought to share the details on the black & white list of GAE(Google App Engine) so anyone getting such issue could address it properly. Details :-
appengine-agentruntime.jar has two instance variables as :-
private static Agent agent
private static Set<String> blackList
We getting blackList from agent & agent = AppEngineDevAgent.getAgent(). So if we check b) appengine-agent.jar we can find agent is Class<?> implClass = agentImplLoader.loadClass("com.google.appengine.tools.development.agent.impl.AgentImpl");
And then going to AgentImpl class i.e. c) appengine-agentimpl.jar we can
see blacklist variable getting populated at class load with the static initialization & it refers Whitelist for filtering the allowed classes.
static {
initBlackList();
}
public static Set<String> getBlackList() {
return blackList;
}
private static boolean isBlackListed(String className) {
Set<String> whiteList = WhiteList.getWhiteList();
return (!whiteList.contains(className))
&& (!className.startsWith("com.sun.xml.internal.bind."));
}
Finally can check d) appengine-tools-sdk-1.8.3.jar for list of all WhiteList classes.
Conclusion: As a hack in order to use any JRE class which do not belong to this WhiteList one need to play around either with the WhiteList or with the BlackList. A possible hack would be if you unjar the appengine-agentruntime.jar library & comment the content of reject method as
public static void reject(String className) {
/*throw new NoClassDefFoundError(className + " is a restricted class. Please see the Google " + " App Engine developer's guide for more details.");*/
}
And then again jar it and use in your project.Hope it helps.
-----------------------------------------------------------------------------
a) appengine-agentruntime.jar :- It holds the actual Runtime class which throws exception (from reject method) for classes which do not belong to above white list.
package com.google.appengine.tools.development.agent.runtime;
import com.google.appengine.tools.development.agent.AppEngineDevAgent;
import com.google.appengine.tools.development.agent.impl.Agent;
import com.google.apphosting.utils.clearcast.ClearCast;
//REMOVED OTHER IMPORTS TO KEEP IT SHORT
public class Runtime {
private static Agent agent = (Agent) ClearCast.cast(
AppEngineDevAgent.getAgent(), Agent.class);
private static Set<String> blackList = agent.getBlackList();
public static ClassLoader checkParentClassLoader(ClassLoader loader) {
ClassLoader systemLoader = ClassLoader.getSystemClassLoader();
return (loader != null) && (loader != systemLoader) ? loader
: Runtime.class.getClassLoader();
}
public static void recordClassLoader(ClassLoader loader) {
agent.recordAppClassLoader(loader);
}
public static void reject(String className) {
throw new NoClassDefFoundError(className
+ " is a restricted class. Please see the Google "
+ " App Engine developer's guide for more details.");
}
private static boolean isBlackListed(Class klass) {
String className = klass.getName().replace('.', '/');
return blackList.contains(className);
}
// REMOVED OTHER METHODS TO KEEP IT SHORT
}
b) appengine-agent.jar :-
package com.google.appengine.tools.development.agent;
import com.google.apphosting.utils.clearcast.ClearCast;
//REMOVED OTHER IMPORTS TO KEEP IT SHORT
public class AppEngineDevAgent {
private static final String AGENT_IMPL = "com.google.appengine.tools.development.agent.impl.AgentImpl";
private static final String AGENT_IMPL_JAR = "appengine-agentimpl.jar";
private static final Logger logger = Logger.getLogger(AppEngineDevAgent.class.getName());
private static Object impl;
public static void premain(String agentArgs, Instrumentation inst) {
URL agentImplLib = findAgentImplLib();
URLClassLoader agentImplLoader = new URLClassLoader(
new URL[] { agentImplLib }) {
protected PermissionCollection getPermissions(CodeSource codesource) {
PermissionCollection perms = super.getPermissions(codesource);
perms.add(new AllPermission());
return perms;
}
};
try {
Class<?> implClass = agentImplLoader
.loadClass("com.google.appengine.tools.development.agent.impl.AgentImpl");
impl = ((AgentImplStruct) ClearCast.staticCast(implClass,
AgentImplStruct.class)).getInstance();
AgentImplStruct agentImplStruct = (AgentImplStruct) ClearCast.cast(
impl, AgentImplStruct.class);
agentImplStruct.run(inst);
} catch (Exception e) {
logger.log(
Level.SEVERE,
"Unable to load the App Engine dev agent. Security restrictions will not be completely emulated.",
e);
}
}
public static Object getAgent() {
return impl;
}
//REMOVED OTHER METHODS TO KEEP IT SHORT
}
c) appengine-agentimpl.jar :-
package com.google.appengine.tools.development.agent.impl;
import com.google.apphosting.runtime.security.WhiteList;
//REMOVED OTHER IMPORTS TO KEEP IT SHORT
public class BlackList {
private static final Logger logger = Logger.getLogger(BlackList.class.getName());
private static Set<String> blackList = new HashSet();
static {
initBlackList();
}
public static Set<String> getBlackList() {
return blackList;
}
private static boolean isBlackListed(String className) {
Set<String> whiteList = WhiteList.getWhiteList();
return (!whiteList.contains(className))
&& (!className.startsWith("com.sun.xml.internal.bind."));
}
private static void initBlackList() {
Set<File> jreJars = getCurrentJreJars();
for (File f : jreJars) {
JarFile jarFile = null;
try {
jarFile = new JarFile(f);
} catch (IOException e) {
logger.log(
Level.SEVERE,
"Unable to read a jre library while constructing the blacklist. Security restrictions may not be entirely emulated. "
+ f.getAbsolutePath());
}
continue;
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
JarEntry entry = (JarEntry) entries.nextElement();
String entryName = entry.getName();
if (entryName.endsWith(".class")) {
String className = entryName.replace('/', '.').substring(0,
entryName.length() - ".class".length());
if (isBlackListed(className)) {
blackList.add(className.replace('.', '/'));
}
}
}
}
blackList = Collections.unmodifiableSet(blackList);
}
private static Set<File> getCurrentJreJars() {
return getJreJars(System.getProperty("java.home"));
}
//REMOVED OTHER METHODS TO KEEP IT SHORT
}
d) appengine-tools-sdk-1.8.3.jar :- It has a class called WhiteList which includes all allowed JRE classes.
package com.google.apphosting.runtime.security;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class WhiteList {
private static Set<String> whiteList = new HashSet(
Arrays.asList(new String[] {
"java.beans.Transient",
"java.lang.BootstrapMethodError",
"java.lang.Character$UnicodeScript",
"java.lang.ClassValue",
"java.lang.SafeVarargs",
//Removed other classes to keep this article short
"java.net.URLClassLoader",
"java.security.SecureClassLoader",
"sun.net.spi.nameservice.NameService" }));
public static Set<String> getWhiteList() {
return whiteList;
}
}

Resources