NancyFx using embedded views - nancy

I'm trying to utilize embedded views feature of NancyFX, but could not manage to make it happen. I've used that example. But still, it looks like Nancy does not use ResourceViewLocationProvider to locate my view.
My bootstrapp configuration,
protected override void ConfigureApplicationContainer(IKernel existingContainer)
{
base.ConfigureApplicationContainer(existingContainer);
var currentAssembly = GetType().Assembly;
ResourceViewLocationProvider.RootNamespaces.Add(currentAssembly, "Candidate.Nancy.SelfHosted.Views");
}
protected override NancyInternalConfiguration InternalConfiguration
{
get { return NancyInternalConfiguration.WithOverrides(x => x.ViewLocationProvider = typeof(ResourceViewLocationProvider)); }
}
My module,
public class AccountModule : NancyModule
{
private readonly IUserManagement _userManagement;
public AccountModule(IUserManagement userManagement) : base("/account")
{
_userManagement = userManagement;
Get["/login"] = p => View["Login.cshtml"];
}
}
Login.cshtml is placed under /Views/Account/Login.cshtml and marked as embedded resource.
If I run application, I got HTTP 500. Seems to me, it tries to find it on filesystem instead of assembly resources.
Nancy.RequestExecutionException: Oh noes! --->
Nancy.ViewEngines.ViewNotFoundException: Unable to locate view
'Login.cshtml' Currently available view engine extensions:
sshtml,html,htm,cshtml,vbhtml Locations inspected:
Login.cshtml,views/Login.cshtml,views/account/Login.cshtml,account/Login.cshtml,views/Account/Login.cshtml,Account/Login.cshtml
Root path:
D:\Development\Projects\candidate.net\src\Candidate.Nancy.Selfhosted\bin\Debug
at Nancy.ViewEngines.DefaultViewFactory.GetRenderedView(String
viewName, Object model, ViewLocationContext viewLocationContext) at
System.Dynamic.UpdateDelegates.UpdateAndExecute4[T0,T1,T2,T3,TRet](CallSite
site, T0 arg0, T1 arg1, T2 arg2, T3 arg3) at
Nancy.ViewEngines.DefaultViewFactory.RenderView(String viewName,
Object model, ViewLocationContext viewLocationContext) at
Nancy.NancyModule.ViewRenderer.get_Item(String viewName) at
Candidate.Nancy.Selfhosted.Modules.AccountModule.<.ctor>b__0(Object p)
in
D:\Development\Projects\candidate.net\src\Candidate.Nancy.Selfhosted\Modules\AccountModule.cs:line
17 at Nancy.Routing.Route.Invoke(DynamicDictionary parameters)
at Nancy.NancyEngine.ResolveAndInvokeRoute(NancyContext context) at
Nancy.NancyEngine.InvokeRequestLifeCycle(NancyContext context,
IPipelines pipelines) --- End of inner exception stack trace ---
at Nancy.NancyEngine.InvokeOnErrorHook(NancyContext context,
ErrorPipeline pipeline, Exception ex)
UPDATE: This issue has been resolved in Nancy 0.12.1.0.

Related

Flink JDBC Sink part 2

