XMLHttpRequest Request URI too large (414) - uri

Well I hoped everything would work fine finally. But of course it doesn't. The new problem is the following message:
Request-URI Too Large The requested URL's length exceeds the
capacity limit for this server.
My fear is that I have to find another method of transmitting the data or is a solution possible?
Code of XHR function:
function makeXHR(recordData)
{
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
var rowData = "?q=" + recordData;
xmlhttp.open("POST", "insertRowData.php"+rowData, true);
xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-Length",rowData.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
alert("Records were saved successfully!");
}
}
xmlhttp.send(null);
}

You should POST rowData in the request body via the send method. So, instead of posting to "insertRowData.php" + rowData, POST to "insertRowData.php" and pass the data in rowData to send.
I suspect that your rowData is a query string with the question mark. If that is the case, then the message body is simply rowData without the prepended question mark.
EDIT: Something like this should work:
var body = "q=" + encodeURIComponent(recordData);
xmlhttp.open("POST", "insertRowData.php", true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = // ...
xmlhttp.send(body);

Related

Getting error when a method is made for post request

When made I post request is made its giving internal server. Is the implementation of Flurl is fine or I am doing something wrong.
try
{
Models.PaymentPost paymentPost = new Models.PaymentPost();
paymentPost.Parts = new Models.Parts();
paymentPost.Parts.Specification = new Models.Specification();
paymentPost.Parts.Specification.CharacteristicsValue = new List<Models.CharacteristicsValue>();
paymentPost.Parts.Specification.CharacteristicsValue.Add(new Models.CharacteristicsValue { CharacteristicName = "Amount", Value = amount });
paymentPost.Parts.Specification.CharacteristicsValue.Add(new Models.CharacteristicsValue { CharacteristicName = "AccountReference", Value = accountId });
foreach (var item in extraParameters)
{
paymentPost.Parts.Specification.CharacteristicsValue.Add(new Models.CharacteristicsValue {
CharacteristicName = item.Key, Value = item.Value });
}
var paymentInJson = JsonConvert.SerializeObject(paymentPost);
var selfCareUrl = "http://svdt5kubmas01.safari/auth/processPaymentAPI/v1/processPayment";
var fUrl = new Flurl.Url(selfCareUrl);
fUrl.WithBasicAuth("***", "********");
fUrl.WithHeader("X-Source-System", "POS");
fUrl.WithHeader("X-Route-ID", "STKPush");
fUrl.WithHeader("Content-Type", "application/json");
fUrl.WithHeader("X-Correlation-ConversationID", "87646eaa-2605-405e-967c-56e8002b5");
fUrl.WithHeader("X-Route-Timestamp", "150935");
fUrl.WithHeader("X-Source-Operator", " ");
var response = await clientFactory.Get(fUrl).Request().PostJsonAsync(paymentInJson).ReceiveJson<IEnumerable<IF.Models.PaymentPost>>();
return response;
}
catch (FlurlHttpException ex)
{
dynamic d = ex.GetResponseJsonAsync();
//string s = ex.GetResponseStringAsync();
return d;
}
You don't need to do this:
var paymentInJson = JsonConvert.SerializeObject(paymentPost);
PostJsonAsync just takes a regular object and serializes it to JSON for you. Here you're effectively double-serializing it and the server is probably confused by that format.
You're also doing a lot of other things that Flurl can do for you, such as creating those Url and client objects explicitly. Although that's not causing errors, this is how Flurl is typically used:
var response = await selfCareUrl
.WithBasicAuth(...)
.WithHeader(...)
...
.PostJsonAsync(paymentPost)
.ReceiveJson<List<IF.Models.PaymentPost>>();

Javascript for CRM 2016 phones

I would like to ask about CRM Javascript code for phones, for example I have the following JS(Javascript) code for CRM web application it's not working with CRM phones
function checkCurrentUserInTeam(teamId) {
var serverUrl = "https://" + window.location.host;
var userId = Xrm.Page.context.getUserId();
if (teamId != null) {
var fwdFilter = "TeamMembershipSet?$filter=TeamId eq guid'" + teamId + "' and SystemUserId eq guid'" + userId + "'";
var url = serverUrl + "/xrmservices/2011/OrganizationData.svc/" + fwdFilter;
var fwdResult = GetOdataResults(url).results;
if (fwdResult != null && fwdResult.length > 0) {
return true;
}
else {
return false;
}
}
return false;
}
function GetOdataResults(url) {
CallOData(url);
str = CallOData(url);
var data = eval('(' + str + ')');
return data.d;
}
function CallOData(url) {
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", url, false);
xmlhttp.setRequestHeader("X-Requested-Width", "XMLHttpRequest");
xmlhttp.setRequestHeader("Accept", "application/json, text/javascript, */*");
xmlhttp.send(null);
return xmlhttp.responseText;
}
I'm using checkCurrentUserInTeam function with team ID as parameter, and the error I think when XMLHttpRequest call the page in phones (See the below pic) .
Click here to view the image
I need your help if you have a specially code for CRM phones or some library for it. Any help in this regard will be highly appreciated.
Thanks ..
It might be the way you are creating your serverUrl. Try using getClientUrl instead.
var serverUrl = Xrm.Page.context.getClientUrl()

How to capture data from third party web site?

For example, I would just like to capture the data for the 30 latest events for the scrolling info shown on this URL:
http://hazmat.globalincidentmap.com/home.php#
Any idea how to capture it?
What language are you using? In Java, you can get the page HTML content using something like this:
URL url;
InputStream is = null;
BufferedReader br;
String line;
try {
url = new URL("http://hazmat.globalincidentmap.com/home.php");
is = url.openStream(); // throws an IOException
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
// Here you need to parse the HTML lines until
//you find something you want, like for example
// "eventdetail.php?ID", and then read the content of
// the <td> tag or whatever you want to do.
}
} catch (MalformedURLException mue) {
mue.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
try {
if (is != null) is.close();
} catch (IOException ioe) {
}
}
Example in PHP:
$c = curl_init('http://hazmat.globalincidentmap.com/home.php');
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
$html = curl_exec($c);
if (curl_error($c))
die(curl_error($c));
$status = curl_getinfo($c, CURLINFO_HTTP_CODE);
curl_close($c);
And then parse the contents of $html variable.

