Jsf2 Richfaces 4 Fileupload, Display error from Business Logic - file-upload

I implemented a file upload using jsf2 and richfaces 4. It works quite good with one little mistake.
When i upload my file it can occour that i receive an exception from my business logic. (e.g. file already processed)
How can i manage it to display this exception? I tried to register me for the upload complete and render the form, but with no success.
My Fileupload bean (i tried to set the catched exception over the faces ontext without luck :-/ ) :
public void uploadSvg(FileUploadEvent event) {
UploadedFile uploadedFile = event.getUploadedFile();
File file = writeFileToDisk(uploadedFile);
try {
Utils.getSpringBean(FigureService.class).importFigure(
file.getAbsolutePath());
} catch (Exception e) {
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR,
file.getName() + " -> " + e.getMessage(), null);
FacesContext.getCurrentInstance().addMessage(null, message);
log.error(e,e);
// TODO display messages
}
}
My page (i am using it for two different fileuploads. hope that doesn't mind) :
<!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:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:a4j="http://richfaces.org/a4j"
xmlns:rich="http://richfaces.org/rich"
xmlns:c="http://java.sun.com/jsp/jstl/core">
<body>
<h:form id="files" >
<h:messages errorStyle="color:red" warnStyle="color: yellow" />
<h:panelGrid columns="1">
<h:column>
<c:if test="#{fileType eq 'svg'}">
<rich:fileUpload fileUploadListener="#{fileUpload.uploadSvg}"
maxFilesQuantity="5" id="uploadsvg" immediateUpload="false"
acceptedTypes="svg" allowFlash="false"
uploadData="#{fileUpload.uploadedFiles }" autoclear="false">
<a4j:ajax event="uploadcomplete" execute="#none" render="files"/>
</rich:fileUpload>
</c:if>
<c:if test="#{fileType eq 'fm'}">
<rich:fileUpload fileUploadListener="#{fileUpload.uploadFm}"
maxFilesQuantity="5" id="uploadfm" immediateUpload="false"
acceptedTypes="csv" allowFlash="false"
uploadData="#{fileUpload.uploadedFiles }" autoclear="false">
<a4j:ajax event="uploadcomplete" execute="#none" render="files"/>
</rich:fileUpload>
</c:if>
</h:column>
</h:panelGrid>
</h:form>
</body>
</html>
Thanks a lot!
greetings,
m

Related

What is wrong with this HttpWebRequest/HttpWebResponse code (why is it considered a "bad" request (400))? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Based on the info from this MS link, I've got the following code in a Windows CE / Compact Framework app which calls a REST method in a Web API server app:
public static string SendXMLFile2(string uri, string data)
{
//TODO: Remove below after testing
String s = data.Substring(0, 128);
MessageBox.Show(String.Format("data length is {0}, uri is {1}, first part is {2}", data.Length, uri, s));
//TODO: Remove above after testing
HttpWebRequest myHttpWebRequest=(HttpWebRequest)WebRequest.Create(uri);
myHttpWebRequest.AllowWriteStreamBuffering=false;
myHttpWebRequest.Method="POST";
UTF8Encoding encodedData = new UTF8Encoding();
//ASCIIEncoding encodedData=new ASCIIEncoding();
byte[] byteArray=encodedData.GetBytes(data);
//myHttpWebRequest.ContentType="application/x-www-form-urlencoded";
myHttpWebRequest.ContentType = "application/xml";
myHttpWebRequest.ContentLength=byteArray.Length;
Stream newStream=myHttpWebRequest.GetRequestStream();
newStream.Write(byteArray,0,byteArray.Length);
newStream.Close();
HttpWebResponse myHttpWebResponse=(HttpWebResponse)myHttpWebRequest.GetResponse();
return myHttpWebResponse.StatusDescription;
}
What I see is:
...and then I get, "The remote server returned an error: (400) Bad Request." The breakpoint in my REST method (on the server) is not even reached when this exception is thrown/returned.
Why? What do I have to change in the code to get the "bad" request to be considered "good"?
UPDATE
To answer mrchief, here's the server code:
[Route("api/inventory/sendXML/{userId}/{pwd}/{filename}")]
public async void SendInventoryXML(String userId, String pwd, String fileName)
{
XDocument doc = XDocument.Load(await Request.Content.ReadAsStreamAsync());
String saveLoc = String.Format(#"C:\HDP\{0}.xml", fileName);
doc.Save(saveLoc);
}
Yes, I'm ignoring userId and pwd for now.
UPDATE 2
Plugging this:
http://192.168.125.50:21608/api/inventory/sendXML/duckbilled/platypus/INV_bla.xml
...into Postman, I get:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML>
<HEAD>
<TITLE>Bad Request</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii">
</HEAD>
<BODY>
<h2>Bad Request - Invalid Hostname</h2>
<hr>
<p>HTTP Error 400. The request hostname is invalid.</p>
</BODY>
</HTML>
??? This same uri works fine when I call it from a Winforms app created in Visual Studio 2013. Well, actually, I use localhost instead there. I get the same response as above if I use the host name instead of the IP Address. But if I use localhost from PostMan:
http://localhost:21608/api/inventory/sendXML/duckbilled/platypus/INV_bla.xml
I get:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html
xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>IIS 8.0 Detailed Error - 404.0 - Not Found</title>
<style type="text/css">
<!--
body{margin:0;font-size:.7em;font-family:Verdana,Arial,Helvetica,sans-serif;}
code{margin:0;color:#006600;font-size:1.1em;font-weight:bold;}
.config_source code{font-size:.8em;color:#000000;}
pre{margin:0;font-size:1.4em;word-wrap:break-word;}
ul,ol{margin:10px 0 10px 5px;}
ul.first,ol.first{margin-top:5px;}
fieldset{padding:0 15px 10px 15px;word-break:break-all;}
.summary-container fieldset{padding-bottom:5px;margin-top:4px;}
legend.no-expand-all{padding:2px 15px 4px 10px;margin:0 0 0 -12px;}
legend{color:#333333;;margin:4px 0 8px -12px;_margin-top:0px;
font-weight:bold;font-size:1em;}
a:link,a:visited{color:#007EFF;font-weight:bold;}
a:hover{text-decoration:none;}
h1{font-size:2.4em;margin:0;color:#FFF;}
h2{font-size:1.7em;margin:0;color:#CC0000;}
h3{font-size:1.4em;margin:10px 0 0 0;color:#CC0000;}
h4{font-size:1.2em;margin:10px 0 5px 0;
}#header{width:96%;margin:0 0 0 0;padding:6px 2% 6px 2%;font-family:"trebuchet MS",Verdana,sans-serif;
color:#FFF;background-color:#5C87B2;
}#content{margin:0 0 0 2%;position:relative;}
.summary-container,.content-container{background:#FFF;width:96%;margin-top:8px;padding:10px;position:relative;}
.content-container p{margin:0 0 10px 0;
}#details-left{width:35%;float:left;margin-right:2%;
}#details-right{width:63%;float:left;overflow:hidden;
}#server_version{width:96%;_height:1px;min-height:1px;margin:0 0 5px 0;padding:11px 2% 8px 2%;color:#FFFFFF;
background-color:#5A7FA5;border-bottom:1px solid #C1CFDD;border-top:1px solid #4A6C8E;font-weight:normal;
font-size:1em;color:#FFF;text-align:right;
}#server_version p{margin:5px 0;}
table{margin:4px 0 4px 0;width:100%;border:none;}
td,th{vertical-align:top;padding:3px 0;text-align:left;font-weight:normal;border:none;}
th{width:30%;text-align:right;padding-right:2%;font-weight:bold;}
thead th{background-color:#ebebeb;width:25%;
}#details-right th{width:20%;}
table tr.alt td,table tr.alt th{}
.highlight-code{color:#CC0000;font-weight:bold;font-style:italic;}
.clear{clear:both;}
.preferred{padding:0 5px 2px 5px;font-weight:normal;background:#006633;color:#FFF;font-size:.8em;}
-->
</style>
</head>
<body>
<div id="content">
<div class="content-container">
<h3>HTTP Error 404.0 - Not Found</h3>
<h4>The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.</h4>
...??? Is it just because this is a POST that is supposed to have an XML file attached, and because it's not there, it gets consumed with confusion?
UPDATE 3
I see the "." in "INV_bla.xml" was confusing PostMan. If I remove it, so that the URI is "http://localhost:21609/api/inventory/sendXML/duckbilled/platypus/INV_bla", I get instead a 500 err msg and:
<!DOCTYPE html>
<html>
<head>
<title>Root element is missing.</title>
<meta name="viewport" content="width=device-width" />
<style>
body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;}
p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px}
b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px}
H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red }
H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon }
pre {font-family:"Consolas","Lucida Console",Monospace;font-size:11pt;margin:0;padding:0.5em;line-height:14pt}
.marker {font-weight: bold; color: black;text-decoration: none;}
.version {color: gray;}
.error {margin-bottom: 10px;}
.expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; }
#media screen and (max-width: 639px) {
pre { width: 440px; overflow: auto; white-space: pre-wrap; word-wrap: break-word; }
}
#media screen and (max-width: 479px) {
pre { width: 280px; }
}
</style>
</head>
<body bgcolor="white">
<span>
<H1>Server Error in '/' Application.
<hr width=100% size=1 color=silver>
</H1>
<h2>
<i>Root element is missing.</i>
</h2>
</span>
<font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif ">
<b> Description: </b>An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
<br>
<br>
<b> Exception Details: </b>System.Xml.XmlException: Root element is missing.
<br>
<br>
<b>Source Error:</b>
<br>
<br>
<table width=100% bgcolor="#ffffcc">
<tr>
<td>
<code>
<pre>
Line 29: public async void SendInventoryXML(String userId, String pwd, String fileName)
Line 30: {
<font color=red>Line 31: XDocument doc = XDocument.Load(await Request.Content.ReadAsStreamAsync());
</font>Line 32: String saveLoc = String.Format(#"C:\HDP\{0}.xml", fileName);
Line 33: doc.Save(saveLoc);
</pre>
</code>
</td>
</tr>
</table>
<br>
<b> Source File: </b> c:\Project\git\CStore\HHS.Web\Controllers\InventoryXMLController.cs
<b> Line: </b> 31
<br>
<br>
<b>Stack Trace:</b>
<br>
<br>
<table width=100% bgcolor="#ffffcc">
<tr>
<td>
<code>
<pre>
[XmlException: Root element is missing.]
System.Xml.XmlTextReaderImpl.Throw(Exception e) +69
System.Xml.XmlTextReaderImpl.ParseDocumentContent() +305
System.Xml.XmlTextReaderImpl.Read() +213
System.Xml.Linq.XDocument.Load(XmlReader reader, LoadOptions options) +44
System.Xml.Linq.XDocument.Load(Stream stream, LoadOptions options) +57
System.Xml.Linq.XDocument.Load(Stream stream) +6
HHS.Web.Controllers.<SendInventoryXML>d__0.MoveNext() in c:\Project\git\CStore\HHS.Web\Controllers\InventoryXMLController.cs:31
System.Runtime.CompilerServices.AsyncMethodBuilderCore.<ThrowAsync>b__0(Object state) +50
System.Web.<>c__DisplayClass7.<Post>b__6() +15
System.Web.Util.SynchronizationHelper.SafeWrapCallback(Action action) +91
</pre>
</code>
</td>
</tr>
</table>
<br>
<hr width=100% size=1 color=silver>
<b>Version Information:</b> Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18446
</font>
</body>
</html>
<!--
[XmlException]: Root element is missing.
at System.Xml.XmlTextReaderImpl.Throw(Exception e)
at System.Xml.XmlTextReaderImpl.ParseDocumentContent()
at System.Xml.XmlTextReaderImpl.Read()
at System.Xml.Linq.XDocument.Load(XmlReader reader, LoadOptions options)
at System.Xml.Linq.XDocument.Load(Stream stream, LoadOptions options)
at System.Xml.Linq.XDocument.Load(Stream stream)
at HHS.Web.Controllers.InventoryXMLController.<SendInventoryXML>d__0.MoveNext() in c:\Project\git\CStore\HHS.Web\Controllers\InventoryXMLController.cs:line 31
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.<ThrowAsync>b__0(Object state)
at System.Web.AspNetSynchronizationContext.<>c__DisplayClass7.<Post>b__6()
at System.Web.Util.SynchronizationHelper.SafeWrapCallback(Action action)
-->
UPDATE 4
With this code (following Brinn's suggestion):
String datta = "<Content></Content>";
String s = SendXMLFile2(uri, datta);
MessageBox.Show(s); // TODO: Remove or comment out after testing
...I still get a 400 error.
UPDATE 5
There is ONE permutation that actually works in Postman to the extent that I reach the breakpoint in the server code (http://localhost:21608/api/inventory/sendXML/duckbill/platypus/INV_bla). However, when I hit F10 to step from the "XDocument doc = ..." line to the "String saveLoc = ..." line, the "Root element is missing" exception is thrown (the one shown above in all its gory glory).
I cannot use that exact same URI in my app, though, as "localhost" is URI-non-grata there.
UPDATE 6
Grasping at straws, I even tried this:
String xmlHeader = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
String crlf = "\r\n";
String datta = "<Content></Content>";
data = xmlHeader + crlf + datta + crlf;
String s = SendXMLFile2(uri, data);
...but the "400 Bad Request" err remains, causing me to rue the day I decided to hang up my spurs.
UPDATE 7
Even when I add an XML file in Postman, I get an error (500 - Internal Server Error):
UPDATE 8
Even with the code straight from the Wigley's mouth (from p. 358 of "Microsoft .NET Compact Framework"):
public static string SendXMLFile2(string uri, string data)
{
WebRequest req = WebRequest.Create(uri);
req.Method = "Post";
req.ContentType = "text/plain; charset=utf-8";
// Encode the data
byte[] encodedBytes = Encoding.UTF8.GetBytes(data);
req.ContentLength = encodedBytes.Length;
// Write encoded data into request stream
Stream requestStream = req.GetRequestStream();
requestStream.Write(encodedBytes, 0, encodedBytes.Length);
requestStream.Close();
WebResponse result = req.GetResponse();
return result.ToString();
}
...I get the "400 - Bad Request" err.
Is it possibly the data - the contents of the XML file - that is throwing a spanner/monkey wrench into the works?
Here's what that looks like (excerpt, with the great middle section elided):
<?xml version="1.0" encoding="utf-8"?>
<Command>
<INV>
<line_id>1</line_id>
<ref_no>valerie</ref_no>
<upc_code>79997000331</upc_code>
<description>ffff</description>
<department>2</department>
<vendor_id>1</vendor_id>
<upc_pack_size>1</upc_pack_size>
<id>79997000331</id>
<pack_size>1</pack_size>
<unit_cost>0</unit_cost>
<unit_list>0</unit_list>
<unit_qty>9</unit_qty>
<new_item>-1</new_item>
</INV>
<INV>
<line_id>2</line_id>
<ref_no>valerie</ref_no>
<upc_code>81127600412</upc_code>
<description>SLV EAG FF 100 BX</description>
<department>2.01</department>
<vendor_id>1</vendor_id>
<upc_pack_size>1</upc_pack_size>
<id>81127600412</id>
<pack_size>1</pack_size>
<unit_cost>0</unit_cost>
<unit_list>0</unit_list>
<unit_qty>9</unit_qty>
<new_item>0</new_item>
</INV>
. . .
<INV>
<line_id>3277</line_id>
<ref_no>valerie</ref_no>
<upc_code>00980000007</upc_code>
<description>TICTAC</description>
<department>8.8</department>
<vendor_id />
<upc_pack_size>1</upc_pack_size>
<id>00980000007</id>
<pack_size>1</pack_size>
<unit_cost>2</unit_cost>
<unit_list>3.55</unit_list>
<unit_qty>0</unit_qty>
<new_item>0</new_item>
</INV>
</Command>
UPDATE 9
I get "The remote server returned an error: (400) Bad Request" in my app. Now I do see two interesting entries in Fiddler: There are two 404s that display in Fiddler which
have "Host" vals of "localhost:21609" and "localhost:21608" (which relate to the REST calls in question), and "URL" values of /favicon.ico ... ???
What in red blazes is that about? They have a "Body" value of 4,905, a "Caching" value of "private" and "Content-Type" of text/html; charset=utf8
Why is favicon.ico problematic or even considered here?
UPDATE 10
This is Fiddler's "Log" tab contents for my "faked" call to the REST method (using Composer to add my POST URI and upload an XML file):
09:14:20:9657 [WebSocket #1439] Read from Server failed... Object reference not set to an instance of an object.
09:23:19:7275 /Fiddler.CertMaker> Invoking makecert.exe with arguments: -pe -ss my -n "CN=www.google-analytics.com, O=DO_NOT_TRUST, OU=Created by http://www.fiddler2.com" -sky exchange -in DO_NOT_TRUST_FiddlerRoot -is my -eku 1.3.6.1.5.5.7.3.1 -cy end -a sha1 -m 132 -b 09/03/2013
09:23:20:1296 /Fiddler.CertMaker>64-CreateCert(www.google-analytics.com) => (0).
09:25:45:6411 [Fiddler] No HTTP request was received from (chrome:1384) new client socket, port 4235.
09:25:55:6411 [Fiddler] No HTTP request was received from (chrome:1384) new client socket, port 4241.
09:36:35:6681 [WebSocket #1473] Read from Client returned error: 0
09:36:35:7491 [WebSocket #1473] Read from Server returned error: 0
09:37:45:4031 [WebSocket #1552] Read from Client returned error: 0
09:37:45:4861 [WebSocket #1552] Read from Server returned error: 0
09:37:51:8077 [WebSocket #1575] Read from Client returned error: 0
09:37:51:8877 [WebSocket #1575] Read from Server returned error: 0
I would think maybe the "Object reference not set to an instance of an object" is indicating something in my server code might be the problem - but the key part of that is not even reached...is the fact that I'm calling async/await code in the server a possible cause of my woes???
UPDATE 11
With the only change being that "21609" becomes "21608" in my URL, Fiddler now gives me a "500" ("Internal Server Error") Result (when using 21609 I got "204" Result, but it didn't work).
With this port number, the real "meat and potatoes" code is reached on the server (the async/await code that calls XDocument.Load(), etc.
Fiddler's Inspectors.WebView tab shows me:
Is the problem that this xml does not start off with this line:
<?xml version="1.0" encoding="utf-8"?>
...and is thus not seen as valid/real XML?
UPDATE 12
Nope - even with a file that contains that xml starting line, it fails in the same way...
UPDATE 13
So depending on the client used, I get different results:
From the handheld device, I get a "/favicon.ico" err in Fiddler.
From Fiddler itself (using the "Composer" tab) I get, "Data at the root level is invalid. Line 1, position 1"
From a test Winforms app, the code works (the expected file is populated and saved where it should be) but there is no trace in Fiddler that an HTTP call was even made (there is no entry/evidence for it)...???
UPDATE 14
The server app does have this in Global.asax.cs:
RouteTable.Routes.IgnoreRoute("{*favicon}", new { favicon = #"(.*/)?favicon.ico(/.*)?" });
...so...what's the problem?
UPDATE 15
I notice that I can get trace log files generated by my server app from this location: C:\Users\\Documents\IISExpress\TraceLogFiles\
Looking there, I find the proverbial boatload of information (overload?), such as:
<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type='text/xsl' href='freb.xsl'?>
<!-- saved from url=(0014)about:internet -->
<failedRequest url="http://localhost:21609/"
siteId="40"
appPoolId="Clr4IntegratedAppPool"
processId="10580"
verb="GET"
remoteUserName=""
userName=""
tokenUserName="SSCS\clay"
authenticationType="anonymous"
activityId="{00000000-0000-0000-1D00-0080020000ED}"
failureReason="STATUS_CODE"
statusCode="200"
triggerStatusCode="403.14"
timeTaken="62"
xmlns:freb="http://schemas.microsoft.com/win/2006/06/iis/freb"
>
. . .
What strikes me is the verb "GET" - this is a "POST" not a "GET" - or am I misunderstanding the meaning of the "verb" member?
UPDATE 16
I tested three different ways of calling the REST method, examining what was happening as best as I could using Fiddler and the trace log files that the server creates.
The only successful calling and execution of the server code (receiving the file, and then saving it to disk) occurred with the Winforms (Visual Studio 2013, .NET 4) app.
Here are some details gleaned from those three attempts:
[a] EXE on handheld device:
400 - Bad Request
breakpoint in server Controller code NOT reached
No activity seen in Fiddler
Summary: Fails - server is reached, but returns err msg
Pertinent contents of Log Trace file:
[ no log trace file created ]
[b] Test Winforms app:
breakpoint in server Controller code IS reached
No activity seen in Fiddler (?!?)
Method works - file is created by server code with the data it should have
Summary: works, but is "invisible" to Fiddler
Pertinent contents of Log Trace file:
<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type='text/xsl' href='freb.xsl'?>
<!-- saved from url=(0014)about:internet -->
<failedRequest url="http://localhost:21608/api/inventory/sendXML/duckbill/Platypus/DSD_42314_3_20140310140842828" siteId="41" appPoolId="Clr4IntegratedAppPool" processId="8916"
verb="POST"
remoteUserName=""
userName=""
tokenUserName="NRBQ\clay"
authenticationType="anonymous"
activityId="{00000000-0000-0000-5D00-0080000000F6}"
failureReason="STATUS_CODE"
statusCode="204"
triggerStatusCode="204"
timeTaken="3666"
xmlns:freb="http://schemas.microsoft.com/win/2006/06/iis/freb"
>
[c] Fiddler "Composer"
breakpoint in server Controller code IS reached
Activity IS seen in Fiddler
Result = 500 ("Internal Server Error")
Summary: Gets further than the handheld, but fails
Pertinent contents of Log Trace file:
<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type='text/xsl' href='freb.xsl'?>
<!-- saved from url=(0014)about:internet -->
<failedRequest url="http://localhost:21608/api/inventory/sendXML/duckbill/platypus/INV_bla"
siteId="41"
appPoolId="Clr4IntegratedAppPool"
processId="8916"
verb="POST"
remoteUserName=""
userName=""
tokenUserName="NRBQ\clay"
authenticationType="anonymous"
activityId="{00000000-0000-0000-4800-0080060000F6}"
failureReason="STATUS_CODE"
statusCode="500"
triggerStatusCode="204"
timeTaken="2964"
xmlns:freb="http://schemas.microsoft.com/win/2006/06/iis/freb"
>
UPDATE 17
Could it be that my encoding is wrong? It seems that might be the case, based on what I read here when researching the err msg I get ("Data at the root level is invalid. Line 1, position 1.")
This is what I'm doing in the client:
WebRequest req = WebRequest.Create(uri);
req.Method = "Post";
req.ContentType = "text/plain; charset=utf-8";
byte[] encodedBytes = Encoding.UTF8.GetBytes(data);
Should ContentType be "application/xml" or "application/x-www-form-urlencoded" (or something else) instead?
and/or should Encoding be something other than UTF8?
UPDATE 18
I noticed in C:\Users\clay\Documents\IISExpress\TraceLogFiles\ that I was getting a "403.14":
<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type='text/xsl' href='freb.xsl'?>
<!-- saved from url=(0014)about:internet -->
<failedRequest url="http://localhost:21609/"
siteId="40"
appPoolId="Clr4IntegratedAppPool"
processId="1572"
verb="GET"
remoteUserName=""
userName=""
tokenUserName="SSCS\clay"
authenticationType="anonymous"
activityId="{00000000-0000-0000-0200-0080060000EB}"
failureReason="STATUS_CODE"
statusCode="200"
triggerStatusCode="403.14"
timeTaken="904"
xmlns:freb="http://schemas.microsoft.com/win/2006/06/iis/freb"
>
Which, according to this and more specifically this indicates "Directory listing denied."
Thinking this may be the crux of the problem, I researched what to do about a 403.14, and I followed Method 1 here, which is entitled "Add a default document (Recommended)" but actually contains the steps to "Enable the Directory Browsing feature in IIS"
But I still get the same triggerStatusCode ("403.14") in C:\Users\clay\Documents\IISExpress\TraceLogFiles\
So I was going to try the other method, too, but I already had a default document, so enable was not an option there (disable was).
Finally, I went with the final option, of updating the IIS Express config:
While that made the web pages look better when running the server (the 403.14 was replaced with a "localhost - /" dir listing), it made no difference when the client app attempted to send the XML file to the server. So, this last changed "fixed" the pages that display in the browser when the server is started, but I'm still seeing the "403.14" problem in the Trace log files when I try to access the server from my client app...???
UPDATE 19
With the latest change (setting the IIS config), the Trace log no longer has the "403.14":
<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type='text/xsl' href='freb.xsl'?>
<failedRequest url="http://localhost:21609/"
. . .
verb="GET"
. . .
failureReason="STATUS_CODE"
statusCode="200"
triggerStatusCode="200"
timeTaken="78"
xmlns:freb="http://schemas.microsoft.com/win/2006/06/iis/freb"
>
...so I guess the "400 - Bad Request" error I get from the server when calling it from the client is unrelated to this erstwhile 403.14 error. Note, too, that it the "failedRequest" is some "GET" operation (whereas my failing call from the client is an HttpPost). What is failing here I don't know, as statusCode 200 is, in fact, "OK"
The first time (only) that I start the server (or start and then call the server from the client), I get a 404 for a missing favicon, but that doesn't seem to really be a problem.
UPDATE 20
The solution was to add at a command prompt either this:
netsh http add urlacl url=http://shannon2:80/ user=everyone
...or the same for port 8080 instead of 80.
See Update 5 here.
It could, frankly, be a number of things. If the service is hosted on IIS, and you have IE, then, being a REST service, navigate to that URI, and you should get a 400.xx error. The xx part is clarified here

ASP.NET Optimization - Bundling

I've been trying out the new minification and bundling feature in ASP.NET MVC 4, and it works great as long as you use the default folder conventions for css and js files.
/Content
/Scripts
I usually put css and script in a folder called Static like this
/Static/Css
/Static/Js
I tried to register my own bundles like this:
public static class BundleCollectionExtensions
{
public static void RegisterScriptsAndCss(this BundleCollection bundles)
{
var bootstrapCss = new Bundle("~/Static/Css", new CssMinify());
bootstrapCss.AddDirectory("~/Static/Css", "*.css");
bootstrapCss.AddFile("~/Static/Css/MvcValidation.css");
bootstrapCss.AddFile("~/Static/Css/bootstrap-responsive.min.css");
bootstrapCss.AddFile("~/Static/Css/bootstrap.min.css");
bundles.Add(bootstrapCss);
var bootstrapJs = new Bundle("~/Static/Js", new JsMinify());
bootstrapJs.AddDirectory("~/Static/Js", "*.js");
bootstrapJs.AddFile("~/Static/Js/jquery-1.7.1.min.js");
bootstrapJs.AddFile("~/Static/Js/jquery.validate.min.js");
bootstrapJs.AddFile("~/Static/Js/jquery.validate.unobtrusive.min.js");
bootstrapJs.AddFile("~/Static/Js/bootstrap.min.js");
bootstrapJs.AddFile("~/Static/Js/gunsforhire.js");
bundles.Add(bootstrapJs);
}
}
And in
Global.ascx.cs
I did this:
BundleTable.Bundles.RegisterScriptsAndCss();
The generated markup looks like this:
<link href="/Static/Css?v=D9JdmLZFFwjRwraNKfA1uei_YMoBoqLf-gFc0zHivM41" rel="stylesheet" type="text/css" />
<script src="/Static/Js?v=mbKbf5__802kj-2LS5j9Ba-wvSxBCKNMQGBgzou6iZs1" type="text/javascript"></script>
However It's doesn't work, the request looks like this:
Request URL:http://localhost:49603/Static/Js?v=mbKbf5__802kj-2LS5j9Ba-wvSxBCKNMQGBgzou6iZs1
Request Method:GET
Status Code:301 Moved Permanently (from cache)
Query String Parametersview URL encoded
v:mbKbf5__802kj-2LS5j9Ba-wvSxBCKNMQGBgzou6iZs1
Request URL:http://localhost:49603/Static/Js/?v=mbKbf5__802kj-2LS5j9Ba-wvSxBCKNMQGBgzou6iZs1
Request Method:GET
Status Code:404 Not Found
Request Headersview source
Accept:*/*
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Host:localhost:49603
Referer:http://localhost:49603/
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11
Query String Parametersview URL encoded
v:mbKbf5__802kj-2LS5j9Ba-wvSxBCKNMQGBgzou6iZs1
Response Headersview source
Cache-Control:private
Content-Length:4757
Content-Type:text/html; charset=utf-8
Date:Thu, 01 Mar 2012 19:05:44 GMT
Server:Microsoft-IIS/7.5
X-Powered-By:ASP.NET
X-SourceFiles:=?UTF-8?B? QzpcQENvZGVccGVsbGVccGVsbGVoZW5yaWtzc29uLnNlXHNyY1xXZWJcU3RhdGljXEpzXA==?=
What am I doing wrong?
Update
I think I was finally able to solve this by doing the following:
Removing the AddDirectory calls bootstrapCss.AddDirectory("~/Static/Css", "*.css");
Giving the bundles paths that do not reflect the real directory structure
What you are doing "wrong" is that your bundle path corresponds to a REAL path. As I understand it, when the request for "/Static/Css?v=D9JdmLZFFwjRwraNKfA1uei_YMoBoqLf-gFc0zHivM41" comes in, the routing engine first looks for a physical path. It finds a match with your folder "static" and it tries to find a file in it that matches "Css?v=D9JdmLZFFwjRwraNKfA1uei_YMoBoqLf-gFc0zHivM41". When it can't find one, because it doesn't exist, it gives a 404. (I've also seen an access denied.) When the routing engine can't find a physical file path it then looks to other handlers like bundling and minification to serve up the request.
Anyway I think you've figured it out from your comments but I'm not sure it will be very clear to anyone that finds your question. Simply change your registration from:
var bootstrapCss = new Bundle("~/Static/Css", new CssMinify());
to:
var bootstrapCss = new Bundle("~/bundles/Css", new CssMinify());
If you make that change, your issue will go away, (granted there is no physical path that corresponds to "bundles".
if done this a few days ago and it worked well. i created a folder named Helper and then i created a new class called CssJsBuilder.
my class looks like this:
public static void Initializing()
{
IBundleTransform jstransformer;
IBundleTransform csstransformer;
#if DEBUG
jstransformer = new NoTransform("text/javascript");
csstransformer = new NoTransform("text/css");
#else
jstransformer = new JsMinify();
csstransformer = new CssMinify();
#endif
var bundle = new Bundle("~/Scripts/js", jstransformer);
bundle.AddFile("~/Scripts/jquery-1.6.2.js", true);
bundle.AddFile("~/Scripts/jquery-ui-1.8.11.js", true);
bundle.AddFile("~/Scripts/jquery.validate.unobtrusive.js", true);
bundle.AddFile("~/Scripts/jquery.unobtrusive-ajax.js", true);
bundle.AddFile("~/Scripts/jquery.validate.js", true);
bundle.AddFile("~/Scripts/modernizr-2.0.6-development-only.js", true);
bundle.AddFile("~/Scripts/AjaxLogin.js", true);
bundle.AddFile("~/Scripts/knockout-2.0.0.debug.js", true);
bundle.AddFile("~/Scripts/bootstrap.js", true);
bundle.AddFile("~/Scripts/dungeon.custom.js", true);
BundleTable.Bundles.Add(bundle);
bundle = new Bundle("~/Content/css", csstransformer);
bundle.AddFile("~/Content/bootstrap-responsive.css", true);
bundle.AddFile("~/Content/bootstrap.css", true);
BundleTable.Bundles.Add(bundle);
bundle = new Bundle("~/Content/themes/base/css", csstransformer);
bundle.AddFile("~/Content/themes/base/jquery.ui.core.css", true);
bundle.AddFile("~/Content/themes/base/jquery.ui.resizable.css", true);
bundle.AddFile("~/Content/themes/base/jquery.ui.selectable.css", true);
bundle.AddFile("~/Content/themes/base/jquery.ui.accordion.css", true);
bundle.AddFile("~/Content/themes/base/jquery.ui.autocomplete.css", true);
bundle.AddFile("~/Content/themes/base/jquery.ui.button.css", true);
bundle.AddFile("~/Content/themes/base/jquery.ui.dialog.css", true);
bundle.AddFile("~/Content/themes/base/jquery.ui.slider.css", true);
bundle.AddFile("~/Content/themes/base/jquery.ui.tabs.css", true);
bundle.AddFile("~/Content/themes/base/jquery.ui.datepicker.css", true);
bundle.AddFile("~/Content/themes/base/jquery.ui.progressbar.css", true);
bundle.AddFile("~/Content/themes/base/jquery.ui.theme.css", true);
BundleTable.Bundles.Add(bundle);
}
After that. Go to Global.asax:
Remove or comment out BundleTable.Bundles.RegisterTemplateBundles()
Add CssJsBuilder.Initializing() to the Application_Start() Method.
Recreate Project and then start it again.
Hope this works for you, too.
In Global.asax.cs replace
BundleTable.Bundles.RegisterTemplateBundles();
with
BundleTable.Bundles.EnableDefaultBundles();
Here is how it worked for me.
This is simplified version I only use default.aspx file no global.asax (you can us it if you want)
In this example I use 2 directories Content2 and Scripts2
in Content2 I have 2 css files one for class="naziv" and other for class="naziv2"
in Scripts2 there are 2 files one with function f1() definition and other with f2() definition
in /bin directory there should be 3 files:
Microsoft.Web.Infrastructure.dll,
System.Web.Optimization.dll,
WebGrease.dll
<%# Page Title="Home Page" Language="vb" debug="true"%>
<%# Import namespace="System.Web.Optimization" %>
<script runat="server" >
Sub Page_Load(sender As Object, e As EventArgs)
System.Web.Optimization.BundleTable.EnableOptimizations = True ''true will force optimization even if debug=true
Dim siteCssBundle = New StyleBundle("~/Content2/css")
siteCssBundle.IncludeDirectory("~/Content2", "*.css")
BundleTable.Bundles.Add(siteCssBundle)
Dim siteJsBundle = New ScriptBundle("~/Scripts2/js")
siteJsBundle.IncludeDirectory("~/Scripts2", "*.js")
BundleTable.Bundles.Add(siteJsBundle)
End Sub
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
</head>
<body onload="f1(); f2();">
<%: Styles.Render("~/Content2/css")%>
<%: Scripts.Render("~/Scripts2/js")%>
<br />
<span class="naziv">Span 1</span> <br />
<span class="naziv2">Span 2</span> <br />
</body>
</html>

Automatically grab file path

Everyone i am looking for a way to automatically upload a file but skip the browse and choose file process.
So i set the location of the file somehow via the form and the client just has to click submit and it will automatcially upload the file from the path i have set. skipping the browse for file process.
I would like to intergrate it into the following undesigns S3 Class
http://undesigned.org.za/2007/10/22/amazon-s3-php-class/documentation
<?php
S3::setAuth(awsAccessKey, awsSecretKey);
$bucket = "upload-bucket";
$path = "myfiles/"; // Can be empty ""
$lifetime = 3600; // Period for which the parameters are valid
$maxFileSize = (1024 * 1024 * 50); // 50 MB
$metaHeaders = array("uid" => 123);
$requestHeaders = array(
"Content-Type" => "application/octet-stream",
"Content-Disposition" => 'attachment; filename=${filename}'
);
$params = S3::getHttpUploadPostParams(
$bucket,
$path,
S3::ACL_PUBLIC_READ,
$lifetime,
$maxFileSize,
201, // Or a URL to redirect to on success
$metaHeaders,
$requestHeaders,
false // False since we're not using flash
);
$uploadURL = "https://{$bucket}.s3.amazonaws.com/";
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>S3 Form Upload</title>
</head>
<body>
<form method="post" action="<?php echo $uploadURL; ?>" enctype="multipart/form-data">
<?php
foreach ($params as $p => $v)
echo " <input type=\"hidden\" name=\"{$p}\" value=\"{$v}\" />\n";
?>
<input type="file" name="file" /> <input type="submit" value="Upload" />
</form>
</body>
</html>
at what point does it grab the file path ?
is it grabbing it out of the name here
can i do something with $_FILES ???
Can someone please give me a point on where to start i would really appriciate this.
thanks
You'll have to specify the tools of the trade. A common html form has no such functionality.
You can try value="c:\somefile.ext" but many browsers will not accept this.

sfFacebookConnectPlugin: Authentication problem

I try to get the sfFacebookConnectPlugin to run by following the tutorial on the symfony homepage.
Everything seems well configured. But when I try to login with sfFacebookConnectAuth/signin.
I get the form error "The username and/or password is invalid.".
I even don't know where to start with the debugging.
First Step could be to find out the right Application-Settings on the Facebook-Side (e.g. Post-Authorize Callback URL, Connect-URL or Canvas Callback URL)
I use symfony 1.4.5 doctrine with sfGuardDoctrinePlugin (on a live host with subdomain.)
Thx for your help.
I found that page: http://burgiblog.com/2009/09/18/developing-facebook-applications-with-symfony/ now it works, I changed three things after reading the tutorial:
modules/sfFacebookConnectAuth/config/security.yml: Use "false" instead of "off"
I added "callback_url" in apps/frontend/config/app.yml
And I used the facebook action in the tutorial
I need to find out, what the problem exactly was. And I need to enhance some things to the plugin. E.g. saving the user data to my profile class etc. (Now I saves a cryptic username instead of the right FB username.)
It says on the plugin page that this plugin is only supported/stable up to Symfony 1.2. Might make sense to email the plugin author directly regarding 1.4 compatibility.
I'm having some problems with sfFacebookConnectPlugin. I tried replicating the simple example from http://burgiblog.com/2009/09/18/developing-facebook-applications-with-symfony/ . And calling the index page, I get redirected to the facebook authentication page but after logging in, I do not get redirected back. I stay logged into facebook only. What am I doing wrong?
Thanks.
This is my code:
[/frontend/config/app.yml]
# default values
all:
facebook:
api_key: xxx
api_secret: xxx
api_id: xxx
callback_url: 'http://localhost'
redirect_after_connect: false
redirect_after_connect_url: ''
connect_signin_url: 'sfFacebookConnectAuth/signin'
app_url: '/my-app'
guard_adapter: ~
js_framework: none # none, jQuery or prototype.
# It is highly recommended to use a js framework if you want a correct experience in IE
sf_guard_plugin:
profile_class: sfGuardUserProfile
profile_field_name: user_id
profile_facebook_uid_name: facebook_uid # WARNING this column must be of type bigint ! 100000398093902 is a valid uid for example !
profile_email_name: email
profile_email_hash_name: email_hash
facebook_connect:
load_routing: true
user_permissions: []
[layout.php]
<!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" xml:lang="en" lang="en" xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<?php use_helper('sfFacebookConnect') ?>
<?php include_http_metas() ?>
<?php include_metas() ?>
<?php include_title() ?>
<link rel="shortcut icon" href="/favicon.ico" />
</head>
<body>
<?php echo $sf_content ?>
<?php include_bottom_facebook_connect_script(); ?>
</body>
</html>
[actions.class.php]
<?php
/**
* facebook actions.
*
* #package
* #subpackage facebook
* #author Your name here
* #version SVN: $Id: actions.class.php 12479 2008-10-31 10:54:40Z fabien $
*/
class homeActions extends sfActions
{
/**
* Executes index action
*
* #param sfRequest $request A request object
*/
public function executeIndex(sfWebRequest $request)
{
sfFacebook::requireLogin();
//get the user object
$user = $this->getUser();
// facebook user id
$this->fb_uid = $user->getCurrentFacebookUid();
// get or create user based on fb_uid
$fb_user = sfFacebook::getOrCreateUserByFacebookUid($this->fb_uid);
}
}
[indexSuccess.php]
<?php if ($sf_user->isFacebookConnected()): ?>
<fb:serverfbml style="width: 740px;">
<script type="text/fbml">
<fb:fbml>
<fb:request-form target="_top" action="[where to redirect after invite]" method="post" type="[name of your app]" content="[text the user will receive]<fb:req-choice url="http://apps.facebook.com/[your app]/" label="Accept!" " image="" invite="true">
<fb:multi-friend-selector cols="4" actiontext="[some text above the invite form]" />
</fb:request-form>
</fb:fbml>
</script>
</fb:serverfbml>
<?php else: ?>
<p>Ooops?</p>
<br />
<?php endif; ?>

Permission Denied Error XMLHttpRequest

<!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>Calling a Web Service Using XmlHttpRequest</title>
<script type="text/javascript" language="javascript">
var xmlhttp;
var XMLContent='<XML ID="Transaction"><Transaction>'+
'<LoginDetails>'+
'<Email>artur</Email>'+
'<Password>demos2</Password>'+
'</LoginDetails>'+
'<JobDetails>'+
'<JobId>40170978</JobId>'+
'<JobRefNo>prod84</JobRefNo>'+
'<JobTitle>'+
'<![CDATA[ Director of R&D Software product (Multimedia)]]>'+
'</JobTitle>'+
'<JobExpiry>30</JobExpiry>'+
'<JobContactName>'+
'<![CDATA[ Brian Mc Fadden]]>'+
'</JobContactName>'+
'<JobContactEmail>brian.mcfadden#recruiters.ie</JobContactEmail>'+
'<JobShortDesc>'+
'<![CDATA[ Director of R&D Software product concepts Multimedia Web 2.0]]> '+
'</JobShortDesc>'+
'<JobDetDesc><![CDATA[ <P class=MsoNormal style="MARGIN: 0cm 0cm 0pt; mso-margin-top-alt: auto; mso-margin-bottom-alt: auto"><STRONG>Director of R&D Software product concepts to</STRONG> build a the new prototyping team and processes from the ground up, utilizing an agile development model, manage the R&D team develop a strong vision and be able to clearly articulate the direction the group will take in terms of methodologies and tools in technologies such as J2EE, .NET, Flash, AJAX, DHTML, JavaScript, take marketing requirements from the principal investigators and write functional requirement documents, manage budget for R&D development, manage the projects developed by the internal team and vendors. </P> <P class=MsoNormal style="MARGIN: 0cm 0cm 0pt; mso-margin-top-alt: auto; mso-margin-bottom-alt: auto">To get this new role you will have a degree in IT / Software and over 5 years plus doing cutting edge development in R&D/ prototyping and leading cutting edge development teams in a software production / product environment, project management and process management skills (AGILE) and demonstrated experience working on product innovation and releases. You may be working in educational gaming, social networking, Web 2.0 applications, mobile technologies, learning management systems, online courseware or shareware. </P> <P class=MsoNormal style="MARGIN: 0cm 0cm 0pt; mso-margin-top-alt: auto; mso-margin-bottom-alt: auto"> </P> <P class=MsoNormal style="MARGIN: 0cm 0cm 0pt">The package is to €105K + Bonus + VHI + Pension + relocation package where applicable + stock options may be negotiated. There are great career advancement opportunities. To discuss this and other opportunities please send an up-to-date resume to brian.mcfadden#recruiters.ie or call +353 1 6489113 in confidence. Your details will not be sent to any third party without your consent. </P> <P class=MsoNormal style="MARGIN: 0cm 0cm 0pt"> </P>]]>'+
'</JobDetDesc>'+
'<JobSalary>90000</JobSalary>'+
'<JobSalaryMax>105000</JobSalaryMax>'+
'<JobQues1><![CDATA[ ]]>'+
'</JobQues1>'+
'<JobQues2><![CDATA[ ]]>'+
'</JobQues2>'+
'<JobQues3><![CDATA[ ]]>'+
'</JobQues3>'+
'<JobType>0|0</JobType>'+
'<JobAddnlBens>17,14,23,1,5,9,12,10</JobAddnlBens>'+
'<JobLocations>96,98,97</JobLocations>'+
'<JobEducations>8</JobEducations>'+
'<JobExperiences>10</JobExperiences>'+
'<JobCategories>1043,1050</JobCategories>'+
'<JobSubcategories>69896,69869</JobSubcategories>'+
'</JobDetails>'+
'</Transaction>'+
'</XML>';
function on_click()
{
if(window.ActiveXObject)
{
try
{
xmlhttp = new ActiveXObject('Msxml2.XMLHTTP');
}
catch (ex)
{
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
}
else if (window.XMLHttpRequest)
{
xmlhttp = new window.XMLHttpRequest();
netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
}
var xmlToSend = '<?xml version="1.0" encoding="utf-8"?>'+
'<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">'+
'<soap:Body>'+
'<InsertXML xmlns="http://recpushdata.cyndigo.com/">'+
'<Jobs>'+XMLContent+'</Jobs>'+
'</InsertXML>'+
'</soap:Body>'+
'</soap:Envelope>';
var szUrl;
szUrl = 'http://recpushdata.cyndigo.com/Jobs.asmx?op=InsertXML';
xmlhttp.onreadystatechange = state_Change;
xmlhttp.open("Post", szUrl, true);
xmlhttp.setRequestHeader ("SOAPAction", "http://recpushdata.cyndigo.com/InsertXML");
xmlhttp.setRequestHeader ("Content-Type", "text/xml");
xmlhttp.send(xmlToSend);
}
function state_Change()
{
// if xmlhttp shows "loaded"
if (xmlhttp.readyState==4)
{
// if "OK"
if (xmlhttp.status==200)
{
alert("OK"+xmlhttp.responseText);
}
else
{
alert("Problem retrieving XML data "+xmlhttp.responseText);
}
}
}
</script>
</head>
<body>
<div>
<h1>
Click the button to call the web service</h1>
<input type="button" onclick="return on_click();" value="OK" />
</div>
<div id="responseDiv">
</div>
</body>
</html>
XmlHttpRequest can only be used to call services local to the domain/server from where the page is being served.
Thus, if you're serving a page from:
http://www.example.com/page1
You cannot make an XmlHttpRequest to:
http://www.sample.com/webservice
Since you're setting Content-type, you need to also set it to use UTF-8. And I think it's supposed to be application/xml (source).
xmlhttp.setRequestHeader("Content-Type", "application/xml; charset=utf-8");
Otherwise, have you verified that the XML is properly formatted? Try saving it as a complete XML file and open it in your browser.
For Internet Explorer
http://www.simple-talk.com/dotnet/asp.net/calling-cross-domain-web-services-in-ajax/
For Firefox
http://installingcats.com/2008/01/29/how-to-fix-ajax-error-uncaught-exception-permission-denied-to-call-method-xmlhttprequestopen/