I have posted a question few days back- Flink Jdbc sink
Now, I am trying to use the sink provided by flink.
I have written the code and it worked as well. But nothing got saved in DB and no exceptions were there. Using previous sink my code was not finishing(that should happen ideally as its a streaming app) but after the following code I am getting no error and the nothing is getting saved to DB.
public class CompetitorPipeline implements Pipeline {
private final StreamExecutionEnvironment streamEnv;
private final ParameterTool parameter;
private static final Logger LOG = LoggerFactory.getLogger(CompetitorPipeline.class);
public CompetitorPipeline(StreamExecutionEnvironment streamEnv, ParameterTool parameter) {
this.streamEnv = streamEnv;
this.parameter = parameter;
}
#Override
public KeyedStream<CompetitorConfig, String> start(ParameterTool parameter) throws Exception {
CompetitorConfigChanges competitorConfigChanges = new CompetitorConfigChanges();
KeyedStream<CompetitorConfig, String> competitorChangesStream = competitorConfigChanges.run(streamEnv, parameter);
//Add to JBDC Sink
competitorChangesStream.addSink(JdbcSink.sink(
"insert into competitor_config_universe(marketplace_id,merchant_id, competitor_name, comp_gl_product_group_desc," +
"category_code, competitor_type, namespace, qualifier, matching_type," +
"zip_region, zip_code, competitor_state, version_time, compConfigTombstoned, last_updated) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
(ps, t) -> {
ps.setInt(1, t.getMarketplaceId());
ps.setLong(2, t.getMerchantId());
ps.setString(3, t.getCompetitorName());
ps.setString(4, t.getCompGlProductGroupDesc());
ps.setString(5, t.getCategoryCode());
ps.setString(6, t.getCompetitorType());
ps.setString(7, t.getNamespace());
ps.setString(8, t.getQualifier());
ps.setString(9, t.getMatchingType());
ps.setString(10, t.getZipRegion());
ps.setString(11, t.getZipCode());
ps.setString(12, t.getCompetitorState());
ps.setTimestamp(13, Timestamp.valueOf(t.getVersionTime()));
ps.setBoolean(14, t.isCompConfigTombstoned());
ps.setTimestamp(15, new Timestamp(System.currentTimeMillis()));
System.out.println("sql"+ps);
},
new JdbcConnectionOptions.JdbcConnectionOptionsBuilder()
.withUrl("jdbc:mysql://127.0.0.1:3306/database")
.withDriverName("com.mysql.cj.jdbc.Driver")
.withUsername("xyz")
.withPassword("xyz#")
.build()));
return competitorChangesStream;
}
}
You need enable autocommit mode for jdbc Sink.
new JdbcConnectionOptions.JdbcConnectionOptionsBuilder()
.withUrl("jdbc:mysql://127.0.0.1:3306/database;autocommit=true")
It looks like SimpleBatchStatementExecutor only works in auto-commit mode. And if you need to commit and rollback batches, then you have to write your own ** JdbcBatchStatementExecutor **
Have you tried to include the JdbcExecutionOptions ?
dataStream.addSink(JdbcSink.sink(
sql_statement,
(statement, value) -> {
/* Prepared Statement */
},
JdbcExecutionOptions.builder()
.withBatchSize(5000)
.withBatchIntervalMs(200)
.withMaxRetries(2)
.build(),
new JdbcConnectionOptions.JdbcConnectionOptionsBuilder()
.withUrl("jdbc:mysql://127.0.0.1:3306/database")
.withDriverName("com.mysql.cj.jdbc.Driver")
.withUsername("xyz")
.withPassword("xyz#")
.build()));

How to use symmetricDS in Embedded mode

I have the following use case:
A database A (Master) and a database B (slave), located on diferent machines.
I want to synchronize the Database A with Database B.
I want to create a java application using SymmetricDS embedded.
As there is no documentation on how to perform this, i want a sample example or a documentation .
Please help me I'm stuck.
this an example how run the Symmetric engine server in embedded mode , and it works perfectley for me :
public class ClientNode {
private ClientSymmetricEngine cEngine;
private File propFile;
public ClientNode(File file) throws FileNotFoundException, IOException {
propFile = file;
Properties propertiesFile = new Properties();
propertiesFile.load(new FileReader(propFile));
cEngine = new ClientSymmetricEngine(propertiesFile, true);
getcEngine().openRegistration("client", "001");// client is the name of the node group and 001 is the ID
getcEngine().setup();
getcEngine().start();
}
public ClientSymmetricEngine getcEngine() {
return cEngine;
}
public void setcEngine(ClientSymmetricEngine cEngine) {
this.cEngine = cEngine;
}
}
Main class :
public static void main(String[] args) {
try {
new ClientNode(new File("client.properties"));
SymmetricWebServer node = new SymmetricWebServer("master.properties");
node.setWebAppDir("Web");
node.setJoin(false);
node.start();
// this will stop the node
//node.stop();
}catch (Exception e) {
e.printStackTrace();
}
}
Properties files :
client.properties :
external.id=001
engine.name=client-001
sync.url=http\://localhost\:31415/sync/client-001
group.id=client
db.url=jdbc\:mysql\://localhost/easyexchangedb_slave
db.driver=com.mysql.jdbc.Driver
db.user=root
registration.url=http\://localhost\:31415/sync/server
db.password=
master.properties :
external.id=server
engine.name=server
sync.url=http\://localhost\:31415/sync/server
group.id=server
db.url=jdbc\:mysql\://localhost/easyexchangedb_master
db.driver=com.mysql.jdbc.Driver
db.user=root
registration.url=http\://localhost\:31415/sync/server
db.password=
auto.registration=true
There's a section in the documentation about embedding symmetricDs engine into Java SE application: http://www.symmetricds.org/doc/3.6/user-guide/html-single/user-guide.html#deployment-options-embedded

