seam create drop down menu for a form, error - seam

I am trying to create 3 drop down menu for a form. First one, is LOB field. Second one is Application field and last one is CTA field. There is one to many relationship between LOB and Application. There is many to many relationship from Application to CTA.
CreateRequest.xhtml
<h:selectOneMenu id="lobField" value="#{manager.lob}" required="true">
<s:selectItems var="lob" value="#{lobs}" label="#{lob.lobDescription}" noSelectionLabel="Select LOB"></s:selectItems>
<s:convertEntity />
<a:support action="#{manager.loadApps}" ajaxSingle="true" event="onchange" reRender="appField,ctaField"/>
</h:selectOneMenu>
<a:outputPanel id="appField">
<h:selectOneMenu value="#{manager.app}" required="true">
<s:selectItems var="app" value="#{manager.applications}" label="#{app.applicationName}" noSelectionLabel="Select Application"></s:selectItems>
<s:convertEntity />
<a:support action="#{manager.loadCtas}" ajaxSingle="true" event="onchange" reRender="ctaField"/>
</h:selectOneMenu>
</a:outputPanel>
<a:outputPanel id="ctaField">
<h:selectOneMenu value="#{manager.cta}" required="true">
<s:selectItems var="cta" value="#{manager.ctas}" label="#{cta.ctaDescription}" noSelectionLabel="Select CTA"></s:selectItems>
<s:convertEntity />
</h:selectOneMenu>
ManagerBean.java
#Stateful
#Name("manager")
public class ManagerBean implements Manager {
#Logger
private Log log;
#In
StatusMessages statusMessages;
private Lob lob;
private Application app;
private Cta cta;
#PersistenceContext(type = PersistenceContextType.EXTENDED)
EntityManager entityManager;
#Out(required = false)
private List<Lob> lobs;
private List<Application> applications;
private List<Cta> ctas;
public void CreateRequest() {
System.out.println("Create Request");
System.out.println(app.getApplicationName());
}
public Lob getLob() {
return lob;
}
public void setLob(Lob lob) {
this.lob = lob;
}
public Application getApp() {
return app;
}
public void setApp(Application app) {
this.app = app;
}
public Cta getCta() {
return cta;
}
public void setCta(Cta cta) {
this.cta = cta;
}
public List<Lob> getLobs() {
return lobs;
}
public void setLobs(List<Lob> lobs) {
this.lobs = lobs;
}
public List<Application> getApplications() {
return applications;
}
public void setApplications(List<Application> applications) {
this.applications = applications;
}
public List<Cta> getCtas() {
return ctas;
}
public void setCtas(List<Cta> ctas) {
this.ctas = ctas;
}
#Destroy
#Remove
public void destroy() {
}
#Factory("lobs")
public void loadLobs() {
lobs = entityManager.createQuery("from Lob").getResultList();
}
public void loadApps() {
System.out.println("load apps called");
applications = lob.getApplicationList();
}
public void loadCtas() {
System.out.println("load ctas called====");
ctas = app.getCtaList();
System.out.println(ctas.size());
}
}
I am able to select a value from LOB, and loadApps is called. Then I am able to select applications, too. But when I select one, I get following error:
19:09:01,921 INFO [lifecycle] WARNING: FacesMessage(s) have been enqueued, but may not have been displayed.
sourceId=managerForm:appField[severity=(ERROR 2), summary=(value is not valid), detail=(value is not valid)]
I am unable to figure out what mistake I am making here.

Are you in a conversation? Without specifying a scope your SFSB will be in the conversation context. Have you started the conversation?

Related

Blazor Server side, set parent class name based on child class name

