Redirecting to a second server is not using it's faces-config - jsf-2.2

I want to store all of my web site's images on a secondary file server to reduce database and main server work loads (there will eventually be a huge number of image files and the browser makes a totally separate request to load the images so I figured I may as well have a separate file server for them).
I have a standard link to forward users to the file server to allow them to upload picture files for products, however it appears not to be using the file server's faces-config file.
In a JSF page on the main server:
<a target="_blank" href="http://localhost:12631/FileServer/faces/ExternalSecure/ForwardUploadImagesProcessing.xhtml#{newEditProductBean.uploadPicviewfParamValues}" >Upload replacement image(s) for storage on #{authBackingBean.demoCompany}'s servers</a>
The forwarding page 'ForwardUploadImagesProcessing.xhtml' on the file server is as follows:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core">
<head>
<title>redirect</title>
</head>
<body>
<f:metadata>
<f:viewParam name="path" value="#{uploadImages.path}" />
<f:viewParam name="filename" value="#{uploadImages.fileName}" />
<f:viewParam name="productTypeName" value="#{uploadImages.productTypeName}" />
<f:viewParam name="productModel" value="#{uploadImages.productModel}" />
<f:event type="preRenderView" listener="#{uploadImages.processUploadEntityImages()}" />
</f:metadata>
</body>
</html>
The 'processUploadEntityImages()' method in the 'UploadImages' backing bean (see below) is called as expected and the System.out statement prints all of the passed f:viewParam values correctly, however the JSF navigation string 'process_UploadImages' does not load the page that it points to on the file server. How can I force it to switch to the file server and it's faces-config?
In the 'UploadImages' backing bean on the file server:
public String processUploadEntityImages()
{
System.out.println("processUploadEntityImages() " + path + " ; " + fileName + " ; " + productTypeName + " ; " + productModel);
return "process_UploadImages";
}
In the 'faces-config' of the file server:
<navigation-rule>
<navigation-case>
<from-outcome>process_UploadImages</from-outcome>
<to-view-id>/ExternalSecure/UploadImages.xhtml</to-view-id>
</navigation-case>
</navigation-rule>
<managed-bean>
<description>For uploading thumb and main images for entities. </description>
<managed-bean-name>uploadImages</managed-bean-name>
<managed-bean-class>processing.UploadImages</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>
In the web.xml on the file server:
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
I have a link on the index page of the file server that links to this page, and the 'UploadImages.xhtml' page is opened correctly using the 'process_UploadImages' navigation rule, so there is no problem there.
Thanks in advance.

I should have known this; I've used it before for redirecting to a JSF page from a link inside an email....
processUploadEntityImages() should look like this:
public void processUploadEntityImages()
{
System.out.println("processUploadEntityImages() " + path + " ; " + fileName + " ; " + productTypeName + " ; " + productModel);
FacesContext facesContext = FacesContext.getCurrentInstance();
NavigationHandler navigationHandler = facesContext.getApplication().getNavigationHandler();
navigationHandler.handleNavigation(facesContext, null, "process_UploadImages");
}

Related

Sending a PDF file in a REST Message

