Getting an error doing serverside XML processing - c#

So I have an aspx page that servers XML + XSL to a client and does a client-side transform which works fine.
I am trying to detect the client and if they don't support client side transformation I am doing it serverside. I am interrupting the render processor the aspx page that would return XML and I am getting it's output, combining it with the output from the XSL page and serving it out. This output however is not well formed. I get
XML Parsing Error: mismatched tag. Expected: </link>.
Location: http://oohrl.com/dashboard.aspx
Line Number 36, Column 20: </script></head>
-------------------^
In the client side generated output, which works fine, I get for instance
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="stylesheet" type="text/css" href="./css/dboard.css"/>
<link rel="stylesheet" type="text/css" href="./css/dboardmenu.css"/>
<script type="text/javascript" src="./js/simpletabs.js"/>
<link href="../css/simpletabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"/>
<script type="text/javascript">
$(document).ready(function () {
$("#BlogSelectList li a").live("click", function () {
var str = ($(this).attr("href")).slice(1, 37)
$.ajax({
contentType: "application/json; charset=utf-8",
url: '../ws/WebServices.asmx/SetActiveBlog',
data: '{ActiveBlogID: "' + str + '"}',
dataType: 'json',
type: "post",
success: function (j) {
window.location.href = 'dashboard.aspx'
}
});
});
})
function showlayer(layer) {
var myLayer = document.getElementById(layer);
if (myLayer.style.display == "none" || myLayer.style.display == "") {
myLayer.style.display = "block";
}
else {
myLayer.style.display = "none";
}
}
</script></head>
If I generate it server side I get
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<META http-equiv="Content-Type" content="text/html; charset=utf-16">
<link rel="stylesheet" type="text/css" href="./css/dboard.css">
<link rel="stylesheet" type="text/css" href="./css/dboardmenu.css">
<script type="text/javascript" src="./js/simpletabs.js"></script>
<link href="../css/simpletabs.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function () {
$("#BlogSelectList li a").live("click", function () {
var str = ($(this).attr("href")).slice(1, 37)
$.ajax({
contentType: "application/json; charset=utf-8",
url: '../ws/WebServices.asmx/SetActiveBlog',
data: '{ActiveBlogID: "' + str + '"}',
dataType: 'json',
type: "post",
success: function (j) {
window.location.href = 'dashboard.aspx'
}
});
});
})
function showlayer(layer) {
var myLayer = document.getElementById(layer);
if (myLayer.style.display == "none" || myLayer.style.display == "") {
myLayer.style.display = "block";
}
else {
myLayer.style.display = "none";
}
}
</script></head>
Which gives me the error. Of course I notice the difference in the <link/> vs <link> tag but I have no idea why the server side processing engine give me different results or how to fix it?
Here is the code I use to generate the XHTML on the server
protected override void Render(HtmlTextWriter writer)
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
HtmlTextWriter hWriter = new HtmlTextWriter(sw);
base.Render(hWriter);
// *** store to a string
string XMLOutput = sb.ToString();
// *** Write it back to the server
if (!Request.Browser.IsBrowser("IE"))
{
writer.Write(XMLOutput);
}
else
{
StringWriter XSLsw = new StringWriter();
HttpContext.Current.Server.Execute("DashboardXSL.aspx", XSLsw);
string output = String.Empty;
using (StringReader srt = new StringReader(XSLsw.ToString())) // xslInput is a string that contains xsl
using (StringReader sri = new StringReader(XMLOutput)) // xmlInput is a string that contains xml
{
using (XmlReader xrt = XmlReader.Create(srt))
using (XmlReader xri = XmlReader.Create(sri))
{
XslCompiledTransform xslt = new XslCompiledTransform();
xslt.Load(xrt);
using (StringWriter _sw = new StringWriter())
using (XmlWriter xwo = XmlWriter.Create(_sw, xslt.OutputSettings)) // use OutputSettings of xsl, so it can be output as HTML
{
xslt.Transform(xri, xwo);
output = _sw.ToString();
}
}
}
writer.Write(output);
Response.Flush();
Response.End();
}

Because the root element of your output document is <html>, the processor chooses HTML as the default format. To create a well-formed XHTML document instead, make sure your XSLT contains the following as a child of the root <xsl:stylesheet> or <xsl:transform> element:
<xsl:output method="xml" omit-xml-declaration="yes" />

I had to set the content type on the xsl sheet to text/html which fixed all problems.
Note this change is ONLY used when transforming server side. When sending it to the client for a client transformation it is not changed to text/html