I have a EditForm with MatBlazor Expansion panels. I am trying to set the individual panels border color if any of the form fields are invalid inside it. I am trying to achieve following..
<MatExpansionPanel Class="#(<bool>ChildElementHasValidationMessage() ? "invalid-red-border": "")">.....</MatExpansionPanel>
I am OK with simple equivalent css solution to find a parent element. Please advice.
Just use Style instead Class to override css:
<MatExpansionPanel Style="#(your expression);"
I answered a related question about MatExpansionPanel: Mat Blazor mat-expansion-panel remove elevation/border
Edited
I wrote my own component to send EditContext on changes. I pasted it below. This is how it works:
<h1>#ShowDemo</h1>
<EditForm Model="#model" OnValidSubmit="#SaveItem">
<DataAnnotationsValidator />
<ValidationSummary />
<MyValidationSneak UpdateDelegate="#( (ctx)=>UpdateUI(ctx) )" />
<InputText id="ItemName" #bind-Value="#model.ItemName" />
<ValidationMessage For="#(() => model.ItemName)" />
<button type="submit">Submit</button>
</EditForm>
#code {
string ShowDemo = "res de res";
protected void UpdateUI(EditContext ctx)
{
var _fieldIdentifier = FieldIdentifier.Create( () => model.ItemName );
ShowDemo = string.Join(", ", ctx.GetValidationMessages(_fieldIdentifier) );
}
ItemModel model = new ItemModel();
private void SaveItem() { }
public class ItemModel
{
[Required]
public string ItemName{ get; set; }
}
}
See it in action at BlazorFiddle:
The MyValidationSneak:
public class MyValidationSneak: ComponentBase, IDisposable
{
[CascadingParameter] EditContext CurrentEditContext { get; set; }
[Parameter] public Action<EditContext> UpdateDelegate { get; set; }
private readonly EventHandler<ValidationStateChangedEventArgs> _validationStateChangedHandler;
public MyValidationSneak()
{
_validationStateChangedHandler = (sender, eventArgs) => GoUpdate();
}
private void GoUpdate() => UpdateDelegate(CurrentEditContext);
private EditContext _previousEditContext;
protected override void OnParametersSet()
{
if (CurrentEditContext == null)
{
throw new InvalidOperationException($"{nameof(ValidationSummary)} requires a cascading parameter " +
$"of type {nameof(EditContext)}. For example, you can use {nameof(ValidationSummary)} inside " +
$"an {nameof(EditForm)}.");
}
if (CurrentEditContext != _previousEditContext)
{
DetachValidationStateChangedListener();
CurrentEditContext.OnValidationStateChanged += _validationStateChangedHandler;
GoUpdate();
_previousEditContext = CurrentEditContext;
}
}
protected virtual void Dispose(bool disposing) {}
void IDisposable.Dispose()
{
DetachValidationStateChangedListener();
this.Dispose(disposing: true);
}
private void DetachValidationStateChangedListener()
{
if (_previousEditContext != null)
{
_previousEditContext.OnValidationStateChanged -= _validationStateChangedHandler;
GoUpdate();
}
}
}
Get code at github

DbSet, DbContext, EntityFramework

I am new to ASP.NET and very new to EF. I am trying to develop an application and after reading some sites I've decided I'm going to create a 3-tier application (DAL, BL, a website as the frontend).
For the DAL layer I've taken inspiration from here
http://codefizzle.wordpress.com/2012/07/26/correct-use-of-repository-and-unit-of-work-patterns-in-asp-net-mvc/
public interface IGenericRepository<T> where T : class
{
void Add(T a);
}
public interface IUnitOfWork:IDisposable
{
IGenericRepository<UserInfo> UserInfoRepository { get; }
void Commit();
}
public class EfGenericRepository<T> : IGenericRepository<T> where T : class
{
private DbSet<T> _dbSet;
public EfGenericRepository(DbSet<T> dbSet)
{
_dbSet = dbSet;
}
public void Add(T a)
{
_dbSet.Add(a);
}
}
public class EfUnitOfWork : DbContext, IUnitOfWork
{
private readonly EfGenericRepository<UserInfo> _userInfoRepo;
public DbSet<UserInfo> UserInfos { get; set; }
public EfUnitOfWork()
{
_userInfoRepo = new EfGenericRepository<UserInfo>(UserInfos);
}
public IGenericRepository<UserInfo> UserInfoRepository
{
get { return _userInfoRepo; }
}
public void Commit()
{
this.SaveChanges();
}
}
and my BL looks like this:
public interface IBussinessLogic
{
void AddUserInfo(string c);
}
public class BusinessLogic: IBussinessLogic
{
private IUnitOfWork _unitOfWork;
public BusinessLogic()
{
_unitOfWork = new EfUnitOfWork();
}
public void AddUserInfo(string c)
{
_unitOfWork.UserInfoRepository.Add(new UserInfo()
{
Address = c
});
_unitOfWork.Commit();
}
}
Now I am using web-forms but I don't think that should be an issue.
On click i execute this:
IBussinessLogic businessLogic = new BusinessLogic();
businessLogic.AddUserInfo(address.Text);
But nothing happens,my data is not saved in the db.
Can anyone please help me?

Caliburn Action not firing