I am trying figure this out any help appreciated. Thanks in advance
The service is a file passthrough that picks up a PDF and then uses the BPL code below to create the rest wrapper and sends the stream data. I am not grabbing the stream from the inbound correctly, "request.Stream" or "request.StreamFC" always produces the following error.
Here is what is sent and returned in the message..
request:
*
<Stream>
15#%Library.FileCharacterStream
</Stream>
response:
<Stream>
Unable to load xml from message: Data at the root level is invalid. Line 1, position 1.
</Stream>
-I think my issue is I am not using the right class by using "%GlobalStreamCharacter", Or the raw PDF CDATA inbound I am not handling correctly
set context.RESTMessage.Stream=##class(%GlobalCharacterStream).%New()
I have tried using different Stream types...File, Binary....but no luck
-The general BPL below
/// BPL Definition
X
Data BPL [ XMLNamespace = "http://www.intersystems.com/bpl" ]
{
<process language='objectscript' request='Ens.StreamContainer' response='Ens.Response'
height='2000' width='2000' >
<context>
.....
.....
....
<code name='Create REST Message' xpos='200' ypos='250' >
<![CDATA[
set context.RESTMessage=##class(EnsLib.HTTP.GenericMessage).%New()
set context.RESTMessage.Stream=##class(%GlobalCharacterStream).%New()
set tSC=context.RESTMessage.Stream.Write(request.StreamFC)
set tSC=context.RESTMessage.HTTPHeaders.SetAt("application/xml","Content-Type")
set tSC=context.RESTMessage.HTTPHeaders.SetAt(context.RESTMessage.Stream.Size,"Content-
Length")
set tSC=context.RESTMessage.HTTPHeaders.SetAt("POST","HttpRequest")
]]>
</code>
You can try this code snippet. I got the answer in the community.
<call name='To application Rest' target='To application REST' async='0'>
<request type='EnsLib.REST.GenericMessage' >
<assign property="callrequest.Stream" value='##class(%Stream.GlobalCharacter).%New()'/>
<assign property="status" value='callrequest.Stream.CopyFrom(request.StreamFC)' action="set" />
<assign property="status" value='callrequest.HTTPHeaders.SetAt("application/xml", "Content-Type")' action="set" />
<assign property="status" value='callrequest.HTTPHeaders.SetAt(callrequest.Stream.Size, "Content-Length")' action="set" />
<assign property="status" value='callrequest.HTTPHeaders.SetAt("POST", "HttpRequest")' action="set" />
</request>
</call>

Azure Load test does not report data driven urls

I have a simple load test that basically executes a single webtest on a constant load. That webtest is hooked to an xml file data source that contains urls to my entire site.
When I execute the load test from my local environment, the test summary page reports the individual urls in the "Top 5 slowest pages" i.e. "https://mysite.or/page" . But when I execute the same test from Azure (i.e. changed Test run location to VSTS in .testsettings), the links are reported as "https://{{Enviroment}}{{Sitemap.url.loc}}". This seems to be just a reporting issue and I can validate that azure is correctly invoking the urls from the data source. Why would the tests from Azure not report the url constructed from the datasource?
Load Test Summary: Executed from Local
Same test executed on Azure
Webtest:
<?xml version="1.0" encoding="utf-8"?>
<WebTest Name="GenericSitemap" Id="02954e81-f3a7-4c9c-94f5-3a4304f88361" Owner="" Priority="2147483647" Enabled="True" CssProjectStructure="" CssIteration="" Timeout="0" WorkItemIds="" xmlns="http://microsoft.com/schemas/VisualStudio/TeamTest/2010" Description="" CredentialUserName="" CredentialPassword="" PreAuthenticate="True" Proxy="default" StopOnError="False" RecordedResultFile="" ResultsLocale="">
<Items>
<Request Method="GET" Guid="01c37ffa-92db-42e8-9d25-a042dcd0123d" Version="1.1" Url="https://{{Enviroment}}{{Sitemap.url.loc}}" ThinkTime="0" Timeout="300" ParseDependentRequests="True" FollowRedirects="True" RecordResult="True" Cache="False" ResponseTimeGoal="0" Encoding="utf-8" ExpectedHttpStatusCode="0" ExpectedResponseUrl="https://{{Enviroment}}{{Sitemap.url.loc}}" ReportingName="" IgnoreHttpStatusCode="False" />
</Items>
<DataSources>
<DataSource Name="Sitemap" Provider="Microsoft.VisualStudio.TestTools.DataSource.XML" Connection="|DataDirectory|\..\Data\sitemap.xml">
<Tables>
<DataSourceTable Name="url" SelectColumns="SelectOnlyBoundColumns" AccessMethod="Random" />
</Tables>
</DataSource>
</DataSources>
<ContextParameters>
<ContextParameter Name="Enviroment" Value="mysite.net" />
</ContextParameters>
</WebTest>
Thanks to #AdrianHHH. I got it working by creating a requestPlugin and setting it on the data driven requests.
Here's my plugin:
[DisplayName("Set Request Params")]
[Description("Fix request urls when run from Azure")]
public class SetRequestParams : WebTestRequestPlugin
{
public override void PreRequest(object sender, PreRequestEventArgs e)
{
e.Request.ReportingName = e.Request.Url;
}
}

Chrome Web Store Manifest

I developed my gmail gadget to find sender email and add it to database .Hopefully I was able to see my gadget at bottom of email, and also I able to call my web Api from google.I created chrome web store app. I did some part and it works fine now. But I want to know exactly which steps I have to follow to do that?
here's my gadget.xml:
<?xml version="1.0" encoding="UTF-8"?>
<Module>`enter code here`
<ModulePrefs title="Test Gadget"
description=""
height="20"
author="excendia"
author_email="..."
author_location="">
<!-- Declare feature dependencies. -->
<!-- This one is not specific to Gmail contextual gadgets. -->
<Require feature="dynamic-height"/>
<!-- The next feature, Caja, is optional, and is supported for
use only within test domains. Uncomment the tag only for
non-production gadgets. -->
<!-- <Require feature="caja"/> -->
<!-- The next feature, google.contentmatch, is required for all
Gmail contextual gadgets.
<Param> - specify one or more comma-separated extractor IDs in
a param named "extractors". This line is overridden by the extractor ID
in the manifest, but is still expected to be present. -->
<Require feature="google.contentmatch">
<Param name="extractors">
google.com:MessageIDExtractor
</Param>
</Require>
</ModulePrefs>
<!-- Define the content type and display location. The settings
"html" and "card" are required for all Gmail contextual gadgets. -->
<Content type="html" view="card">
<![CDATA[
<script type="text/javascript">
<!-- Fetch the array of content matches. -->
matches = google.contentmatch.getContentMatches();
var matchList = document.createElement('UL');
var listItem;
var extractedText;
<!-- Iterate through the array and display output for each match. -->
for (var match in matches) {
for (var key in matches[match]) {
listItem = document.createElement('LI');
extractedText = document.createTextNode(key + ": " + matches[match][key]);
listItem.appendChild(extractedText);
matchList.appendChild(listItem);
}
}
document.body.appendChild(matchList);
gadgets.window.adjustHeight(100);
</script>
]]>
</Content>
</Module>
You can find steps to create chrome web store here.

add all controller and action node to Mvc.sitemap automatically

I have install MVCSitemapProvider on my MVC 3 application for breadcrumbs trail. It has auto generate following node in Mvc.sitemap.xml
<?xml version="1.0" encoding="utf-8" ?>
<mvcSiteMap xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://mvcsitemap.codeplex.com/schemas/MvcSiteMap-File-3.0"
xsi:schemaLocation="http://mvcsitemap.codeplex.com/schemas/MvcSiteMap-File-3.0 MvcSiteMapSchema.xsd"
enableLocalization="true">
<mvcSiteMapNode title="Home" controller="Home" action="Index">
<mvcSiteMapNode title="About" controller="Home" action="About"/>
</mvcSiteMapNode>
</mvcSiteMap>
And Following is the HTML Helper for displaying breadcrumbs
#Html.MvcSiteMap().SiteMapPath()
In my application, there is lot of controller and their action that is hectic to add all mvcSiteMapNode in mvcSiteMap of those action and question is that Is it possible to list all controller and their respective action in mvcSiteMapNode of Mvc.sitemap.xml without writting all manually.
I think the closest thing is using attributes on the methods, see https://github.com/maartenba/MvcSiteMapProvider/wiki/Defining-sitemap-nodes-in-code. Example:
// GET: /Checkout/Complete
[MvcSiteMapNodeAttribute(Title = "Checkout complete", ParentKey = "Checkout")]
public ActionResult Complete(int id)
{
// ...
}

How to consume wcf service running as windows service in ajax client

I have created a WCF service and it is hosted in windows service. When I have added a web reference to that service to an asp.net web forms project through right client menu in the solution explorer I am able to access the service and add reference to it.
Now I want to access this service through AJAX client (i.e in ASP.NET project through ScriptManager component)and call the service in a timer to get continuous stream of values.
I have never worked on AJAX or web that much, I did not find an suitable example on net on this.
I'm using WSHttpBinding.
I'm posting my code so that you can tell where I'm doing wrong.
WCF Service Library Code:
ITestService.cs code....
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Web;
namespace TestServiceLibrary
{
// NOTE: If you change the interface name "IService1" here, you must also update the reference to "IService1" in App.config.
[ServiceContract(Namespace="TestServiceLibrary")]
public interface ITestService
{
[OperationContract]
[WebGet]
double Add(double n1, double n2);
// TODO: Add your service operations here
}
}
TestService.cs code...............
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace TestServiceLibrary
{
// NOTE: If you change the class name "Service1" here, you must also update the reference to "Service1" in App.config.
public class TestService : ITestService
{
public double Add(double n1, double n2)
{
return n1 + n2;
}
}
}
TestServiceHost.cs (code of console application)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using TestServiceLibrary;
namespace TestServiceHost
{
class Program
{
static void Main(string[] args)
{
ServiceHost myhost = new ServiceHost(typeof(TestService));
myhost.Open();
while (System.Console.ReadKey().Key != System.ConsoleKey.Enter)
{
//System.Threading.Thread.Sleep(100);
}
myhost.Close();
}
}
}
XML Configuration of app.config... same in both wcf service library and wcf service host(console application in this case..)
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.web>
<compilation debug="true" />
</system.web>
<!-- When deploying the service library project, the content of the config file must be added to the host's
app.config file. System.Configuration does not support config files for libraries. -->
<system.serviceModel>
<services>
<service name="TestServiceLibrary.TestService" behaviorConfiguration="TestServiceLibrary.Service1Behavior">
<host>
<baseAddresses>
<add baseAddress = "http://localhost:8731/TestServiceLibrary/TestService/" />
</baseAddresses>
</host>
<!-- Service Endpoints -->
<!-- Unless fully qualified, address is relative to base address supplied above -->
<endpoint name="TestService_wsHttpBinding" address ="" binding="wsHttpBinding" contract="TestServiceLibrary.ITestService">
<!--
Upon deployment, the following identity element should be removed or replaced to reflect the
identity under which the deployed service runs. If removed, WCF will infer an appropriate identity
automatically.
-->
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<!-- Metadata Endpoints -->
<!-- The Metadata Exchange endpoint is used by the service to describe itself to clients. -->
<!-- This endpoint does not use a secure binding and should be secured or removed before deployment -->
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="TestServiceLibrary.Service1Behavior">
<!-- To avoid disclosing metadata information,
set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="True"/>
<!-- To receive exception details in faults for debugging purposes,
set the value below to true. Set to false before deployment
to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="False" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
Web Client (asp.net client, default.aspx) code...
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Simple AJAX Service Client Page</title>
<script type="text/javascript">
// <![CDATA[
// This function creates an asynchronous call to the service
function makeCall(operation){
var n1 = document.getElementById("num1").value;
var n2 = document.getElementById("num2").value;
// If user filled out these fields, call the service
if(n1 && n2){
// Instantiate a service proxy
var proxy = new TestServiceLibrary.ITestService();
// Call correct operation on proxy
switch(operation){
case "Add":
proxy.Add(parseFloat(n1), parseFloat(n2), onSuccess, onFail, null);
break;
}
}
}
// This function is called when the result from the service call is received
function onSuccess(mathResult){
document.getElementById("result").value = mathResult;
}
// This function is called if the service call fails
function onFail(){
document.getElementById("result").value = "Error";
}
// ]]>
</script>
</head>
<body>
<h1>
Simple AJAX Service Client Page</h1>
<p>
First Number:
<input type="text" id="num1" /></p>
<p>
Second Number:
<input type="text" id="num2" /></p>
<input id="btnAdd" type="button" onclick="return makeCall('Add');" value="Add" />
<p>
Result:
<input type="text" id="result" /></p>
<form id="mathForm" action="" runat="server">
<asp:ScriptManager ID="ScriptManager" runat="server">
<Services>
<asp:ServiceReference Path="http://localhost:8732/TestServiceLibrary/TestService/" />
</Services>
</asp:ScriptManager>
</form>
</body>
</html>
The error Im getting when accessing the webservice through asp.net in ajax is Microsoft JScript runtime error: 'TestServiceLibrary' is undefined
Please go through this code and help me in finding the problem. Thank you all for your responses.
Looks like the problem is with my service hosting and the endpoint i'm using.
I should modified my service hosting in the console application to use WebServiceHost instead of ServiceHost, then only the ajax clients can talk to my service. Instead of wsHttpBinding, I should use webHttpBinding.
So the code for webHosting is as follows.
using (var host = new WebServiceHost(
typeof(TestService)))
{
// Start listening for messages
host.Open();
Console.WriteLine("Press any key to stop the service.");
Console.ReadKey();
// Close the service
host.Close();
}
The xml configuration of my console is
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.serviceModel>
<services>
<service
name="TestServiceLibrary.TestService"
behaviorConfiguration="">
<endpoint address="http://localhost:8732/TestService"
binding="webHttpBinding"
bindingConfiguration=""
name="TestService_WebHttp"
contract="TestServiceLibrary.ITestService" />
</service>
</services>
</system.serviceModel>
</configuration>
Now when I did this changes I'm able to call my service through ie using the following url in ie http://localhost:8732/TestService/Add?n1=20&n2=20 and result returned by it is as follows <double xmlns="http://schemas.microsoft.com/2003/10/Serialization/">40</double>
Finally i found the solution to my problem. Im using JSON as way of communicating data and the script for receiving the data is as follows:
<script type="text/javascript">
$("#mybutton").click(function () {
$.getJSON("http://localhost:8732/TestService/Add", null, function (result) {
});
});
</script>
Use some tool like firebug to determine what is happening with the request. WSHttpBinding is secure by default. Check your security settings. Try first with no security to make sure it is not a security issue.
Have you attempted to connect to the service from the AJAX client yet? If so, are you getting any errors?
Without seeing code, there could be a number of things as Chandermani has said.
I've not done AJAX with WCF, but looking over the article Preet recommended, I would suggest checking (if you haven't already) that your AJAX client has the necessary code as per the article.
Are your service operations decorated with [WebGet]?
Do you have the config file for the AJAX client set up properly? Is the service's config file set up properly?

Resources