Related

MVC - display image from sqlite db

how can i export an image from DB - Sqlite and display this image in the view?
im using angular code, and the images byte stored now in x.img var.
i want to display the image in img tag.
i tried few ways...
please your help.
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">
<link href="~/Content/productmenuStyle.css" rel="stylesheet" />
<script src="~/Scripts/angular.js"></script>
<script type="text/javascript">
var app = angular.module("myCode", []);
app.controller("CodeController", function ($scope, $http) {
$scope.Table = false;
$scope.showProduct = function (num) {
$scope.number = num;
$scope.getProduct(num);
}
$scope.getProduct = function (num) {
var list = $http({
method: 'post',
url: 'getProductjson',
params: {
prClass: num
}
});
list.then(function (list) {
$scope.Products = list.data;
}, function () {
alert("Inavalid data !!!");
});
}
$scope.sendProduct = function (num) {
var list = $http({
method: 'post',
url: 'sendProduct',
params: {
pid: num,
}
});
list.then(function (list) {
alert("The Product Addad To The Cart");
}, function () {
alert("Inavalid data !!!");
});
}
});
</script>
</head>

Processing multiline html textarea in c#

I have a textarea on my html page
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("#btnSquareNumbers").click(function () {
var Calculate = $("#txtString").val();
//Calculate = $("#txtString") //.Replace("<br/>", ",").TrimEnd(',')
$.ajax({
url: "/api/SquareNumbers/SquareNums/",
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(Calculate),
success: function (result) {
$("#txtResult").val(result);
},
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
$("#txtResult").val(err.Message)
}
});
});
});
</script>
</head>
<body>
<textarea id="txtString" cols=50 rows="15"></textarea><br>
<input type="button" value="Square All Numbers" id="btnSquareNumbers"><br>
<output type="text" id="txtResult" disabled />
</body>
</html>
It will accept a vertical list of numbers e.g.
2
5
8
13
I need to send this to the C# controller, square each number and display the results on the web page.
When I run the code, it truncates the numbers and gives 25813 squared!
I am new to this... any advice?
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace ReturnMultilineText.Controllers
{
public class SquareNumbersController : ApiController
{
[HttpPost]
public List<int> SquareNums([FromBody]string Calculate)
{
List<string> caseList = txtString.Split().ToList();
List<int> intList = caseList.ConvertAll(int.Parse);
List<int> ans = new List<int>();
for (var i = 0; i < intList.Count; i++)
{
ans.Add((intList[i] * intList[i]));
}
return ans;
}
}
}
Input:
1 2 3 4
2 3 4
Gives Output:
1,4,9,16,1,4,9
I am nearly there now.... Need to find the linefeed... does stringify remove it? and replace it with a space?
GOT THE SOLUTION... just needed to split by "\n"...
string[] textList = Calculate.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries);
Cheers for the help and advice.

How to call webservice in HTML page using JQuery?