<ItemsControl DockPanel.Dock="Right" x:Name="Actions">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button x:Name="Action"
HorizontalAlignment="Right"
Content="{Binding Label}"
Margin="3" Width="30"></Button>
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
The above view binds with this viewmodel
public class DeploymentInputViewModel<T> : PropertyChangedBase
{
public BindableCollection<InputActionViewModel> Actions {get;set;}
}
I see my buttons. But when clicking it nothing happen.
The viewModels for InputActionViewModel:
public abstract class InputActionViewModel{
public InputActionViewModel()
{
}
public virtual Task Action()
{
return Task.FromResult<object>(null);
}
public string ActionToolTip { get; set; }
public string Label { get; set; }
public object Value { get; set; }
}
and also
public class InputCertificateActionViewModel : InputActionViewModel
{
[Import]
private IShell _shell;
[Import]
private IWindowsDialogs _dialogs;
private readonly IDeploymentSettingInputViewModel vm;
public InputCertificateActionViewModel(IDeploymentSettingInputViewModel vm)
{
this.vm = vm;
Label = "...";
ActionToolTip = "Pick a Certificate";
}
public bool IsManagementCertificate {get;set;}
public bool IsDeploymentCertificate { get; set; }
public async override Task Action()
{
if(IsManagementCertificate)
{
var subs = await _shell.IdentityModel.GetEnabledSubscriptionsAsync();
foreach(var sub in subs)
{
using (ManagementClient client = CloudContext.Clients.CreateManagementClient(sub.GetCredentials()))
{
var cert = _dialogs.SelectItemDialog("Select a certificate", "Pick one", true,
(await client.ManagementCertificates.ListAsync()).Select(c =>
new SelectItem(c.Thumbprint, Encoding.Default.GetString(c.PublicKey), c, (s) => c.Thumbprint.Contains(s))).ToArray())
.Tag as ManagementCertificateListResponse.SubscriptionCertificate;
this.vm.Value = cert.Thumbprint;
}
}
}else if(IsDeploymentCertificate)
{
}
}
}
I am adding actionViewModels by inserting directly into the observable code at startup.
haveActions.Actions.Add(DI.BuildUp(new InputCertificateActionViewModel(vm)
{
IsDeploymentCertificate = certAttribute.IsDeploymentCertificate,
IsManagementCertificate = certAttribute.IsManagementCertificate,
}));
haveActions is an instance of InputCertificateActionViewModel
Couldn't fit this all in a comment:
I can't have a peek at the Caliburn.Micro at the moment, but it might be something related to calling your method Action.
At a guess though, I'd say that by convention Caliburn.Micro expects to find a method that matches the Action<T> delegate to use for it's Actions, so your public virtual Task Action() won't be located and bound.
Have a quick check by defining a new method with a compatible signature, e.g public void MyMethod() and checking to see if it's located correctly and will function.
If that is the problem, you'll probably want to have a look at the IResult and Coroutines part of the Caliburn.Micro documentation, which looks like it will help you implement your desired behaviour.

JSF custom panel with button - action not invoked