Autofixture test for invalid constructor parameter

I have the following class and test. I want to test passing a null value as a parameter to the constructor and are expecting an ArgumentNullException. But since I use the Autofixture's CreateAnonymous method I get a TargetInvocationException instead.
What is the correct way to write those kinds of tests?
public sealed class CreateObject : Command {
// Properties
public ObjectId[] Ids { get; private set; }
public ObjectTypeId ObjectType { get; private set; }
public UserId CreatedBy { get; private set; }
// Constructor
public CreateObject(ObjectId[] ids, ObjectTypeId objectType, UserId createdBy) {
Guard.NotNull(ids, "ids");
Guard.NotNull(objectType, "objectType");
Guard.NotNull(createdBy, "createdBy");
Ids = ids;
ObjectType = objectType;
CreatedBy = createdBy;
}
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void constructor_with_null_ids_throw() {
fixture.Register<ObjectId[]>(() => null);
fixture.CreateAnonymous<CreateObject>();
}
IMO, Ruben Bartelink's comment is the best answer.
With AutoFixture.Idioms, you can do this instead:
var fixture = new Fixture();
var assertion = new GuardClauseAssertion(fixture);
assertion.Verify(typeof(CreateObject).GetConstructors());
The Verify method will provide you with a quite detailed exception message if any constructor argument in any constructor is lacking a Guard Clause.
FWIW, AutoFixture extensively uses Reflection, so I don't consider it a bug that it throws a TargetInvocationException. While it could unwrap all TargetInvocationException instances and rethrow their InnerException properties, that would also mean disposing of (potentially) valuable information (such as the AutoFixture stack trace). I've considered this, but don't want to take AutoFixture in that direction, for exactly that reason. A client can always filter out information, but if information is removed prematurely, no client can get it back.
If you prefer the other approach, it's not too hard to write a helper method that unwraps the exception - perhaps something like this:
public Exception Unwrap(this Exception e)
{
var tie = e as TargetInvocationException;
if (tie != null)
return tie.InnerException;
return e;
}
I came across this while I was searching for something similar. I would like to add that, combined with automoqcustomization and xunit, below code also works and its much cleaner.
[Theory, AutoMoqData]
public void Constructor_GuardClausesArePresent(GuardClauseAssertion assertion)
{
assertion.Verify(typeof(foo).GetConstructors());
}
You just need to create the AutoMoqData attribute as follows.
public class AutoMoqDataAttribute : AutoDataAttribute
{
public AutoMoqDataAttribute() : base(() => new Fixture().Customize(new AutoMoqCustomization()))
{
}
}

WPF CodedUI test: programmatically launching application

If I record actions to enter in login credentials into a dialog and call this Submit() in say UImap1.uitests. The autogenerated code will look something like this:
public void Launch()
{
#region Variable Declarations
WpfEdit uIUsernameBoxEdit = this.UIOCC600OILoginWindow.UIUsernameBoxEdit;
WpfEdit uIPasswordBoxEdit = this.UIOCC600OILoginWindow.UIPasswordBoxEdit;
WpfButton uIOKButton = this.UIOCC600OILoginWindow.UIOKButton;
#endregion
// Type 'username' in 'usernameBox' text box
uIUsernameBoxEdit.Text = this.LaunchParams.UIUsernameBoxEditText;
// Click 'passwordBox' text box
Mouse.Click(uIPasswordBoxEdit, new Point(63, 13));
// Type '********' in 'passwordBox' text box
Keyboard.SendKeys(uIPasswordBoxEdit, this.LaunchParams.UIPasswordBoxEditSendKeys, true);
// Click 'OK' button
Mouse.Click(uIOKButton, new Point(33, 14));
}
Now, if I manually launch the application under a method decorded with ClassInitialize in my in my CodedUI test class as follows:
[ClassInitialize()]
public static void MyTestInitialize(TestContext context)
{
Process.Start(#"C:\Program Files (x86)\MyCompany\MyApp.exe");
Playback.Wait(2000);
var uimap = new LaunchApplicationMap();
var loginParams = uimap.EnterLoginCredentialsParams;
loginParams.UIUsernameBoxEditText = "username";
loginParams.UIPasswordBoxEditSendKeys = Playback.EncryptText("password
");
uimap.Launch();
Playback.Wait(5000);
}
why do I get the following a null exception as shown below?
This is also the stack trace:
System.NullReferenceException was unhandled by user code
Message=Object reference not set to an instance of an object.
Source=Microsoft.VisualStudio.TestTools.UITest.Framework
StackTrace:
at Microsoft.VisualStudio.TestTools.UITest.Framework.UITestService.TechnologyManagerByName(String technologyName)
at Microsoft.VisualStudio.TestTools.UITesting.UITestControl.ValidateSearchProperties()
at Microsoft.VisualStudio.TestTools.UITesting.UITestControl.FindInternal()
at Microsoft.VisualStudio.TestTools.UITesting.UITestControl.FindControlIfNecessary()
at Microsoft.VisualStudio.TestTools.UITesting.UITestControl.SetProperty(String propertyName, Object value)
at Microsoft.VisualStudio.TestTools.UITesting.WpfControls.WpfEdit.set_Text(String value)
at UITests.UIMaps.LaunchApplicationMapClasses.LaunchApplicationMap.Launch() in C:\dev\OCC600\Source - Copy\Tests\UITests\UIMaps\LaunchApplicationMap.Designer.cs:line 44
at UITests.LogsViewTests.MyTestInitialize(TestContext context) in C:\dev\OCC600\Source - Copy\Tests\UITests\LogsViewTests.cs:line 70
InnerException:
TIA.
You need to initialize the playback engine to use CodedUI outside of a test method. The framework automatically initializes playback/cleanup in the testinitalize/cleanup methods so you don't see it in there.
ClassInitialize/AssemblyInitialize happen before any tests begin so you have to call Playback.Initialize().

EJB3Unit testing no-tx-datasource

I am doing tests on an ejb3-project using ejb3unit http://ejb3unit.sourceforge.net/Session-Bean.html for testing. All my Services long for #PersistenceContext (UnitName=bla). I set up the ejb3unit.properties like this:
ejb3unit_jndi.1.isSessionBean=true
ejb3unit_jndi.1.jndiName=ejb/MyServiceBean
ejb3unit_jndi.1.className=com.company.project.MyServiceBean
everything works with the in-memory-database.
So now i want additionally test another servicebean with #PersistenceContext (UnitName=noTxDatasource) that goes for a defined in my datasources.xml:
<datasources>
<local-tx-datasource>
...
</local-tx-datasource>
<no-tx-datasource>
<jndi-name>noTxDatasource</jndi-name>
<connection-url>...</connection-url>
<driver-class>oracle.jdbc.OracleDriver</driver-class>
<user-name>bla</user-name>
<password>bla</password>
</no-tx-datasource>
</datasources>
How do I tell ejb3unit to make this work:
Object object = InitialContext.doLookup("java:/noTxDatasource");
if (object instanceof DataSource) {
return ((DataSource) object).getConnection();
} else {
return null;
}
Currently it fails saying: javax.NamingException: Cannot find the name (noTxDataSource) in the JNDI tree Current bindings: (ejb/MyServiceBean=com.company.project.MyServiceBean)
How can I add this no-tx-datasource to the jndi bindings?
I hate answering my own questions, but I had some simple thought:
public void setUp() throws Exception {
OracleDataSource ds = new OracleDataSource();
ds.setServerName("localhost");
ds.setPortName(1521);
ds.setDatabaseName("database"); // SID
ds.setUser("user");
ds.setPassword("pass");
InitialContext ic = new InitialContext();
ic.add("noTxDatasource", ds);
}
This will additionally allow you to make the following lookup work:
Object object = InitialContext.doLookup("java:/noTxDatasource");
delivering a datasource (in this case oracle).

Resources