Generating PDFs using Phantom JS on .NET applications

I have been looking into phantomJS and looks like it could be a great tool to use generating PDFs. I wonder if anyone have successfully used it for their .NET applications.
My specific question is: how would you use modules like rasterize.js on the server, receive requests and send back generated pdfs as a response.
My general question is: is there any best practice for using phantomJS with .NET Applications. What would be the best way to achieve it?
I am fairly new in .NET World and I would appreciate the more detailed answers. Thanks everyone. :)
I don't know about best practices, but, I'm using phantomJS with no problems with the following code.
public ActionResult DownloadStatement(int id)
{
string serverPath = HttpContext.Server.MapPath("~/Phantomjs/");
string filename = DateTime.Now.ToString("ddMMyyyy_hhmmss") + ".pdf";
new Thread(new ParameterizedThreadStart(x =>
{
ExecuteCommand("cd " + serverPath + #" & phantomjs rasterize.js http://localhost:8080/filetopdf/" + id.ToString() + " " + filename + #" ""A4""");
})).Start();
var filePath = Path.Combine(HttpContext.Server.MapPath("~/Phantomjs/"), filename);
var stream = new MemoryStream();
byte[] bytes = DoWhile(filePath);
return File(bytes, "application/pdf", filename);
}
private void ExecuteCommand(string Command)
{
try
{
ProcessStartInfo ProcessInfo;
Process Process;
ProcessInfo = new ProcessStartInfo("cmd.exe", "/K " + Command);
ProcessInfo.CreateNoWindow = true;
ProcessInfo.UseShellExecute = false;
Process = Process.Start(ProcessInfo);
}
catch { }
}
public ViewResult FileToPDF(int id)
{
var viewModel = file.Get(id);
return View(viewModel);
}
private byte[] DoWhile(string filePath)
{
byte[] bytes = new byte[0];
bool fail = true;
while (fail)
{
try
{
using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
bytes = new byte[file.Length];
file.Read(bytes, 0, (int)file.Length);
}
fail = false;
}
catch
{
Thread.Sleep(1000);
}
}
System.IO.File.Delete(filePath);
return bytes;
}
Here is the action flow:
The user clicks on a link to DownloadStatement Action. Inside there, a new Thread is created to call the ExecuteCommand method.
The ExecuteCommand method is responsible to call phantomJS. The string passed as an argument do the following.
Go to the location where the phantomJS app is and, after that, call rasterize.js with an URL, the filename to be created and a print format. (More about rasterize here).
In my case, what I really want to print is the content delivered by the action filetoupload. It's a simple action that returns a simple view. PhantomJS will call the URL passed as parameter and do all the magic.
While phantomJS is still creating the file, (I guess) I can not return the request made by the client. And that is why I used the DoWhile method. It will hold the request until the file is created by phantomJS and loaded by the app to the request.
If you're open to using NReco.PhantomJS, which provides a .NET wrapper for PhantomJS, you can do this very succinctly.
public async Task<ActionResult> DownloadPdf() {
var phantomJS = new PhantomJS();
try {
var temp = Path.Combine(Path.GetTempPath(),
Path.ChangeExtension(Path.GetRandomFileName(), "pdf")); //must end in .pdf
try {
await phantomJS.RunAsync(HttpContext.Server.MapPath("~/Scripts/rasterize.js"),
new[] { "https://www.google.com", temp });
return File(System.IO.File.ReadAllBytes(temp), "application/pdf");
}
finally {
System.IO.File.Delete(temp);
}
}
finally {
phantomJS.Abort();
}
}
Here's some very basic code to generate a PDF using Phantom.JS but you can find more information here: https://buttercms.com/blog/generating-pdfs-with-node
var webPage = require('webpage');
var page = webPage.create();
page.viewportSize = { width: 1920, height: 1080 };
page.open("http://www.google.com", function start(status) {
page.render('google_home.pdf, {format: 'pdf', quality: '100'});
phantom.exit();
});

A simple secenario to implement JavaScript ASP.NET C#, question rephrased

I had asked this question before, but I got no correct answer.
So, this is a simple thing:
textbox.text='user typing';
Button: store the value to a variable and a database.
Very simple, nothing to it.
But there should be no post back, that is the page must not load again.
Try Ajax? I tried it, but it is not working.
I lost a lot of time trying to implement this using JavaScript Ajax and read many many posts.
But for some reason I cannot implement the functionality correctly.
var xmlHttp;
var is_ie = (navigator.userAgent.indexOf('MSIE') >= 0) ? 1 : 0;
var is_ie5 = (navigator.appVersion.indexOf("MSIE 5.5")!=-1) ? 1 : 0;
var is_opera = ((navigator.userAgent.indexOf("Opera6")!=-1)||(navigator.userAgent.indexOf("Opera/6")!=-1)) ? 1 : 0;
//netscape, safari, mozilla behave the same???
var is_netscape = (navigator.userAgent.indexOf('Netscape') >= 0) ? 1 : 0;
function btnClick(){
if (strReportURL.length > 0)
{
//Create the xmlHttp object to use in the request
//stateChangeHandler will fire when the state has changed, i.e. data is received back
// This is non-blocking (asynchronous)
xmlHttp = GetXmlHttpObject(handler);
//Send the xmlHttp get to the specified url
xmlHttp_Get(xmlHttp, "AjaxHanlder.aspx?Data="+txtData.Text,handler);
}
}
//stateChangeHandler will fire when the state has changed, i.e. data is received back
// This is non-blocking (asynchronous)
function handler()
{
//readyState of 4 or 'complete' represents that data has been returned
if (xmlHttp.readyState == 4 || xmlHttp.readyState == 'complete')
{
//Gather the results from the callback
var result = xmlHttp.responseText;
//Populate the innerHTML of the div with the results
document.getElementById('lblResult').innerHTML = result;
}
}
// XMLHttp send GET request
function xmlHttp_Get(xmlhttp, url,handler) {
xmlhttp.open('GET', url, true);
xmlhttp.onreadystatechange = handler;
xmlhttp.send(null);
}
function GetXmlHttpObject(handler) {
var objXmlHttp = null; //Holds the local xmlHTTP object instance
//Depending on the browser, try to create the xmlHttp object
if (is_ie){
//The object to create depends on version of IE
//If it isn't ie5, then default to the Msxml2.XMLHTTP object
var strObjName = (is_ie5) ? 'Microsoft.XMLHTTP' : 'Msxml2.XMLHTTP';
//Attempt to create the object
try{
if(!objXmlHttp)
objXmlHttp = new ActiveXObject(strObjName);
//objXmlHttp.onreadystatechange = handler;
}
catch(e){
//Object creation errored
alert('IE detected, but object could not be created. Verify that active scripting and activeX controls are enabled');
return;
}
}
else if (is_opera){
//Opera has some issues with xmlHttp object functionality
alert('Opera detected. The page may not behave as expected.');
return;
}
else{
// Mozilla | Netscape | Safari
objXmlHttp = new XMLHttpRequest();
objXmlHttp.onload = handler;
objXmlHttp.onerror = handler;
}
//Return the instantiated object
return objXmlHttp;
}
///AJAX HANDLER PAGE
public class AjaxHandler : System.Web.UI.Page
{
private void Page_Load(object sender, System.EventArgs e)
{
if(Request.QueryString["Data"]!=null)
{
StoreYourData(Request.QueryString);
}
}
}

Resources