I have built a custom component button, but somehow the action is not invoked. When debugging the getAction-Method within the component and invoking the supplied MethodeExpression the Bean-Method is called as expected. But due to some reason, the Expression is not invoked when pressing the button in the browser.
Is there some kind of additional Interface necessary to pass the action to the embedded button-component?
Any help is very appreciated since I am stuck at this issue for some days now
MyClass:
public class MyClass extends UIPanel implements SystemEventListener
{
private UIForm form;
private HtmlCommandButton buttonOk;
public MyClass()
{
FacesContext context = getFacesContext();
UIViewRoot root = context.getViewRoot();
root.subscribeToViewEvent(PostAddToViewEvent.class, this);
}
#Override
public void processEvent(SystemEvent event)
{
this.form = new UIForm();
this.buttonOk = new HtmlCommandButton();
this.buttonOk.setId("okButtonId");
this.buttonOk.setActionExpression(getAction());
this.buttonOk.setValue("OK");
this.form.getChildren().add(this.buttonOk);
getChildren().add(this.form);
}
private enum PropertyKeys
{
action, text, titel
}
public MethodExpression getAction()
{
return (MethodExpression) getStateHelper().eval(PropertyKeys.action);
}
public void setAction(MethodExpression actionExpression)
{
getStateHelper().put(PropertyKeys.action, actionExpression);
}
public String getText()
{
return (String) getStateHelper().eval(PropertyKeys.text);
}
public void setText(String text)
{
getStateHelper().put(PropertyKeys.text, text);
}
public String getTitel()
{
return (String) getStateHelper().eval(PropertyKeys.titel);
}
public void setTitel(String titel)
{
getStateHelper().put(PropertyKeys.titel, titel);
}
#Override
public void encodeAll(FacesContext context) throws IOException
{
ResponseWriter writer = context.getResponseWriter();
writer.startElement(HTML.DIV_ELEM, this);
writer.writeText(getText(), null);
this.form.encodeAll(context);
writer.endElement(HTML.DIV_ELEM);
}
#Override
public void encodeChildren(FacesContext context) throws IOException
{
}
#Override
public boolean isListenerForSource(Object source)
{
return (source instanceof MyClass);
}
}
MyClassHandler:
public class MyClassHandler extends ComponentHandler
{
public MyClassHandler(ComponentConfig config)
{
super(config);
}
#SuppressWarnings("rawtypes")
#Override
protected MetaRuleset createMetaRuleset(Class type)
{
return super.createMetaRuleset(type).addRule(new MethodRule("action", String.class, new Class[] { ActionEvent.class }));
}
}
myView Method:
...
public String myMethod()
{
System.err.println("myMethod");
return "/some/path/yadayada.xhtml";
}
...
MyView.xhtml
<myTag action="#{myView.myMethod}" id="id1" titel="bla" text="bleh" />
Exdending UICommand is enough, since you only want one action to be executed.
You have to provide two additional MethodExpressions via the tag-attributes and within the decode-method you can check which button has been pressed and redirect the particular MethodExpression to the standard-action provided by UICommand. This way, you dont have to worry about the legacy-interface ActionSource, or how Events are broadcasted.
public void decode(FacesContext contex)
{
Map<String,String> map = context.getExternalContext.getRequestParameterMap();
// your rendered buttons need a name you check for
final boolean okPressed = map.containsKey( getClientId + ":ok" );
final boolean cancelPressed = map.containsKey( getClientId + ":cancel" );
if(okPressed || cancelPressed)
{
MethodExpression exp = null;
if(okPressed)
{
exp = getActionOk();
}
else
{
exp = getActionCancel();
}
// redirect to standard action
setActionExpression(exp);
queueEvent(new ActionEvent(this));
}
}
In order to make use of of this you need two attributes (actionOk and actionCancel) which use Method Expressions (setter and getter). Those have to be configured by a ComponentHandler as you did for the action-attribute.

Create a log everytime When methods in an interface class are called

I want to update a log file(txt) everytime when methods in a an interface class are called?
Is there any way to do this other than writing code in every method to create log?
Here's my 30 mins. you'll have to implement the logging code somewhere so you have to create another abstraction for your code. thus an abstract class is needed. i think. this is very quick and dirty.
public interface IService<T>
{
List<T> GetAll();
bool Add(T obj);
}
then you'll need the abstract class where you'll need to implement your logging routine
public abstract class Service<T> : IService<T>
{
private void log()
{
/// TODO : do log routine here
}
public bool Add(T obj)
{
try
{
log();
return AddWithLogging(obj);
}
finally
{
log();
}
}
public List<T> GetAll()
{
try
{
log();
return GetAllWithLog();
}
finally
{
log();
}
}
protected abstract List<T> GetAllWithLog();
protected abstract bool AddWithLogging(T obj);
}
as for your concrete classes
public class EmployeeService : Service<Employee>
{
protected override List<Employee> GetAllWithLog()
{
return new List<Employee>() { new Employee() { Id = 0, Name = "test" } };
}
protected override bool AddWithLogging(Employee obj)
{
/// TODO : do add logic here
return true;
}
}
public class CompanyService : Service<Company>
{
protected override List<Company> GetAllWithLog()
{
return new List<Company>() { new Company() { Id = 0, Name = "test" } };
}
protected override bool AddWithLogging(Company obj)
{
/// TODO : do add logic here
return true;
}
}
public class Employee
{
public int Id {get;set;}
public string Name { get; set;}
}
public class Company
{
public int Id { get; set; }
public string Name { get; set; }
}
then on your implementation you can just..
static void Main(string[] args)
{
IService<Employee> employee = new EmployeeService();
List<Employee> employees = employee.GetAll();
foreach (var item in employees)
{
Console.WriteLine(item.Name);
}
IService<Company> company = new CompanyService();
List<Company> companies = company.GetAll();
foreach (var item in companies)
{
Console.WriteLine(item.Name);
}
Console.ReadLine();
}
hope this helps!
I think you would have to use Aspect Oriented Programming to achieve that. Read http://www.sharpcrafters.com/aop.net
I think you meant class (instead of interface)
Two options I can think of:
Implementing INotifyPropertyChanged which is in lines of writing code in every method
or
to adopt on of the AOP frameworks in the article http://www.codeproject.com/KB/cs/AOP_Frameworks_Rating.aspx if that is not a major leap

Resources