i have WebService that get 2 string and return if they equals
WebService that in http://192.168.100.MyIP/HTML_SIMPLE_TEST/
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class Service1 : System.Web.Services.WebService
{
[WebMethod(Description = "Validate the login credentials")]
public bool Validate(string UserName, string Password)
{
if (Password == "test" && UserName == "test")
return true;
else
return false;
}
}
and i have html page that call this WebService and need to return the Result
<html lang="en-US">
<head>
<meta http-equiv="content-type" content="application/xhtml+xml; charset=UTF-8" />
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
var Surl = "http://localhost:3031/WS_HTML/Service1.asmx/Validate";
$(document).ready(function () {
$("input#submit").click(function (event) {
//var uid = document.getElementById("UserName").value;
//var pwd = document.getElementById("Password").value;
var uid = "test";
var pwd = "test";
var dataString = "{ 'UserName' : '" + uid + "', 'Password' : '" + pwd + "'}";
$.ajax({
ServiceCallID: 1,
url: Surl,
type: 'POST',
data: dataString,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
returnVal = result.d;
alert(returnVal);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
returnVal = '';
}
});
});
});
</script>
</head>
<body >
<form method=post runat="server">
<input type="submit" />Connet to my WS
</form>
</body>
</html>
this what i get:
and i try this, still same problem....
<script>
function XX() {
alert("in");
$.post('http://localhost/WS_HTML/Service1.asmx/Validate', { username: 'test', password: 'test' }, function (response) {
response; // Here is response
alert(response);
});
}
</script>
</head>
<body >
<form method=post runat="server">
<input type="submit" onclick="XX();" />Connet to my WS2
</form>
</body>
</html>
i try with $.get - and same.... Nothing happens....
from the browser its work. if i write this: localhost/WS_HTML/Service1.asmx i see my WS,
but if i write this: localhost/WS_HTML/Service1.asmx/Validate i see error on browser =>
Request format is unrecognized for URL unexpectedly ending in '/Validate'.
I swear to God that for several days I break my head and can not figure out why it does not work
):
thanks,
You not forced to use jQuery for make Ajax request. You can use standard javascript (it's more efficient, and you have not to load library for that...)
Also, you don't have to create an click event for submit your form, you can juste create an HTML structure and submit by an onclick attribute, is more efficient (less browser memory).
<!DOCTYPE html>
<html lang="en-US">
<head>
<script type="text/javascript">
var myUrl = "http://localhost:3031/WS_HTML/Service1.asmx/Validate";
function submitMyForm(){
// Define your datas
var uid = "test";
var pwd = "test";
var dataString = "{ 'UserName' : '" + uid + "', 'Password' : '" + pwd + "'}";
// Create and send the request
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
// Log with console.log() or alert if you want...
console.log('State of my request changed! ');
if (XMLHttpRequest.DONE === request.readyState) {
console.log(request.responseText);
}
}
request.open('POST', myUrl, true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.send(data);
}
</script>
</head>
<body>
<form>
<button onclick="submitMyForm()" >Connect to my WS</button>
</form>
</body>
</html>
I see you use a basic javascript alert() on your code, for the debug you can use console.log() (you can see the doc here).
For your question, I don't think the problem is your HTML/Javascript. jQuery method you've look right. HTML too.
I think you've a problem with your server, This not a client problem. It's a server error : you can see that with your HTTP status code (405 -> doumentation for this HTTP code here).
Have you right configured your server ? You can surrely found informations about 405 method not Allowed - ISS server on this website, on or the MSDN forum
Hope I help you.
Why not use $.post() ?
$.post('/your/service/url/', {username:'asd', password:'qwe'}, function(response){
response; // Here is response
});

OAuth 2.0 access using javascript

I want to insert, update data from the fusion tables.
While selecting from the fusion table all seems to work fine. But during row addition i need to used OAuth 2.0 but unable to find a suitable solution to get the access token and use it during the insert.
A code sample would help a lot.
var fusiondata;
function initialize() {
// Initialize JSONP request
var script = document.createElement('script');
var url = ['https://www.googleapis.com/fusiontables/v1/query?'];
url.push('sql=');
var query = 'insert into 1bPbx7PVJU9NaxgAGKqN2da4g5EbXDybE_UVvlAE (name,luckynumber) values('abc',89)';
var encodedQuery = encodeURIComponent(query);
url.push(encodedQuery);
url.push('&callback=viewData');
url.push('&key=AIzaSyA0FVy-lEr_MPGk1p_lHSrxGZDcxy6wH4o');
script.src = url.join('');
var body = document.getElementsByTagName('body')[0];
body.appendChild(script);
}
function viewData(data) {
// code not required
}
I know most of you are suffering for google auth and inserting and updating fusion table. I am providing the entire code how to use the gauth lib to insert in a simple manner
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Authorization Request</title>
<script src="https://apis.google.com/js/client.js"></script>
<script type="text/javascript">
function auth() {
var config = {
'client_id': '365219651081-7onk7h52kas6cs5m17t1api72ur5tcrh.apps.googleusercontent.com',
'scope': 'https://www.googleapis.com/auth/fusiontables'
};
gapi.auth.authorize(config, function() {
console.log('login complete');
console.log(gapi.auth.getToken());
});
}
function insert_row(){
alert("insert called");
gapi.client.setApiKey('AIzaSyA0FVy-lEr_MPGk1p_lHSrxGZDcxy6wH4o');
var query = "INSERT INTO 1T_qE-o-EtX24VZASFDn6p3mMoPcWQ_GyErJpPIc(Name, Age) VALUES ('Trial', 100)";
gapi.client.load('fusiontables', 'v1', function(){
gapi.client.fusiontables.query.sql({sql:query}).execute(function(response){console.log(response);});
});
}
</script>
</head>
<body>
<button onclick="auth();">Authorize</button>
<p> </p>
<button onclick="insert_row();">Insert Data</button>
</body>
</html>

Reading XML data from ASMX webservice for Jquery autocomplete

Me and ASMX web services do not get on. We argue. She brings up arguments we had in the past. It's a pain. Our relationship is on the rocks!
I have an ASMX web service, which I haven't serialised with the Newtonsoft library (as explained why here: http://encosia.com/2011/04/13/asp-net-web-services-mistake-manual-json-serialization/). It looks like this:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string[] GetCitiesWithState(string isoalpha2, string prefixText)
{
var dict = AtomicCore.CityObject.GetCitiesInCountryWithStateAutocomplete(isoalpha2, prefixText);
string[] cities = dict.Values.ToArray();
return cities;
}
Simple enough right? It return this when searching for new:
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/">
<string>New Orleans, Louisiana</string>
<string>New York, New York</string>
</ArrayOfString>
I was expecting JSON, but after a bit of reading, it seems I shouldn't try and serialise the output - it should just happen right? Anyway, so I have the following JQuery on the frontend:
$('#<%=txtCity.ClientID%>').autocomplete('<%=ResolveUrl("~/AtomicService/Assets.asmx/GetCitiesWithState")%>', {
dataType: 'json',
httpMethod: 'POST',
contentType: 'application/json; charset=utf-8',
parse: function (data) {
var rows = new Array();
for (var i = 0; i < data.d.length; i++) {
rows[i] = { data: data.d[i], value: data.d[i].Value, result: data.d[i].Value };
}
return rows;
},
formatItem: function (row, i, n) {
return row.Value;
},
extraParams: {
minChars: 2,
isoalpha2: '<%=Session["BusinessCountry"].ToString()%>',
maxRows: 20,
prefixText: function () {
return $('#<%=txtCity.ClientID%>').val()
}
},
max: 20
}).result(function (event, data, formatted) {
if (data) {
alert(data['Key']);
}
});
I can see the calls using Chrome:
And yet stuff all happens! There is no Jquery errors, no fireworks, no anything. She is ignoring me.
At first I was blaming the webservice, but I think this may have more to do with how I'm parsing and formatting the data in jquery.
So, my question is, what am I doing wrong and how can I make the autocomplete work correctly?
Help appreciated :)
EDIT: It may not be helpful, but this is what I see in Fiddler:
The jQuery UI autocomplete does not anymore use the formatItem method. That and many other such methods were present in autocomplete's earlier version that was a plugin here
I have rewritten your code using the jQuery UI's autocomplete and it works for me with the below htm and asmx files.
Refer to the demos on the jQueryUI autocomplete for more methods you could use.
I have used the json2.min.js from www.json.org
Also I have added the [System.Web.Script.Services.ScriptService] attribute to the Service1 class so that it could directly be invoked from jQuery as a json web service.
These articles helped me:
ASMX and JSON – Common mistakes and misconceptions
Using jQuery to Consume ASP.NET JSON Web Services
3 mistakes to avoid when using jQuery with ASP.NET AJAX
The htm file
<!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>jQuery to ASMX</title>
<link rel="Stylesheet" type="text/css"
href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.11/themes/cupertino/jquery-ui.css"/>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.11/jquery-ui.min.js"></script>
<script type="text/javascript" src="http://localhost/Scripts/json2.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function() {
$("#txtInput").autocomplete({
source:function (request, response) {
var paramters = {
isoalpha2: '<%=Session["BusinessCountry"].ToString()%>',
prefixText: request.term
};
$.ajax({
url: 'Service1.asmx/GetCitiesWithState',
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(paramters),
success: function(data) {
response($.each(data.d, function(index, value) {
return {
label: value,
value: index
}
}));
}
});
},
minLength:2,
delay:500
});
});
</script>
<p>
Hello, World!</p>
<label for="txtInput">
Enter the string here:</label><input type="text" id="txtInput"/>
</body>
</html>
The asmx file
using System.Web.Script.Services;
using System.Web.Services;
namespace jQueryAutoCompleteBackEnd
{
/// <summary>
/// Summary description for Service1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[ScriptService]
public class Service1 : WebService
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string[] GetCitiesWithState(string isoalpha2, string prefixText)
{
return new string[] { "New Orleans, Lousiana", "New York, New York" };
}
}
}
The reason that the asmx webmethod is returning XML rather than JSON is because the HTTP method is GET rather than POST.
In order for the autocomplete plugin to use POST you'll have to implement the source parameter using a callback function, see here

Categories