Bean not being found - java-ee-7

I am trying to learn JavaEE; after following a tutorial I am unable to reach a bean that is clearly annotated correctly:
#Named("editPhotoBean")
#SessionScoped
public class EditPhoto implements Serializable `
calling a bean method using jsf tag:
`<h:inputFile
id="file"
value="#{editPhotoBean.uploadedPart}">
<f:validator validatorId="imageUploadValidator" />
</h:inputFile>`
I get:
javax.el.PropertyNotFoundException: /upload.xhtml #30,63
value="#{editPhotoBean.uploadedPart}": Target Unreachable, identifier
'editPhotoBean' resolved to null
formerly I had it as:
#Named(value = "editPhotoBean")
Something else that is telling is the fact that properties on other beans show up as unfound by netbeans:
<tr><td align='center'>
<label>
<c:if test="#{photoBook.currentPhoto.public}">
Everyone can see this photo
</c:if>
<c:if test="#{not photoBook.currentPhoto.public}">
Only you can see this photo
</c:if>
</label>
</td></tr>
<tr><td align='center'>
<label>Uploaded as #{photoBook.currentPhoto.filename}</label>
though that bean is marked:
#Named("photoBook")
#SessionScoped
public class PhotoBook implements Serializable {
I suspect it has something to do with my libraries, everything else has worked but I looked and realized that I don't have any JAvaEE libraries installed except what comes with glassfish:
any hints on what to install ? || is it something else ?
Thanks!

If using JSF or PrimeFaces set annotation #ManagedBean on top of
class
List item setter and getter on uploadedPart property

Related

Loaded class is of incorrect type: expected(org.eclipse.ui.menus.WorkbenchWindowControlContribution) got (de.blub.menu.ToolbarContributionItem)

This is my menucontribution in the plugin.xml:
<menuContribution
locationURI="toolbar:org.eclipse.ui.main.toolbar?after=additions">
<dynamic
class="de.blub.menu.ToolbarContributionItem"
id="some.id">
<visibleWhen checkEnabled="false">
<!-- some conditions -->
</visibleWhen>
</dynamic>
</menuContribution>
The ToolBarContributionItem class extends CompoudStatement as required according to the Documentation:
The element provides a mechanism that will call back into the defined class to provide an IContributionItem to be shown when the menu or toolbar is built. The defined class must be a derivative of the org.eclipse.jface.action.ContributionItem base class. It can also use org.eclipse.ui.action.CompoundContributionItem and provide an implementation for the abstract getContributionItems method to provide a dynamic menu item.
public class ToolbarContributionItem extends CompoundContributionItem {
...
But I get the Error Message
!MESSAGE Loaded class is of incorrect type: expected(org.eclipse.ui.menus.WorkbenchWindowControlContribution) got (de.blub.menu.ToolbarContributionItem)
!STACK 0
java.lang.IllegalArgumentException: Loaded class is of incorrect type: expected(org.eclipse.ui.menus.WorkbenchWindowControlContribution) got (de.blub.menu.ToolbarContributionItem)
at org.eclipse.ui.internal.util.Util.safeLoadExecutableExtension(Util.java:713)
So what's the problem here?
The documentation is wrong, see Eclipse bug 509635.
The class must extend org.eclipse.ui.menus.WorkbenchWindowControlContribution

ReactJS.net unable to debug

I've created a small app using ReactJS.Net and ASP.NET 5. If I render a component serverside using #Html.React and tie that to the MVC
#using System.Threading.Tasks
#using React.AspNet
#model Models.DashboardViewModel
#Html.React("MessageBoard", new
{
recentPosts = Model.RecentPosts
})
messageBoard.jsx
"use strict";
var MessageBoard = React.createClass({
render: function(){
return (<table className="table forum table-striped">
<thead>
<tr>
<th className="cell-stat"></th>
<th>Topic</th>
<th className="cell-stat text-center hidden-xs hidden-sm">Replies</th>
<th className="cell-stat-2x hidden-xs hidden-sm">Last Post</th>
</tr>
</thead>
<tbody>
{this.props.recentPosts.map(function(boardPost){
return <BoardPostRow post={boardPost}/>;
}, this)}
</tbody>
</table>)
}
});
This all works great. The problem is that when I go to sources, there is no .js file so I have no way to debug. This is probably ok for some simple read-only elements. But now I want to render some interactive elements that contain state, a form for creating a new Post to the "message board". Here's the code in the same *.cshtml file.
<div id="newPost"></div>
#section scripts
{
<script src="#Url.Content("~/scripts/Components/Board/boardPostForm.jsx")"></script>
<script src="#Url.Content("~/scripts/Components/Common/textInput.jsx")"></script>
<script>React.render(BoardPostForm({}), document.getElementById("newPost"))</script>
#Html.ReactInitJavaScript()
}
The error I get in the console is:
Uncaught SyntaxError: Unexpected token <
textInput.jsx:19 Uncaught SyntaxError: Unexpected token <
(index):69 Uncaught ReferenceError: BoardPostForm is not defined(anonymous function) # (index):69
(index):70 [.NET] Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of MessageBoard. See http://fb.me/react-warning-keys for more information.
(index):71 [.NET] Warning: Unknown DOM property class. Did you mean className?
(index):71 Uncaught ReferenceError: MessageBoard is not defined
It seems an error trying to read the .jsx, because it takes me to the render function when I click on the error. What am I missing here? Maybe I need to do the jsx->js conversion as part of my build process (I am using Gulp) instead of relying on ReactJS.NET?
What happens if you hit /scripts/Components/Board/boardPostForm.jsx in your web browser? It should show the compiled JSX and have some ReactJS.NET info at the top of the file. If it doesn't, make sure the *.jsx handler is configured in your Web.config. It should look something like this:
<add name="ReactJsx" verb="GET" path="*.jsx" type="React.Web.JsxHandlerFactory, React.Web" preCondition="integratedMode" />
What am I missing here? Maybe I need to do the jsx->js conversion as part of my build process (I am using Gulp) instead of relying on ReactJS.NET?
You can use Gulp if you like, up to you. I have a sample here that uses Webpack for bundling, and ReactJS.NET for server-side rendering: https://github.com/reactjs/React.NET/tree/master/src/React.Sample.Webpack

using Microsoft.Web.MVC on View

I am following an online example for creating a wizard control. It involves in serializing the model on the view, then pass it to the controller which Deserialize the model and use. Below is the code for the View,
#using Microsoft.Web.Mvc
#model Sample.Models.RegisterWizardViewModel
#{
var currentStep = Model.Steps[Model.CurrentStepIndex];
ViewBag.Title = "Register";
}
#using (Html.BeginForm())
{
#Html.Serialize("wizard", Model)
#Html.Hidden("StepType", Model.Steps[Model.CurrentStepIndex].GetType())
#Html.EditorFor(x => currentStep, null, "")
if (Model.CurrentStepIndex > 0)
{
<input type="submit" value="Previous" name="prev" />
}
if (Model.CurrentStepIndex < Model.Steps.Count - 1)
{
<input type="submit" value="Next" name="next" />
}
else
{
<input type="submit" value="Finish" name="finish" />
}
}
Now at first I was not finding [Deserialize] attribute in the controller and for that I have installed the MvcContrib package from the NuGet.
The problem I am facing is that #Html.Serialize("wizard", Model) is not found. Also the namespace Microsoft.Web.Mvc could not be resolved. If in the Controller file I use Microsoft.Web.Mvc then it work without a problem but when I use the same namespace in the view then it could not be resolved. What is the difference between System.Web.MVC and Microsoft.Web.MVC? How to resolved the namespace error?
I have also read that #Html.Serialize is not available and it can be accessible through MVC Futures. I have added the package but how to use it to Serialize the model on the View?
Edit: Just like to mention that I have installed the nuget package Microsoft.AspNet.Mvc.Futures 5.0.0' but I am unable to see any reference in the references folder. There is no Microsoft.AspNet.Mvc or Microsoft.AspNet.Mvc.Futures reference in the references folder. Where did it go I wonder?

How can I use cshtml files with Durandal?

I got the DurandalJS StarterKit template on VS2012... All works great...
But in some views I need to do something like that:
#if (Roles.IsUserInRole("Administrators"))
{
<p>Test</p>
}
However with durandal all my views are '.html' files... Is that possible to use '.cshtml' files to access some information like that?
Or is there any other way to do that with durandal?
Junior
I am doing it like this:
Create a generic controller for Durandal views:
public class DurandalViewController : Controller
{
//
// GET: /App/views/{viewName}.html
[HttpGet]
public ActionResult Get(string viewName)
{
return View("~/App/views/" + viewName + ".cshtml");
}
}
Register a route:
routes.MapRoute(
name: "Durandal App Views",
url: "App/views/{viewName}.html",
defaults: new { controller = "DurandalView", action = "Get" }
);
Copy Views/web.config to /App/views/web.config (so Razor views work in this location).
This lets me use the normal Durandal conventions (even the html extension for views), and put durandal views as cshtml files in their normal location without adding any more server code.
If you also have static html views, you can also place the cshtml views in a subfolder or use the normal MVC /Views folder.
I wouldn't recommend using ASP.NET MVC with Durandal.
What you are probably looking to do is use the Razor view engine (to get the benefits of a compiler, strong typing etc.) which exists independently from ASP.NET MVC. Just WebAPI for data I/O is more than enough to very efficiently create a Durandal.js application.
If you are interested in using Razor/CSHTML with Durandal and Knockout there is an open source option out there called FluentKnockoutHelpers that may be exactly what you are looking for. It offers much of the 'nice' parts of ASP.NET MVC allowing you to use the awesome abilities of Durandal and Knockout with almost no downfalls.
Source
Live demo using Durandal.js
In a nutshell it provides a bunch of features which makes doing Durandal/Knockout development just as easy as ASP.NET MVC. (You simply provide a C# type that your JavaScript model is based off of for most of the features.) You only have to write JavaScript and un-compiled markup for complicated cases which is unavoidable and no different than MVC! (Except in MVC your code would also likely end up would also be a big jQuery mess which is why you are using Durandal/Knockout in the first place!)
Features:
Painlessly generate Knockout syntax with strongly typed, fluent, lambda expression helpers similar to ASP.NET MVC
Rich intellisense and compiler support for syntax generation
Fluent syntax makes it a breeze to create custom helpers or extend whats built in
OSS alternative to ASP.NET MVC helpers: feel free to add optional features that everyone in the community can use
Painlessly provides validation based on .NET types and DataAnnotations in a few lines of code for all current/future application types and changes
Client side JavaScript object factory (based on C# types) to create new items in for example, a list, with zero headaches or server traffic
Example without FluentKnockoutHelpers
<div class="control-group">
<label for="FirstName" class="control-label">
First Name
</label>
<div class="controls">
<input type="text" data-bind="value: person.FirstName" id="FirstName" />
</div>
</div>
<div class="control-group">
<label for="LastName" class="control-label">
Last Name
</label>
<div class="controls">
<input type="text" data-bind="value: person.LastName" id="LastName" />
</div>
</div>
<h2>
Hello,
<!-- ko text: person.FirstName --><!-- /ko -->
<!-- ko text: person.LastName --><!-- /ko -->
</h2>
Provide FluentKnockoutHelpers with a .NET type and you can do this in style with Intellisense and a compiler in Razor / CSHTML
#{
var person = this.KnockoutHelperForType<Person>("person", true);
}
<div class="control-group">
#person.LabelFor(x => x.FirstName).Class("control-label")
<div class="controls">
#person.BoundTextBoxFor(x => x.FirstName)
</div>
</div>
<div class="control-group">
#person.LabelFor(x => x.LastName).Class("control-label")
<div class="controls">
#person.BoundTextBoxFor(x => x.LastName)
</div>
</div>
<h2>
Hello,
#person.BoundTextFor(x => x.FirstName)
#person.BoundTextFor(x => x.LastName)
</h2>
Take a look at the Source or Live Demo for an exhaustive overview of FluentKnockoutHelper's features in a non-trivial Durandal.js application.
Yes, you can absolutely use cshtml files with Durandal and take advantage of Razor on the server. I assume that also means you want MVC, so you can do that too and use its routing.
If you don;t want the routing then you can set the webpages.Enabled in the web.config, as the other comments suggest.
<add key="webpages:Enabled" value="true" />
I don't recommend that you use .cshtml files as views directly. You're better off placing the .cshtml files behind a controller.
For example, take the HotTowel sample, edit /App/main.js, and replace the function definition with the following:
define(['durandal/app',
'durandal/viewLocator',
'durandal/system',
'durandal/plugins/router',
'durandal/viewEngine',
'services/logger'],
function (app, viewLocator, system, router, viewEngine, logger) {
Note that we added a reference to the Durandal viewEngine. Then we need to replace
viewLocator.useConvention();
with
viewLocator.useConvention('viewmodels', '../../dynamic');
viewEngine.viewExtension = '/';
The first argument to viewLocation.useConvention sets the /Apps/viewmodels/ directory as the location for the view models js files, but for the view location, uses the URL http://example.com/dynamic/, with an extension of '/'. So that if Durandal is looking for the view named 'shell', it will reference http://example.com/dynamic/shell/ (this is because the view directory is mapped relative to the viewmodels directory, hence /App/viewmodels/../../dynamic will give you simply /dynamic).
By convention, this previous URL (http://example.com/dynamic/shell/) will be mapped to the controller DynamicController, and the action "Shell".
After this, you simply add a controller - DynamicController.cs, like this:
// will render dynamic views for Durandal
public class DynamicController : Controller
{
public ActionResult Shell()
{
return View();
}
public ActionResult Home()
{
return View();
}
public ActionResult Nav()
{
return View();
}
public ActionResult Details()
{
return View();
}
public ActionResult Sessions()
{
return View();
}
public ActionResult Footer()
{
return View();
}
}
Create .cshtml files for each of the above actions. This way you get to use controllers, server side IoC et al to generate dynamic views for your SPA.
DurandaljS is a client framework which forms mainly a solid base for single-page apps (SPA).
I assume you are using asp.net web API as your server technology. In that case, you can determine the user's role inside your API controller and based on that return data to the client. On the client you can use Knockout "if" binding in order to show / hide certain areas of your page.
What you perhaps can do is placing this code in the Index.cshtml.
Following link shows how to customize moduleid to viewid mapping
http://durandaljs.com/documentation/View-Location/
by convention durandal tries to find view url in following steps
1) Checke whether object has getView() function which returns either dom or a string ( url for the view)
2) If object does not have getView function then checks whether object has viewUrl property
3) If above two steps fails to produce url or a DOM view drundal falls to default convention
which maps moduleid xyz.js to view xyz.html using view url ( path of Views folder ) defined in main.js
so for moduleid xyz.js path of the view will be views/xyz.html
you can overwrite this default mapping behavior by overwriting convertModuleIdToViewId function.
So there are many ways you can customize your view url for specific model (.js object)
I made an extension to Durandal which gives you the ability to place an applicationContent div in your cshtml file together with the applicationHost div. In applicationContent you can now use both ASP .Net MVC syntax together with knockout bindings.
Only thing I did was put some extra code in the viewLocator.js file which looks for an applicationContent div:
locateViewForObject: function(obj, area, elementsToSearch) {
var view;
if (obj.getView) {
view = obj.getView();
if (view) {
return this.locateView(view, area, elementsToSearch);
}
}
if (obj.viewUrl) {
return this.locateView(obj.viewUrl, area, elementsToSearch);
}
view = document.getElementById('applicationContent');
if (view) {
return this.locateView(view, area, elementsToSearch);
}
var id = system.getModuleId(obj);
if (id) {
return this.locateView(this.convertModuleIdToViewId(id), area, elementsToSearch);
}
return this.locateView(this.determineFallbackViewId(obj), area, elementsToSearch);
},
Your original cshtml file can now do something like this:
<div class="row underheader" id="applicationContent">
<div class="small-5 columns">
<div class="contentbox">
#using (Html.BeginForm("Generate", "Barcode", FormMethod.Post, Attributes.Create()
.With("data-bind", "submit: generateBarcodes")))
{
<div class="row formrow">
<label for="aantalBijlagen">#Translations.Label_AantalBijlagen</label>
</div>
<div class="row">
<select name="aantalBijlagen" class="small-6 columns">
<option>0</option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>
</div>
<div class="row">
<button class="button right" type="submit" id="loginbutton"><span class="glyphicon glyphicon-cog"></span> #Translations.Action_Generate</button>
</div>
}
</div>
</div>
<div class="small-7 columns" data-bind="if: hasPdfUrl">
<div class="contentbox lastcontent">
<iframe data-bind="attr: {src: pdf_url}"></iframe>
</div>
</div>
You can find my fork of the durandal project here and a small blogpost of what and how I did this here.
I'm not very familiar with DurandalJS but because it's a client-side system, it should make no difference what technology is used on the server to generate the HTML markup. So if you use Razor CSHTML files to generate the HTML on the server, DurandalJS should work just fine with it.
If you're getting a particular error then please share that error, but I can't think of any reason why it wouldn't work.

change name of calendar export from "liferay.ics"

Someone know how to change the filename of the liferay calendar event before export?
The default one is "liferay.ics".
Thanks
Sabrina
You can alter the name by writting an hook.
Override the export_import.jspf file located at %liferay_folder%\%your_server%\webapps\ROOT\html\portlet\calendar
<aui:fieldset label="export">
<aui:input cssClass="lfr-input-text-container" label="" name="exportFileName" type="text" value="liferay.ics" />
</aui:fieldset>
Changing the value attribute should do the trick.
Owk after looking a bit closer to the calendar portlet it appears that my above solution is only visible on the export/import tab and not when you export an event from the summary tab.
The endpoint who is responsible for creating the file: http://www.jarvana.com/jarvana/view/com/liferay/portal/portal-impl/6.1.0/portal-impl-6.1.0-sources.jar!/com/liferay/portlet/calendar/action/ExportEventsAction.java?format=ok
It appears that when no portlet parameter with the name exportFileName is set the action will automaticly name it liferay.ics:
Short And Easy fix:
Add (in event_action.jsp):
<portlet:param name="exportFileName" value="<%= event.getTitle() %>" />
to :
<c:if test="<%= CalEventPermission.contains(permissionChecker, event, ActionKeys.VIEW) %>">
<portlet:actionURL windowState="<%= LiferayWindowState.EXCLUSIVE.toString() %>" var="exportURL">
<portlet:param name="struts_action" value="/calendar/export_events" />
<portlet:param name="redirect" value="<%= currentURL %>" />
<portlet:param name="eventId" value="<%= String.valueOf(event.getEventId()) %>" />
</portlet:actionURL>
<liferay-ui:icon
image="export"
url='<%= exportURL %>'
/>
</c:if>
Write an wrapper arround the ExportEventsAction. (For more Advance senarios)
Use this method when more advance operations are required in the future.
http://www.liferay.com/web/mika.koivisto/blog/-/blogs/7132115
https://github.com/liferay/liferay-plugins/blob/master/hooks/sample-struts-action-hook/docroot/WEB-INF/src/com/liferay/samplestrutsaction/hook/action/SampleStrutsPortletAction.java
Wrapper basic concepts:
In your hook xml:
<?xml version="1.0"?>
<!DOCTYPE hook PUBLIC "-//Liferay//DTD Hook 6.1.0//EN" "http://www.liferay.com/dtd/liferay-hook_6_1_0.dtd">
<hook>
<custom-jsp-dir>/WEB-INF/jsps/</custom-jsp-dir>
<struts-action>
<struts-action-path>/calendar/export_events</struts-action-path>
<struts-action-impl>aiao.liferay.strutsactions.ExportEventActionWrapper</struts-action-impl>
</struts-action>
</hook>
Your wrapper looks like this:
public class ExportEventActionWrapper extends BaseStrutsPortletAction {
#Override
public void processAction(StrutsPortletAction originalStrutsPortletAction, PortletConfig portletConfig, ActionRequest actionRequest, ActionResponse actionResponse) throws Exception {
_logger.info("Call To Wrapper");
//do your magic here...
originalStrutsPortletAction.processAction(portletConfig, actionRequest, actionResponse);
}
private Log _logger = LogFactoryUtil.getLog(ExportEventActionWrapper.class);
}