Core Ajax for State and country combo box to be used in JSP.
ajaxTest.jsp
<%#page contentType="text/html" pageEncoding="UTF-8" import="com.test.AjaxClass.*"%>
AJAX Page
var XmlHttp=false;
function CreateXmlHttp()
{
try
{
XmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); //for IE6
}
catch(e)
{
try
{
XmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(oc)
{
XmlHttp = new XMLHttpRequest();//for browser mozila, opera, firefox.
}
}
}
function cState(){
var countid = document.getElementById('country').value;
CreateXmlHttp();
XmlHttp.onreadystatechange=HandleResponse;
XmlHttp.open("GET", "any.jsp?r=Math.random()&countid="+countid, true);
XmlHttp.send(null);
}
function HandleResponse(){
var stateobj = document.getElementById("state");
stateobj.options.length = 0;
if(XmlHttp.readyState==4 || XmlHttp.readyState=="complete"){
var XmlRoot = XmlHttp.responseXML.documentElement;
var xRows = XmlRoot.getElementsByTagName("check");
for(var i=0; i<xRows.length; i++){
var stateid = xRows[i].childNodes[0].firstChild.nodeValue;
var statename = xRows[i].childNodes[1].firstChild.nodeValue;
stateobj.options[i] = new Option(statename,stateid);
}
}
}
</script>
</head>
<body>
<select onchange="cState();" name="country" id="country">
<option value="0">Select Country</option>
<%
for (CountryClass cc : ajax.getCoutryList()) {
%>
<option value="<%=cc.getCountryid()%>"><%=cc.getCountryName()%></option>
<% }
%>
</select>
<select name="state" id="state">
</select>
</body>
any.jsp
<?xml version="1.0"?>
<%#page contentType="text/xml" pageEncoding="UTF-8" import="com.test.AjaxClass.*"%>
<%
int countid = Integer.parseInt(request.getParameter("countid"));
//System.out.println("tt :: " + countid);
java.util.List statelist = call.changeState(countid);
//System.out.println("length ::" + statelist.size());
for (StateClass sc : statelist) {
%>
<%=sc.getStateid()%>
<%=sc.getStateName()%>
<%
}
%>
AjaxClass.java
package com.test;
import java.util.ArrayList;
import java.util.List;
public class AjaxClass {
private List<CountryClass> coutryList = new ArrayList<CountryClass>();
public List<CountryClass> getCoutryList() {
coutryList.add(new CountryClass(1, "India"));
coutryList.add(new CountryClass(2, "Pakistan"));
coutryList.add(new CountryClass(3, "Bangladesh"));
coutryList.add(new CountryClass(4, "U.A.E."));
return coutryList;
}
public void setCoutryList(List<CountryClass> coutryList) {
this.coutryList = coutryList;
}
public class CountryClass {
public Integer countryid;
public String countryName;
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
public Integer getCountryid() {
return countryid;
}
public void setCountryid(Integer countryid) {
this.countryid = countryid;
}
public CountryClass(Integer countryid, String countryName) {
this.countryid = countryid;
this.countryName = countryName;
}
}
private List<StateClass> stateList = new ArrayList<StateClass>();
public List<StateClass> getStateList() {
stateList.add(new StateClass(1, 1, "Gujarat"));
stateList.add(new StateClass(2, 1, "Maharashtra"));
stateList.add(new StateClass(3, 2, "Karachi"));
stateList.add(new StateClass(4, 2, "Lahore"));
stateList.add(new StateClass(5, 3, "Dhaka"));
stateList.add(new StateClass(6, 3, "Chittagong"));
stateList.add(new StateClass(7, 4, "Dubai"));
stateList.add(new StateClass(8, 4, "Behrin"));
stateList.add(new StateClass(9, 4, "Sarjah"));
return stateList;
}
public void setStateList(List<StateClass> stateList) {
this.stateList = stateList;
}
public class StateClass {
Integer stateid;
Integer countryref;
String stateName;
public Integer getCountryref() {
return countryref;
}
public void setCountryref(Integer countryref) {
this.countryref = countryref;
}
public String getStateName() {
return stateName;
}
public void setStateName(String stateName) {
this.stateName = stateName;
}
public Integer getStateid() {
return stateid;
}
public void setStateid(Integer stateid) {
this.stateid = stateid;
}
public StateClass(Integer stateid, Integer countryref, String stateName) {
this.stateid = stateid;
this.countryref = countryref;
this.stateName = stateName;
}
}
public List<StateClass> changeState(Integer countryref) {
List<StateClass> newList = new ArrayList<AjaxClass.StateClass>();
for (StateClass stateClass : getStateList()) {
if (stateClass.countryref == countryref) {
newList.add(stateClass);
}
}
return newList;
}
}
Related
While developing xamarin forms custom webview, when I try to load URL from assets folder, getting below error
[AndroidProtocolHandler] Unable to open asset URL: file:///android_asset/www/sf.min.js
This is my code
ChatbotView.xaml file
<controls:HybridWebView
x:Name="webView"
Uri="TestWebPage.html"
Margin="10"
BackgroundColor="Red"
HorizontalOptions="FillAndExpand"
VerticalOptions="FillAndExpand" />
This is ChatbotViewModel and HybridWebView class
public class ChatbotViewModel: BaseViewModel
{
public UrlWebViewSource SourceContent { get; set; }
public ChatbotViewModel()
{
var source = new UrlWebViewSource();
var baseUrl = DependencyService.Get<IBaseUrl>().Get();
string filePathUrl = Path.Combine(baseUrl, "TestWebPage.html");
source.Url = filePathUrl;
SourceContent = source;
}
}
public interface IBaseUrl { string Get(); }
public class HybridWebView : WebView
{
Action<string> action;
public static readonly BindableProperty UriProperty = BindableProperty.Create(
propertyName: "Uri",
returnType: typeof(string),
declaringType: typeof(HybridWebView),
defaultValue: default(string));
public string Uri
{
get { return (string)GetValue(UriProperty); }
set { SetValue(UriProperty, value); }
}
public void RegisterAction(Action<string> callback)
{
action = callback;
}
public void Cleanup()
{
action = null;
}
public void InvokeAction(string data)
{
if (action == null || data == null)
{
return;
}
action.Invoke(data);
}
}
This is HybridWebViewRenderer, JavascriptWebViewClient and JSBridge class
public class HybridWebViewRenderer : WebViewRenderer
{
const string JavascriptFunction = "function Chat1(data){jsBridge.invokeAction(data);}";
Context _context;
public HybridWebViewRenderer(Context context) : base(context)
{
_context = context;
}
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.WebView> e)
{
base.OnElementChanged(e);
if (e.OldElement != null)
{
Control.RemoveJavascriptInterface("jsBridge");
((HybridWebView)Element).Cleanup();
}
if (e.NewElement != null)
{
Control.SetWebViewClient(new JavascriptWebViewClient(this, $"javascript: {JavascriptFunction}"));
Control.AddJavascriptInterface(new JSBridge(this), "jsBridge");
Control.Settings.AllowFileAccess = true;
Control.Settings.JavaScriptEnabled = true;
Control.Settings.SetAppCacheMaxSize(100000000);
Control.Settings.AllowFileAccessFromFileURLs = true;
Control.Settings.AllowUniversalAccessFromFileURLs = true;
Control.Settings.AllowContentAccess = true;
Control.SetWebChromeClient(new WebChromeClient());
Control.SetWebViewClient(new WebViewClient());
var myUlr2 = $"file:///android_asset/TestWebPage.html";
Control.LoadUrl(myUlr2);
}
}
public class JavascriptWebViewClient : FormsWebViewClient
{
string _javascript;
public JavascriptWebViewClient(HybridWebViewRenderer renderer, string javascript) : base(renderer)
{
_javascript = javascript;
}
public override void OnPageFinished(Android.Webkit.WebView view, string url)
{
base.OnPageFinished(view, url);
view.EvaluateJavascript(_javascript, null);
}
}
public class JSBridge : Java.Lang.Object
{
readonly WeakReference<HybridWebViewRenderer> hybridWebViewRenderer;
public JSBridge(HybridWebViewRenderer hybridRenderer)
{
hybridWebViewRenderer = new WeakReference<HybridWebViewRenderer>(hybridRenderer);
}
[JavascriptInterface]
[Export("invokeAction")]
public void InvokeAction(string data)
{
HybridWebViewRenderer hybridRenderer;
if (hybridWebViewRenderer != null && hybridWebViewRenderer.TryGetTarget(out hybridRenderer))
{
((HybridWebView)hybridRenderer.Element).InvokeAction(data);
}
}
}
}
Below is TestWebpage.html file. This file is accessing one of JavaScript file from assets folder
<script type='text/javascript' src='file:///android_asset/www/sf.min.js'></script>
sf.min.js is not getting loaded and throwing error.
<html>
<body>
<button onclick="Chat1()">Submit</button>
<script type='text/javascript' src='file:///android_asset/www/sf.min.js'></script>
<script type='text/javascript'>
function Chat1() {
var initESW = function (gslbBaseURL) {
embedded_svc.settings.displayHelpButton = true; //Or false
embedded_svc.settings.language = ''; //For example, enter 'en' or 'en-US'
embedded_svc.settings.enabledFeatures = ['LiveAgent'];
embedded_svc.settings.entryFeature = 'LiveAgent';
embedded_svc.init(
'https://ulr.my.salesforce.com',
'https://ulr.force.com/visualforce',
gslbBaseURL,
'00D7a00000055uj',
'US_Universities',
{
'baseLiveAgentContentURL': 'https://c.la3-c1cs-cdg.salesforceliveagent.com/content',
'deploymentId': '720008Oqg',
'buttonId': '5730PID',
'baseLiveAgentURL': 'https://d.la3-c1cs-cdg.salesforceliveagent.com/chat',
'eswLiveAgentDevName': 'EmbeddedServiceLiveAgent_Parent0000000jLUAQ_17d9a605e8e',
'isOfflineSupportEnabled': false
}
);
};
if (!window.embedded_svc) {
var s = document.createElement('script');
console.log("Control here1")
var sdxMin = 'https://ulr.salesforce.com/embeddedservice/5.0/esw.min.js/'
console.log("Control here2")
s.src = sdxMin;
console.log("Control here3")
s.onload = function () {
initESW(null);
}
document.body.appendChild(s);
}
else {
initESW('https://service.force.com');
}
}
</script>
</body>
</html>
doc.microsoft webview, this I have followed for development. How can I fix this error ?
Edit 1 : Screenshot of Assets folder
From my perspective,you haven't put the sf.min.js file under Assets/www/sf.min.js folder.When compiling the TestWebpage.html, the system can't detect the js file as a result of the error "[AndroidProtocolHandler] Unable to open asset URL: file:///android_asset/www/sf.min.js".
I am having difficulty displaying a web page in a webview in xamarin forms application.
I started out with eshoponcontainers sample application. which went well till I got to the login stage. When the Authorization request is sent the login page doesnt show up. A test in postman revealed an unathorised client error so I was expecting to see that page loaded in my webview but that is not happening.
My .xaml page is as follows
<AbsoluteLayout
Grid.Column="0"
Grid.ColumnSpan="3"
Grid.Row="0"
Grid.RowSpan="2"
IsVisible="{Binding IsLogin}">
<WebView
Source="{Binding LoginUrl}"
AbsoluteLayout.LayoutBounds="0, 0, 1, 1"
AbsoluteLayout.LayoutFlags="All">
<WebView.Behaviors>
<OnPlatform x:TypeArguments="Behavior">
<On Platform="iOS, Android">
<On.Value>
<behaviors:EventToCommandBehavior
EventName="Navigating"
EventArgsConverter="{StaticResource WebNavigatingEventArgsConverter}"
Command="{Binding NavigateCommand}" />
</On.Value>
</On>
<On Platform="UWP">
<On.Value>
<behaviors:EventToCommandBehavior
EventName="Navigated"
EventArgsConverter="{StaticResource WebNavigatedEventArgsConverter}"
Command="{Binding NavigateCommand}" />
</On.Value>
</On>
</OnPlatform>
</WebView.Behaviors>
</WebView>
</AbsoluteLayout>
The code behind looks like this
public partial class LoginView : ContentPage
{
private bool _animate;
public LoginView ()
{
InitializeComponent ();
}
protected override async void OnAppearing()
{
var content = this.Content;
this.Content = null;
this.Content = content;
var vm = BindingContext as LoginViewModel;
if (vm != null)
{
vm.InvalidateMock();
if (!vm.IsMock)
{
_animate = true;
await AnimateIn();
}
}
}
protected override void OnDisappearing()
{
_animate = false;
}
public async Task AnimateIn()
{
if (Device.RuntimePlatform == Device.UWP)
{
return;
}
await AnimateItem(Banner, 10500);
}
private async Task AnimateItem(View uiElement, uint duration)
{
try
{
while (_animate)
{
await uiElement.ScaleTo(1.05, duration, Easing.SinInOut);
await Task.WhenAll(
uiElement.FadeTo(1, duration, Easing.SinInOut),
uiElement.LayoutTo(new Rectangle(new Point(0, 0), new Size(uiElement.Width, uiElement.Height))),
uiElement.FadeTo(.9, duration, Easing.SinInOut),
uiElement.ScaleTo(1.15, duration, Easing.SinInOut)
);
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
}
I have the following inthe "LoginViewModel"
public class LoginViewModel: ViewModelBase
{
private ValidatableObject<string> _userName;
private ValidatableObject<string> _password;
private bool _isMock;
private bool _isValid;
private bool _isLogin;
private string _authUrl;
private ISettingsService _settingsService;
private IOpenUrlService _openUrlService;
private IIdentityService _identityService;
public LoginViewModel(
ISettingsService settingsService,
IOpenUrlService openUrlService,
IIdentityService identityService)
{
_settingsService = settingsService;
_openUrlService = openUrlService;
_identityService = identityService;
_userName = new ValidatableObject<string>();
_password = new ValidatableObject<string>();
InvalidateMock();
AddValidations();
}
public ValidatableObject<string> UserName
{
get
{
return _userName;
}
set
{
_userName = value;
RaisePropertyChanged(() => UserName);
}
}
public ValidatableObject<string> Password
{
get
{
return _password;
}
set
{
_password = value;
RaisePropertyChanged(() => Password);
}
}
public bool IsMock
{
get
{
return _isMock;
}
set
{
_isMock = value;
RaisePropertyChanged(() => IsMock);
}
}
public bool IsValid
{
get
{
return _isValid;
}
set
{
_isValid = value;
RaisePropertyChanged(() => IsValid);
}
}
public bool IsLogin
{
get
{
return _isLogin;
}
set
{
_isLogin = value;
RaisePropertyChanged(() => IsLogin);
}
}
public string LoginUrl
{
get
{
return _authUrl;
}
set
{
_authUrl = value;
RaisePropertyChanged(() => LoginUrl);
}
}
public ICommand MockSignInCommand => new Command(async () => await MockSignInAsync());
public ICommand SignInCommand => new Command(async () => await SignInAsync());
public ICommand RegisterCommand => new Command(Register);
public ICommand NavigateCommand => new Command<string>(async (url) => await NavigateAsync(url));
public ICommand SettingsCommand => new Command(async () => await SettingsAsync());
public ICommand ValidateUserNameCommand => new Command(() => ValidateUserName());
public ICommand ValidatePasswordCommand => new Command(() => ValidatePassword());
public override Task InitializeAsync(object navigationData)
{
if (navigationData is LogoutParameter)
{
var logoutParameter = (LogoutParameter)navigationData;
if (logoutParameter.Logout)
{
Logout();
}
}
return base.InitializeAsync(navigationData);
}
private async Task MockSignInAsync()
{
IsBusy = true;
IsValid = true;
bool isValid = Validate();
bool isAuthenticated = false;
if (isValid)
{
try
{
await Task.Delay(10);
isAuthenticated = true;
}
catch (Exception ex)
{
Debug.WriteLine($"[SignIn] Error signing in: {ex}");
}
}
else
{
IsValid = false;
}
if (isAuthenticated)
{
_settingsService.AuthAccessToken = GlobalSetting.Instance.AuthToken;
await NavigationService.NavigateToAsync<MainViewModel>();
await NavigationService.RemoveLastFromBackStackAsync();
}
IsBusy = false;
}
private async Task SignInAsync()
{
IsBusy = true;
await Task.Delay(10);
LoginUrl = _identityService.CreateAuthorizationRequest();
IsValid = true;
IsLogin = true;
IsBusy = false;
}
private void Register()
{
_openUrlService.OpenUrl(GlobalSetting.Instance.RegisterWebsite);
}
private void Logout()
{
var authIdToken = _settingsService.AuthIdToken;
var logoutRequest = _identityService.CreateLogoutRequest(authIdToken);
if (!string.IsNullOrEmpty(logoutRequest))
{
// Logout
LoginUrl = logoutRequest;
}
if (_settingsService.UseMocks)
{
_settingsService.AuthAccessToken = string.Empty;
_settingsService.AuthIdToken = string.Empty;
}
_settingsService.UseFakeLocation = false;
}
private async Task NavigateAsync(string url)
{
var unescapedUrl = System.Net.WebUtility.UrlDecode(url);
if (unescapedUrl.Equals(GlobalSetting.Instance.LogoutCallback))
{
_settingsService.AuthAccessToken = string.Empty;
_settingsService.AuthIdToken = string.Empty;
IsLogin = false;
LoginUrl = _identityService.CreateAuthorizationRequest();
}
else if (unescapedUrl.Contains(GlobalSetting.Instance.IdentityCallback))
{
var authResponse = new AuthorizeResponse(url);
if (!string.IsNullOrWhiteSpace(authResponse.Code))
{
var userToken = await _identityService.GetTokenAsync(authResponse.Code);
string accessToken = userToken.AccessToken;
if (!string.IsNullOrWhiteSpace(accessToken))
{
_settingsService.AuthAccessToken = accessToken;
_settingsService.AuthIdToken = authResponse.IdentityToken;
await NavigationService.NavigateToAsync<MainViewModel>();
await NavigationService.RemoveLastFromBackStackAsync();
}
}
}
}
private async Task SettingsAsync()
{
await NavigationService.NavigateToAsync<SettingsViewModel>();
}
private bool Validate()
{
bool isValidUser = ValidateUserName();
bool isValidPassword = ValidatePassword();
return isValidUser && isValidPassword;
}
private bool ValidateUserName()
{
return _userName.Validate();
}
private bool ValidatePassword()
{
return _password.Validate();
}
private void AddValidations()
{
_userName.Validations.Add(new IsNotNullOrEmptyRule<string> { ValidationMessage = "A username is required." });
_password.Validations.Add(new IsNotNullOrEmptyRule<string> { ValidationMessage = "A password is required." });
}
public void InvalidateMock()
{
IsMock = _settingsService.UseMocks;
}
}
I am creating an API for project tasks. It has a TasksController as listed below. I am generating hypermedia using WebApi.Hal and the service supports hal+json and hal+xml media types also.
Following is the response I currently have for the GET request http://localhost:51910/api/tasks/1. In the response there is a list of links for priorities – but they don’t have associated name in the response (to show in the UI – like Low, Medium, High, etc.).
What is the best HAL approach for getting name of the priorities also, using WebApi.HAL?
Note: The list of priorities can be enhanced in the future.
Priority
public class Priority
{
public int PriorityID { get; set; }
public string PriorityName { get; set; }
public string Revision { get; set; }
public DateTime ApprovalDate { get; set; }
}
Controller
public class TasksController : ApiController
{
// GET api/values/5
[HttpGet]
public TaskRepresentation Get(int id)
{
Task selectedTask = TasksHelper.GetTask(id);
TaskRepresentation taskRepresentation = new TaskRepresentation(selectedTask);
return taskRepresentation;
}
//PUT For Setting Priority
[HttpPut]
[Route("api/tasks/{taskID}/priorities/{priorityID}")]
public TaskRepresentation PutSetPriority(int taskID, int priorityID)
{
Task selectedTask = TasksHelper.GetTask(taskID);
Priority selectedPriority = null;
List<Priority> allPriorities = TasksPrioritiesHelper.GetAllPriorities();
foreach (Priority p in allPriorities)
{
if (p.PriorityID == priorityID)
{
selectedPriority = p;
}
}
//Update Task
if (selectedPriority != null)
{
selectedTask.CurrentPriority = selectedPriority.PriorityName;
}
else
{
throw new Exception("Not available");
}
TaskRepresentation taskRepresentation = new TaskRepresentation(selectedTask);
return taskRepresentation;
}
[HttpGet]
[Route("api/tasks/{taskID}/priorities/{priorityID}")]
public Priority Get(int taskID, int priorityID)
{
Priority selectedPriority = null;
List<Priority> allPriorities = TasksPrioritiesHelper.GetAllPriorities();
foreach (Priority p in allPriorities)
{
if (p.PriorityID == priorityID)
{
selectedPriority = p;
}
}
return selectedPriority;
}
}
HAL Generation Related Classes
public static class LinkTemplates
{
public static class TaskLinks
{
public static Link TaskEntry { get { return new Link("self", "~/api/tasks/{taskID}"); } }
public static Link PriorityLink { get { return new Link("priorities", "~/api/tasks/{taskID}/priorities/{priorityID}"); } }
}
}
public class TaskRepresentation : Representation
{
Task theTask;
public int TaskID{get{return theTask.TaskID;}}
public string TaskName{get{return theTask.Name;}}
public string CurrentPriority{get{return theTask.CurrentPriority;}}
public string Category{get{return theTask.Category;}}
public TaskRepresentation(Task t)
{
theTask = t;
}
public override string Rel
{
get { return LinkTemplates.TaskLinks.TaskEntry.Rel; }
set { }
}
public override string Href
{
get { return LinkTemplates.TaskLinks.TaskEntry.CreateLink(new { taskID = theTask.TaskID }).Href; }
set { }
}
protected override void CreateHypermedia()
{
foreach (Priority p in theTask.PossiblePriorities)
{
Links.Add(LinkTemplates.TaskLinks.PriorityLink.CreateLink(new { taskID = theTask.TaskID, priorityID = p.PriorityID }));
}
}
}
HAL Specification mentions title - this will meet the requirement.
Following is the updated response.
{
"TaskID": 1,
"TaskName": "Task1",
"CurrentPriority": "Medium",
"Category": "IT",
"_links": {
"self": {
"href": "/api/tasks/1"
},
"priorities": [
{
"href": "/api/tasks/1/priorities/101",
"title": "Low"
},
{
"href": "/api/tasks/1/priorities/103",
"title": "High"
},
{
"href": "/api/tasks/1/priorities/104",
"title": "Critical"
}
]
}
}
WebAPI.HAL changes
protected override void CreateHypermedia()
{
foreach (Priority p in theTask.PossiblePriorities)
{
Link lnk = LinkTemplates.TaskLinks.PriorityLink.CreateLink(new { taskID = theTask.TaskID, priorityID = p.PriorityID });
lnk.Title = p.PriorityName;
Links.Add(lnk);
}
}
Code
public static class LinkTemplates
{
public static class TaskLinks
{
public static Link TaskEntry { get { return new Link("self", "~/api/tasks/{taskID}"); } }
//public static Link PriorityLink { get { return new Link("priorities", "~/api/tasks/{taskID}/priorities/{priorityID}"); } }
public static Link PriorityLink
{
get
{
Link l = new Link("priorities", "~/api/tasks/{taskID}/priorities/{priorityID}");
return l;
}
}
}
}
public class TasksController : ApiController
{
// GET api/values/5
[HttpGet]
public TaskRepresentation Get(int id)
{
Task selectedTask = TasksHelper.GetTask(id);
TaskRepresentation taskRepresentation = new TaskRepresentation(selectedTask);
return taskRepresentation;
}
//PUT For Setting Priority
[HttpPut]
[Route("api/tasks/{taskID}/priorities/{priorityID}")]
public TaskRepresentation PutSetPriority(int taskID, int priorityID)
{
Task selectedTask = TasksHelper.GetTask(taskID);
Priority selectedPriority = null;
List<Priority> allPriorities = TasksPrioritiesHelper.GetAllPriorities();
foreach (Priority p in allPriorities)
{
if (p.PriorityID == priorityID)
{
selectedPriority = p;
}
}
//Update Task
if (selectedPriority != null)
{
selectedTask.CurrentPriority = selectedPriority.PriorityName;
}
else
{
throw new Exception("Not available");
}
TaskRepresentation taskRepresentation = new TaskRepresentation(selectedTask);
return taskRepresentation;
}
[HttpGet]
[Route("api/tasks/{taskID}/priorities/{priorityID}")]
public Priority Get(int taskID, int priorityID)
{
Priority selectedPriority = null;
List<Priority> allPriorities = TasksPrioritiesHelper.GetAllPriorities();
foreach (Priority p in allPriorities)
{
if (p.PriorityID == priorityID)
{
selectedPriority = p;
}
}
return selectedPriority;
}
}
public class TaskRepresentation : Representation
{
Task theTask;
public int TaskID{get{return theTask.TaskID;}}
public string TaskName{get{return theTask.Name;}}
public string CurrentPriority{get{return theTask.CurrentPriority;}}
public string Category{get{return theTask.Category;}}
public TaskRepresentation(Task t)
{
theTask = t;
}
public override string Rel
{
get { return LinkTemplates.TaskLinks.TaskEntry.Rel; }
set { }
}
public override string Href
{
get { return LinkTemplates.TaskLinks.TaskEntry.CreateLink(new { taskID = theTask.TaskID }).Href; }
set { }
}
protected override void CreateHypermedia()
{
foreach (Priority p in theTask.PossiblePriorities)
{
Link lnk = LinkTemplates.TaskLinks.PriorityLink.CreateLink(new { taskID = theTask.TaskID, priorityID = p.PriorityID });
lnk.Title = p.PriorityName;
Links.Add(lnk);
}
}
}
public class Task
{
public string Name { get; set; }
public int TaskID { get; set; }
public string Category { get; set; }
public string CurrentPriority { get; set; }
public List<Priority> PossiblePriorities { get; set; }
}
public class Priority
{
public int PriorityID { get; set; }
public string PriorityName { get; set; }
public string Revision { get; set; }
public DateTime ApprovalDate { get; set; }
}
public static class TasksPrioritiesHelper
{
public static List<Priority> GetAllPriorities()
{
List<Priority> possiblePriorities = new List<Priority>();
Priority pLow = new Priority { PriorityID = 101, PriorityName = "Low" };
Priority pMedium = new Priority { PriorityID = 102, PriorityName = "Medium" };
Priority pHigh = new Priority { PriorityID = 103, PriorityName = "High" };
Priority pCritical = new Priority { PriorityID = 104, PriorityName = "Critical" };
possiblePriorities.Add(pLow);
possiblePriorities.Add(pMedium);
possiblePriorities.Add(pHigh);
possiblePriorities.Add(pCritical);
return possiblePriorities;
}
public static List<Priority> GetAdministrativePriorities()
{
List<Priority> possiblePriorities = new List<Priority>();
Priority pLow = new Priority { PriorityID = 101, PriorityName = "Low" };
Priority pHigh = new Priority { PriorityID = 103, PriorityName = "High" };
possiblePriorities.Add(pLow);
possiblePriorities.Add(pHigh);
return possiblePriorities;
}
public static List<Priority> GetPossiblePrioritiesForTask(Task t)
{
List<Priority> possibleTaskPriorities = new List<Priority>();
if (String.Equals(t.Category, "IT"))
{
possibleTaskPriorities = GetAllPriorities();
}
else
{
possibleTaskPriorities = GetAdministrativePriorities();
}
Priority currentTaskPriority = null;
foreach(Priority p in possibleTaskPriorities )
{
if(String.Equals(t.CurrentPriority,p.PriorityName ))
{
currentTaskPriority=p;
}
}
if(currentTaskPriority!=null)
{
possibleTaskPriorities.Remove(currentTaskPriority);
}
return possibleTaskPriorities;
}
}
public static class TasksHelper
{
public static Task GetTask(int id)
{
Task selectedTask = null;
List<Task> tasks = GetAllTasks();
foreach (Task t in tasks)
{
if(t.TaskID==id)
{
selectedTask = t;
}
}
return selectedTask;
}
public static List<Task> GetAllTasks()
{
List<Task> tasks;
tasks = new List<Task>();
Task t1 = new Task{Category = "IT",CurrentPriority = "Medium",Name = "Task1",TaskID = 1};
t1.PossiblePriorities = TasksPrioritiesHelper.GetPossiblePrioritiesForTask(t1);
tasks.Add(t1);
return tasks;
}
}
Repository
namespace AgenziaMatrimoniale.DataAccess {
public class AgenziaMatrimonialeRepository
{
private readonly string _connectionString = ConfigurationManager.ConnectionStrings["AgenziaMatrimonialeConnectionString"].ConnectionString;
public List<Candidato> FindSimple(int? id, string sesso, string citta)
{
List<Candidato> result = new List<Candidato>();
string query = "SELECT * FROM Candidato";
using (var connection = new SqlConnection(_connectionString))
{
SqlCommand command = new SqlCommand(query, connection);
try
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
var dbId = Convert.ToInt32(reader["Id"]);
var dbNome = Convert.ToString(reader["Nome"]);
var dbCognome = Convert.ToString(reader["Cognome"]);
var dbSesso = Convert.ToString(reader["Sesso"]);
var dbCitta = Convert.ToString(reader["Citta"]);
var dbProfessione = Convert.ToString(reader["Professione"]);
var dbDescrizione = Convert.ToString(reader["Descrizione"]);
if (id.HasValue && dbId == id)
{
AggiungiCandidatoAiRisultati(result, dbId, dbNome, dbCognome, dbSesso, dbCitta, dbProfessione, dbDescrizione);
}
else if (!id.HasValue
&& (string.IsNullOrEmpty(sesso) || dbSesso==sesso)
&& (string.IsNullOrEmpty(citta)|| dbCitta.ToLower().Contains(citta.ToLower())))
{
AggiungiCandidatoAiRisultati(result, dbId, dbNome, dbCognome, dbSesso, dbCitta, dbProfessione, dbDescrizione);
}
}
reader.Close();
}
catch (Exception ex)
{
Debug.WriteLine(string.Format("Errore applicativo: {0}", ex.Message));
throw ex;
}
}
return result;
}
public Candidato FindCandidato(int id)
{
List<Candidato> candidati = FindSimple(id, null, null);
if (candidati.Count == 1)
{
return candidati[0];
}
return null;
}
Controller
namespace AgenziaMatrimoniale.Controllers
{
public class CandidatoController : Controller
{
private readonly AgenziaMatrimonialeRepository _repository;
public CandidatoController()
{
_repository = new AgenziaMatrimonialeRepository();
}
public ActionResult Index(string sesso, string citta)
{
List<Candidato> candidati = _repository.FindSimple(null, sesso, citta);
List<SelectListItem> sessi= new List<SelectListItem> {
new SelectListItem { Text = "Maschio", Value = "M" },
new SelectListItem { Text = "Femmina", Value = "F" }
};
ViewBag.sesso = sessi;
return View(candidati);
}
public ActionResult Details(int id)
{
Candidato candidato = _repository.FindCandidato(id);
return View(candidato);
}
}
}
It depends...if you're trying to fill a table with data collected from a DB and possibly filter that data....then you are doing just fine.
You remind me this little piece of code that's just VERY similar.
using Prova1.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Linq;
using System.Web;
namespace Prova1.DataAccess
{
public class ProvaRepository
{
private readonly string _connectionString = ConfigurationManager.ConnectionStrings["StringConnectionName"].ConnectionString;
public List<Modello> Find(int? id, string filtro1, string filtro2)
{
List<Modello> result = new List<Modello>();
string query = "SELECT * FROM Tabella";
using (var connection = new SqlConnection(_connectionString))
{
SqlCommand command = new SqlCommand(query, connection);
try
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
var dbId = Convert.ToInt32(reader["Id"]);
var dbCampo1 = Convert.ToString(reader["Campo1"]);
var dbCampo2 = Convert.ToString(reader["Campo2"]);
var dbCampo3 = Convert.ToString(reader["Campo3"]);
Modello modello = new Modello();
if (id.HasValue && dbId == id)
{
AddModello(result, dbId, dbCampo1, dbCampo2, dbCampo3, modello);
}
else if (!id.HasValue
&& (string.IsNullOrEmpty(filtro1) || dbCampo1.ToLower().Contains(filtro1.ToLower()))
&& (string.IsNullOrEmpty(filtro2) || dbCampo2.ToLower().Contains(filtro2.ToLower()))
)
{
AddModello(result, dbId, dbCampo1, dbCampo2, dbCampo3, modello);
}
}
reader.Close();
}
catch (Exception ex)
{
Debug.WriteLine(string.Format("Errore Applicativo {0}: ", ex.Message));
throw ex;
}
}
return result;
}
private static void AddModello(List<Modello> result, int dbId, string dbCampo1, string dbCampo2, string dbCampo3, Modello modello)
{
modello.Id = dbId;
modello.Campo1 = dbCampo1;
modello.Campo2 = dbCampo2;
modello.Campo3 = dbCampo3;
result.Add(modello);
}
public Modello FindDetail(int id)
{
List<Modello> modello = Find(id, null, null);
if (modello.Count == 1)
{
return modello[0];
}
return null;
}
}
}
Edit: I forgot the Controller
using Prova1.DataAccess;
using Prova1.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Prova1.Controllers
{
public class ProvaController : Controller
{
private readonly ProvaRepository _repository;
public ProvaController()
{
_repository = new ProvaRepository();
}
// GET: Prova
public ActionResult Index(string filtro1, string filtro2)
{
List<Modello> modelli = _repository.Find(null, filtro1, filtro2);
return View(modelli);
}
public ActionResult Detail(int id)
{
Modello modello = _repository.FindDetail(id);
return View(modello);
}
}
}
Trying to set value for Spring MVC portlet:actionURL portlet:param but for some reason the EL doesn't parse the JSTL. Please see below for the detail of Message.java and MessageForm.java and Message.java does implement equals() and hascode(), running as Spring MVC Portlet in WebSphere Portal Server v8.0 and JDK 1.6.
Here is my JSP:
<c:forEach items="${messageForm.messageList}" var="message" varStatus="status">
<HTMLWRAPPER name="Message_Repeat">
<tr sequence_class="tableRowPrimary,tableRowAlternate">
<td class="descriptionCell" width="150" align="Center"><form:hidden path="messageList[${status.index}].subject"/>
<a href='
<portlet:actionURL>
<portlet:param name="action" value="detail"/>
<portlet:param name="id" value="${message.id}"/>
</portlet:actionURL>'><c:out value="${message.subject}"/></a>
</td>
</tr>
</HTMLWRAPPER>
</c:forEach>
Using Spring MVC portlet v3.2.8 and below are the taglibs:
<%# taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<%# taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
Message.java
public class Message implements Serializable {
private static final long serialVersionUID = 1L;
Integer id;
String type;
String subject;
String receiveDate;
String expireDate;
boolean readFlag;
boolean deleteFlag;
String body;
ArrayList<Attachment> attachmentList;
Integer attachmentCount;
String toAddress;
String fromAddress = "From Online";
public String getToAddress() {
return toAddress;
}
public void setToAddress(String toAddress) {
this.toAddress = toAddress;
}
public String getFromAddress() {
return fromAddress;
}
public void setFromAddress(String fromAddress) {
this.fromAddress = fromAddress;
}
public ArrayList<Attachment> getAttachmentList() {
return attachmentList;
}
public void setAttachmentList(ArrayList<Attachment> attachmentList) {
this.attachmentList = attachmentList;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public Integer getAttachmentCount() {
return attachmentCount;
}
public void setAttachmentCount(Integer attachmentCount) {
this.attachmentCount = attachmentCount;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getReceiveDate() {
return receiveDate;
}
public void setReceiveDate(String receiveDate) {
this.receiveDate = receiveDate;
}
public String getExpireDate() {
return expireDate;
}
public void setExpireDate(String expireDate) {
this.expireDate = expireDate;
}
public boolean isDeleteFlag() {
return deleteFlag;
}
public void setDeleteFlag(boolean deleteFlag) {
this.deleteFlag = deleteFlag;
}
public boolean isReadFlag() {
return readFlag;
}
public void setReadFlag(boolean readFlag) {
this.readFlag = readFlag;
}
#Override
public boolean equals(Object object) {
boolean result = false;
if (object == null || object.getClass() != getClass()) {
result = false;
} else {
Message message = (Message) object;
if (this.getType() == message.getType()
&& this.getId() == message.getId()) {
result = true;
}
}
return result;
}
#Override
public int hashCode() {
int hash = 3;
hash = 7 * hash + this.id.hashCode();
hash = 7 * hash + this.subject.hashCode();
return hash;
}
}
MessageForm.java
public class MessageForm implements Serializable {
private static final long serialVersionUID = 1L;
public ArrayList<Message> messageList = new ArrayList<Message>();
public String delMsgConf;
public String getDelMsgConf() {
return delMsgConf;
}
public void setDelMsgConf(String delMsgConf) {
this.delMsgConf = delMsgConf;
}
public ArrayList<Message> getMessageList() {
return messageList;
}
public void setMessageList(ArrayList<Message> messageList) {
this.messageList = messageList;
}
}
Here is the Controller:
#ActionMapping(params = "action=detail")
public void detailMessage(#ModelAttribute("messageForm") MessageForm messageForm, BindingResult result, Model model,#RequestParam(required=false, value="id") String id, ActionRequest actionRequest,ActionResponse actionResponse) throws Exception {
ArrayList<Message> messages = messageForm.getMessageList();
HttpServletRequest servletRequest = PortletUtils.getHttpServletRequest(actionRequest);
String sessionId = servletRequest.getSession().getId();
String messageId = actionRequest.getParameter("id");
When print out messageId it simply shows ${message.id} as value - any idea what am I doing wrong?