Problems with PhantomJS: phantom.args doesn't seem to work - c#

Here is my PhantomJS test project which I run in cmd.exe by typing (for example):
>phantomjs.exe abacus.js 1111 222
name: 1111
pass: 222
load started
load finished
jQuery loaded
console> name:
console> pass: undefined
step 0
step 1
done
Abacus.js:
var name, pass;
if (phantom.args.length !== 2) {
console.log('not enough arguments!');
phantom.exit();
} else {
name = phantom.args[0];
pass = phantom.args[1];
}
console.log("name: " + name); //output: "name: MyUsername"
console.log("pass: " + pass); //output: "pass: MyPassword"
var stepIndex = 0;
var page = new WebPage();
var loadInProgress = true;
var jQueryLoad = false;
page.onConsoleMessage = function (msg, line, source) {
console.log('console> ' + msg);
};
page.onAlert = function (msg) {
console.log('alert> ' + msg);
};
page.onLoadStarted = function () {
loadInProgress = true;
console.log("load started");
};
page.onLoadFinished = function () {
loadInProgress = false;
console.log("load finished");
jQueryLoad = page.injectJs("jquery-1.7.1.min.js");
if (jQueryLoad)
console.log('jQuery loaded');
};
var interval = setInterval(function () {
if (jQueryLoad && !loadInProgress && typeof steps[stepIndex] == "function") {
steps[stepIndex]();
page.render("step " + stepIndex + ".png");
console.log("step " + stepIndex++);
}
if (typeof steps[stepIndex] != "function") {
console.log("done");
phantom.exit();
}
}, 1000);
var steps = [
function () {
page.evaluate(function () {
console.log("name: " + this.name); //output: "console> name:"
console.log("pass: " + this.pass); //output: "console> pass: undefined"
var arr = document.frmMain;
if (arr !== null) {
arr.elements["username"].value = "MyUsername"; //Only fils in form if it's a string literal
arr.elements["password"].value = "MyPassword";
} else {
console.log("Could not find frmMain");
}
});
}, function () {
page.evaluate(function () {
document.frmMain.submit();
});
} ];
page.open("http://www.abacusdatagraphics.com/");
page.viewportSize = { width: 1280, height: 1024 };
Any help would be appreciated as to why phantom.args & name/pass suddenly lose their values.
I am running cmd.exe in C# since the name and password change every now and then and are kept in a database. This is simply a small test program to see if it can be done.
(Also, thanks to Stack Overflow for giving me most of this code in the first place)

#jlafay
The solution I used from this is as such:
PhantomJS wasn't able to fill in the forms with variables because page.evaluate can't handle parameters so when filling out the form, the variables (and the forms) are null.
So instead I treated function() as a string and passed the variables like this:
page.evaluate('function () {' +
'var theName = ' + name + ';' +
'var thePass = ' + pass + ';' +
'console.log(\"name: \" + this.name);' + //output: "console> name:"
'console.log(\"pass: \" + this.pass);' + //output: "console> pass: undefined"
'var arr = document.frmMain;' +
'if (arr !== null) {' +
' arr.elements["username"].value = theName;' +
' arr.elements["password"].value = thePass;' +
'} else {' +
' console.log("Could not find frmMain");' +
'}' +
'}');
Or something like that, I don't have the code anymore.

Related

C# JQuery, Load data in webform and pass it to another webform

I'm making a "Ping" (ICMP) web application and I need to show the time results of the ping in a graph (I'm using shieldui). I'm really new to web development and so my knowledge on the frameworks is limited.
In "ping.aspx", I am loading a list of the servers I want to be able to ping. When I press a button labelled "ping", the web application will ping all the servers and then open a new window with a single graphic per each server.
It is working till the point of loading the graph in the new window
Here is my grafica.aspx file:
$(".pingAll").click(function () {
primerClick = true;
$("#txtLista option").each(function () {
var valorSvr = $(this).val();
//var container = $("#contenedorChart");
//var grafics = container.find("div");
//var idGrafics = grafics.length + 1;
//container.append("<div id=shieldui-chart" + valorSvr + "></div>");
refreshListaServidores(valorSvr)
});
//window.location.href = 'graficas.aspx';
});
function refreshListaServidores(valorSvr) {
$("#txtLista option").each(function () {
var valorSvr = $(this).val();
var container = $("#contenedorChart");
var grafics = container.find("div");
var idGrafics = grafics.length + 1;
container.append("<div id=shieldui-chart" + valorSvr + "></div>");
});
lista = lista + "|" + valorSvr;
var data = {
vl: lista
}
$.ajax({
type: "POST",
url: "ping.aspx/valoresLista",
cache: false,
async: true,
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
var resultado = result.d
$.each(resultado, function (index, item) {
var resultPing = { items: [] };
var resultadoGrafica = { grafica: [null] };
$.each(item, function (inde, ite) {
var valMs = ite.ms;
var valServer = ite.servers;
var txtData = "Servidor: " + valServer + " | " + "Dirección: " + ite.address + " | " +
"Time to Live: " + ite.ttl + " | " + "Tamaño Buffer: " + ite.bufferSize + " | " +
"Tiempo en ms: " + valMs + "\n";
resultadoGrafica.grafica.push(valMs);
resultPing.items.push(txtData);
});
$("#txtResultPing").val(resultPing.items);
jQuery(function ($) {
$("div[id*='shieldui-chart" + valorSvr + "']").shieldChart({
axisX: {
axisType: 'linear',
ticksColor: 'yellow',
borderColor: 'yellow',
min: 1,
max: 40
},
theme: "dark",
primaryHeader: {
text: "Gráfico de: " + valorSvr
},
exportOptions: {
image: false,
print: false
},
dataSeries: [{
seriesType: "line",
collectionAlias: "Tiempos en ms",
data: resultadoGrafica.grafica
}]
});
});
});
}, error: function (result, xhr, ajaOptions, throwError) {
var vainaconvaina = result + xhr + ajaOptions + throwError;
}
});
}
and in back code, in c# I have
[WebMethod]
public static List<List<dataResult>> valoresLista(string vl)
{
dataResult dataRes = new dataResult();
HttpContext.Current.Session["pingas"] = vl;
Ping ping = new Ping();
string contentLista = vl;
string[] contentListaArray = contentLista.Split('|');
List<dataResult> listaPing = new List<dataResult>();
List<List<dataResult>> listaGral = new List<List<dataResult>>();
foreach (string word in contentListaArray)
{
dataRes = new dataResult();
if (!string.IsNullOrEmpty(word.ToString()))
{
try
{
listaPing = new List<dataResult>();
for (int i = 1; i <= 40; i++)
{
dataRes = new dataResult();
ping = new Ping();
PingReply pingreply = ping.Send(word);
if (pingreply.Status == IPStatus.Success)
{
dataRes.servers = Convert.ToString(word);
dataRes.address += Convert.ToString(pingreply.Address);
dataRes.ms += Convert.ToInt32(pingreply.RoundtripTime);
dataRes.ttl += Convert.ToInt32(pingreply.Options.Ttl);
dataRes.bufferSize += Convert.ToString(pingreply.Buffer.Length.ToString());
dataRes.errr += "Successful";
}
else
{
dataRes.errr = Convert.ToString("Host de destino no disponible o inalcanzable");
}
listaPing.Add(dataRes);
}
}
catch (Exception err)
{
PingReply pingreply = ping.Send(word);
if (pingreply.Status == IPStatus.DestinationHostUnreachable || pingreply.Status == IPStatus.DestinationNetworkUnreachable || pingreply.Status == IPStatus.TimeExceeded || pingreply.Status == IPStatus.TtlExpired || pingreply.Status == IPStatus.Unknown)
{
string emailEnProceso = "Se le informa ";
emailEnProceso += Environment.NewLine;
emailEnProceso += Environment.NewLine;
emailEnProceso += "que el servidor " + vl;
emailEnProceso += Environment.NewLine;
emailEnProceso += Environment.NewLine;
emailEnProceso += "podría estar presentando fallos debido a que en el último minuto no estuvo respondiento las solicitudes de ping ";
emailEnProceso += Environment.NewLine;
emailEnProceso += "Tome las medidas necesarias. ";
emailEnProceso += Environment.NewLine;
emailEnProceso += Environment.NewLine;
emailEnProceso += "something";
emailEnProceso += Environment.NewLine;
emailEnProceso += "www.somethingelse.com";
string asunto = "Falla en el servidor " + vl;
enviarMail(emailEnProceso, asunto, "someEmail#gmail.com");
listaPing.Add(dataRes);
}
else
{
dataRes.errr = Convert.ToString(err.Message);
}
}
listaGral.Add(listaPing);
}
}
return listaGral;
}
I'm pretty sure this code is not that bad at all, but what I need to know is how to "move" the data from "ping.aspx" to "grafica.aspx".
Maybe I am really close, but in fact I don't really understand how to organize myself between to webforms.
Thanks a lot.
As far as I see from your code fragments, it seems to be ok. But it depends what data you get on the post success. Also you do not need to create a new chart instance on each request, you just can refresh the existing instance.
The whole app is needed though for detailed help.

Group query to get specific order

I use this query to populate my gallery:
function GalleryCatPopulate(url, listname, target) {
var eng = false;
if ((window.location.href.indexOf("lang=en") > 0)) {
eng = true;
}
// Getting our list items
$.ajax({
url: url + "/_api/web/lists/getbytitle('" + listname + "')/items?$select=Title,English",
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
completeGalleryCat(data, target, eng);
},
error: function (data) {
failureGalleryCat(data, target);
}
});
}
function completeGalleryCat(data, target, eng) {
var items = data.d.results;
var prefix = "";
var sufix = "<div class='clear'></div>";
//if (eng)
// prefix = "<div class='filter selected' data-category='cat-all'>All</div>";
//else
// prefix = "<div class='filter selected' data-category='cat-all'>Todas</div>";
var menu = "";
var cat = "";
var title = "Transporte de Materiales";
console.log(title.replace(/\s/g, "_").replace(/[^\w\s]/gi, ''));
for (var item in items) {
if (eng)
cat = items[item].English;
else
cat = items[item].Title;
menu += "<div class='filter' data-category='" + cat.replace(/\s/g, "_").replace(/[^\w\s]/gi, '') +"'>"+ cat +"</div>";
}
$(target).html(prefix + menu + sufix);
}
function failureGalleryCat(data, target) {
$(target).text("Ocurrió un error en la carga las categorias. Por favor revise la consola para más información");
}
function GalleryContentPopulate(url, listname, target) {
var eng = false;
var queryGallery = "$select=Title,Description,Enlace,EncodedAbsUrl,Categoria/Title&$expand=Categoria/Title$SortField=Title&SortDir=Desc";
if ((window.location.href.indexOf("lang=en") > 0)) {
queryGallery = "$select=TitleEnglish,DescriptionEnglish,Enlace,EncodedAbsUrl,Categoria/English&$expand=Categoria/English";
eng = true;
}
// Getting our list items
$.ajax({
url: url + "/_api/web/lists/getbytitle('" + listname + "')/items?$top=1000&" + queryGallery,
//url: url + "/_api/web/lists/getbycategory('Office'),
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
completeGalleryContent(data, target, eng);
},
error: function (data) {
failureGalleryContent(data, target);
}
});
}
function completeGalleryContent(data, target, eng) {
var items = data.d.results;
//console.log(items);
var menu = "";
var cat = "";
for (var item in items) {
if(items[item].DescriptionEnglish==null)
items[item].DescriptionEnglish="";
if(items[item].Description==null)
items[item].Description="";
if(items[item].Categoria.results!= null && items[item].Categoria.results!= undefined && items[item].Categoria.results.length > 0){
cat =setCategories(eng,items[item].Categoria.results);
}
if (eng){
//menu += "<div class='mega-entry " + cat + " cat-all' id='mega-entry-1' data-src='" + items[item].EncodedAbsUrl + "' data-width='' data-height='' data-lowsize=''><div class='mega-covercaption mega-square-bottom mega-landscape-right mega-portrait-bottom mega-red'><div class='mega-title'>" + items[item].TitleEnglish + "</div><p>" + items[item].DescriptionEnglish + "</p></div><div class='mega-coverbuttons'><div class='mega-link mega-red'></div><a class=' ' rel='group' href='" + items[item].EncodedAbsUrl + "' title='" + items[item].TitleEnglish + "'><div class='mega-view mega-red'></div></a></div></div>";
menu += "<div class='mega-entry " + cat + " cat-all' id='mega-entry-1' data-src='" + items[item].EncodedAbsUrl + "' data-width='' data-height='' data-lowsize=''><div class='mega-covercaption mega-square-bottom mega-landscape-right mega-portrait-bottom mega-red'><div class='mega-title'>" + items[item].TitleEnglish + "</div><p>" + items[item].DescriptionEnglish + "</p></div><div class='mega-coverbuttons'><a class=' ' rel='group' href='" + items[item].EncodedAbsUrl + "' title='" + items[item].TitleEnglish + "'><div class='mega-view mega-red'></div></a></div></div>";
}else{
//menu += "<div class='mega-entry "+ cat + " cat-all' id='mega-entry-1' data-src='" + items[item].EncodedAbsUrl + "' data-width='' data-height='' data-lowsize=''><div class='mega-covercaption mega-square-bottom mega-landscape-right mega-portrait-bottom mega-red'><div class='mega-title'>" + items[item].Title + "</div><p>" + items[item].Description + "</p></div><div class='mega-coverbuttons'><div class='mega-link mega-red'></div><a class='fancybox' rel='group' href='" + items[item].EncodedAbsUrl + "' title='"+ items[item].Title +"'><div class='mega-view mega-red'></div></a></div></div>";
menu += "<div class='mega-entry "+ cat + " cat-all' id='mega-entry-1' data-src='" + items[item].EncodedAbsUrl + "' data-width='' data-height='' data-lowsize=''><div class='mega-covercaption mega-square-bottom mega-landscape-right mega-portrait-bottom mega-red'><div class='mega-title'>" + items[item].Title + "</div><p>" + items[item].Description + "</p></div><div class='mega-coverbuttons'><a class='fancybox' rel='group' href='" + items[item].EncodedAbsUrl + "' title='"+ items[item].Title +"'><div class='mega-view mega-red'></div></a></div></div>";
}
}
$(target).html(menu);
var api = $(target).megafoliopro(
{
filterChangeAnimation: "pagebottom", // fade, rotate, scale, rotatescale, pagetop, pagebottom,pagemiddle
filterChangeSpeed: 400, // Speed of Transition
filterChangeRotate: 99, // If you ue scalerotate or rotate you can set the rotation (99 = random !!)
filterChangeScale: 0.6, // Scale Animation Endparameter
delay: 20,
defaultWidth: 980,
paddingHorizontal: 10,
paddingVertical: 10,
layoutarray: [9, 11, 5, 3, 7, 12, 4, 6, 13] // Defines the Layout Types which can be used in the Gallery. 2-9 or "random". You can define more than one, like {5,2,6,4} where the first items will be orderd in layout 5, the next comming items in layout 2, the next comming items in layout 6 etc... You can use also simple {9} then all item ordered in Layout 9 type.
});
//console.log("entra");
// FANCY BOX ( LIVE BOX) WITH MEDIA SUPPORT
//console.log("sale");
// THE FILTER FUNCTION
$('.filter').click(function () {
$('.filter').each(function () { jQuery(this).removeClass("selected") });
api.megafilter(jQuery(this).data('category'));
$(this).addClass("selected");
});
var categorySelected = getParameterByName("Category");
// $('[data-category="Office"],[data-category="Oficinas"]').click();
// Aquí agarramos la primera categoria
$(".filter").eq(0).trigger("click");
$("div[data-category='"+categorySelected +"']").click();
jQuery(".fancybox").fancybox();
}
function failureGalleryContent(data, target) {
// console.log(data);
$(target).text("Ocurrió un error en la carga la sección parallax. Por favor revise la consola para más información");
}
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
function setCategories(boolLang, objResult){
var cat ="";
for(var item in objResult){
if(boolLang)
cat += replaceAll(" ", "_",objResult[item].English.replace(/[^\w\s]/gi, '')) + ' ';
else
cat += replaceAll(" ", "_",objResult[item].Title.replace(/[^\w\s]/gi, '')) + ' ';
}
return cat;
}
function replaceAll( find, replace,string) {
return string.replace(new RegExp(escapeRegExp(find), 'g'), replace);
}
function escapeRegExp(string) {
return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}
The problem is that I don´t know why first take one image of each category and after that get all images of one categorie, for example
I have this categories
Services, Home, Office
In my first row of images I get:
firstimageServices
firstimageHome
firstimageOffice
secondimageOffice
thirdimageOffice
etc...
But I want to group all by categorie, so it will be:
firstimageServices
secondimageServices
thirdimageServices
fourimageServices
etc...
firstimageHome
secondimageHome
thirdimageHome
fourimageHome
etc...
firstimageOffice
secondimageOffice
thirdimageOffice
fourimageOffice
etc..
How can I do in my query to group it? Regards!
Note: I look something of interest in these link msdn but how can I apply it in my query to sort by "Title"
So In first fields I get something like that:
When it pass first rows of categories I get that I want like these:
I finally do it just change query for:
"$select=Title,Description,Enlace,EncodedAbsUrl,Categoria/Title&$expand=Categor‌​i‌​a/Title&$orderby=Title asc";

site freezes after closing the print window

I am using jquery.printElement.js to print. When I click on print button a print window opens with print and cancel button. If I print the document or cancel the print window every thing works fine, but if I close the window with the close button in the title bar [x] than everything stops working after dispose of print window on chrome version 35.
/// <reference path="http://code.jquery.com/jquery-1.4.1-vsdoc.js" />
/*
* Print Element Plugin 1.2
*
* Copyright (c) 2010 Erik Zaadi
*
* Inspired by PrintArea (http://plugins.jquery.com/project/PrintArea) and
* http://stackoverflow.com/questions/472951/how-do-i-print-an-iframe-from-javascript-in-safari-chrome
*
* Home Page : http://projects.erikzaadi/jQueryPlugins/jQuery.printElement
* Issues (bug reporting) : http://github.com/erikzaadi/jQueryPlugins/issues/labels/printElement
* jQuery plugin page : http://plugins.jquery.com/project/printElement
*
* Thanks to David B (http://github.com/ungenio) and icgJohn (http://www.blogger.com/profile/11881116857076484100)
* For their great contributions!
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
* Note, Iframe Printing is not supported in Opera and Chrome 3.0, a popup window will be shown instead
*/
; (function (window, undefined) {
var document = window["document"];
var $ = window["jQuery"];
$.fn["printElement"] = function (options) {
var mainOptions = $.extend({}, $.fn["printElement"]["defaults"], options);
//iframe mode is not supported for opera and chrome 3.0 (it prints the entire page).
//http://www.google.com/support/forum/p/Webmasters/thread?tid=2cb0f08dce8821c3&hl=en
if (mainOptions["printMode"] == 'iframe') {
if ($.browser.opera || (/chrome/.test(navigator.userAgent.toLowerCase())))
mainOptions["printMode"] = 'popup';
}
//Remove previously printed iframe if exists
$("[id^='printElement_']").remove();
return this.each(function () {
//Support Metadata Plug-in if available
var opts = $.meta ? $.extend({}, mainOptions, $(this).data()) : mainOptions;
_printElement($(this), opts);
});
};
$.fn["printElement"]["defaults"] = {
"printMode": 'iframe', //Usage : iframe / popup
"pageTitle": '', //Print Page Title
"overrideElementCSS": null,
/* Can be one of the following 3 options:
* 1 : boolean (pass true for stripping all css linked)
* 2 : array of $.fn.printElement.cssElement (s)
* 3 : array of strings with paths to alternate css files (optimized for print)
*/
"printBodyOptions": {
"styleToAdd": 'padding:10px;margin:10px;', //style attributes to add to the body of print document
"classNameToAdd": '' //css class to add to the body of print document
},
"leaveOpen": false, // in case of popup, leave the print page open or not
"iframeElementOptions": {
"styleToAdd": 'border:none;position:absolute;width:0px;height:0px;bottom:0px;left:0px;', //style attributes to add to the iframe element
"classNameToAdd": '' //css class to add to the iframe element
}
};
$.fn["printElement"]["cssElement"] = {
"href": '',
"media": ''
};
function _printElement(element, opts) {
//Create markup to be printed
var html = _getMarkup(element, opts);
var popupOrIframe = null;
var documentToWriteTo = null;
if (opts["printMode"].toLowerCase() == 'popup') {
popupOrIframe = window.open('about:blank', 'printElementWindow', 'width=650,height=440,scrollbars=yes');
documentToWriteTo = popupOrIframe.document;
}
else {
//The random ID is to overcome a safari bug http://www.cjboco.com.sharedcopy.com/post.cfm/442dc92cd1c0ca10a5c35210b8166882.html
var printElementID = "printElement_" + (Math.round(Math.random() * 99999)).toString();
//Native creation of the element is faster..
var iframe = document.createElement('IFRAME');
$(iframe).attr({
style: opts["iframeElementOptions"]["styleToAdd"],
id: printElementID,
className: opts["iframeElementOptions"]["classNameToAdd"],
frameBorder: 0,
scrolling: 'no',
src: 'about:blank'
});
document.body.appendChild(iframe);
documentToWriteTo = (iframe.contentWindow || iframe.contentDocument);
if (documentToWriteTo.document)
documentToWriteTo = documentToWriteTo.document;
iframe = document.frames ? document.frames[printElementID] : document.getElementById(printElementID);
popupOrIframe = iframe.contentWindow || iframe;
}
focus();
documentToWriteTo.open();
documentToWriteTo.write(html);
documentToWriteTo.close();
_callPrint(popupOrIframe);
};
function _callPrint(element) {
if (element && element["printPage"])
element["printPage"]();
else
setTimeout(function () {
_callPrint(element);
}, 50);
}
function _getElementHTMLIncludingFormElements(element) {
var $element = $(element);
//Radiobuttons and checkboxes
$(":checked", $element).each(function () {
this.setAttribute('checked', 'checked');
});
//simple text inputs
$("input[type='text']", $element).each(function () {
this.setAttribute('value', $(this).val());
});
$("select", $element).each(function () {
var $select = $(this);
$("option", $select).each(function () {
if ($select.val() == $(this).val())
this.setAttribute('selected', 'selected');
});
});
$("textarea", $element).each(function () {
//Thanks http://blog.ekini.net/2009/02/24/jquery-getting-the-latest-textvalue-inside-a-textarea/
var value = $(this).attr('value');
//fix for issue 7 (http://plugins.jquery.com/node/13503 and http://github.com/erikzaadi/jQueryPlugins/issues#issue/7)
if ($.browser.mozilla && this.firstChild)
this.firstChild.textContent = value;
else
this.innerHTML = value;
});
//http://dbj.org/dbj/?p=91
var elementHtml = $('<div></div>').append($element.clone()).html();
return elementHtml;
}
function _getBaseHref() {
var port = (window.location.port) ? ':' + window.location.port : '';
return window.location.protocol + '//' + window.location.hostname + port + window.location.pathname;
}
function _getMarkup(element, opts) {
var $element = $(element);
var elementHtml = _getElementHTMLIncludingFormElements(element);
var html = new Array();
html.push('<html><head><title>' + opts["pageTitle"] + '</title>');
if (opts["overrideElementCSS"]) {
if (opts["overrideElementCSS"].length > 0) {
for (var x = 0; x < opts["overrideElementCSS"].length; x++) {
var current = opts["overrideElementCSS"][x];
if (typeof (current) == 'string')
html.push('<link type="text/css" rel="stylesheet" href="' + current + '" >');
else
html.push('<link type="text/css" rel="stylesheet" href="' + current["href"] + '" media="' + current["media"] + '" >');
}
}
}
else {
$("link", document).filter(function () {
return $(this).attr("rel").toLowerCase() == "stylesheet";
}).each(function () {
html.push('<link type="text/css" rel="stylesheet" href="' + $(this).attr("href") + '" media="' + $(this).attr('media') + '" >');
});
}
//Ensure that relative links work
html.push('<base href="' + _getBaseHref() + '" />');
html.push('</head><body style="' + opts["printBodyOptions"]["styleToAdd"] + '" class="' + opts["printBodyOptions"]["classNameToAdd"] + '">');
html.push('<div class="' + $element.attr('class') + '">' + elementHtml + '</div>');
html.push('<script type="text/javascript">function printPage(){focus();print();' + ((!$.browser.opera && !opts["leaveOpen"] && opts["printMode"].toLowerCase() == 'popup') ? 'close();' : '') + '}</script>');
html.push('</body></html>');
return html.join('');
};
})(window);
Is there any way to identify the close event and end it peacefully OR do not show the [x] option at the right top corner?
Hi i struggled with this for the past 3 days, and came to the conclusion of the following:
these lines:
if (mainOptions["printMode"] == 'iframe') {
if ($.browser.opera || (/chrome/.test(navigator.userAgent.toLowerCase())))
mainOptions["printMode"] = 'popup';
}
are obsoletes and they seems to cause issues in Chrome, it happens that by the time when this plugin was created, Chrome and Opera have issues when printing an iframe content.
As of today that's not longer an issue (and since Opera uses Webkit as Chrome, i must assume this also happens to work on Opera as well).
So for now removes those lines and you will notice that the print dialog will not have the blank window anymore, hence you should not have this problem.

Taglib array exception when setting Artist field

I keep getting an array out of bounds exception with Taglib.tag.Performers in this function that edits ID3 data. I read elsewhere that clearing tag.performers[] can help (if null) but I still get the error sometimes.
Error message:
"Index was outside the bounds of the array.Data:
'System.Collections.ListDictionaryInternal' for test.mp3"
var fileArr = Directory.GetFiles(BasePath, "*.*", SearchOption.AllDirectories).Where(s => s.EndsWith(".mp3") || s.EndsWith(".m4a")).ToArray();
foreach (var file in fileArr)
{
string fileName = Path.GetFileName(file);
string tagArtist = "";
string tagTitle = "";
string tempRegFilename = fileName;
string title = "";
//Apply to tag
TagLib.File mp3tag = TagLib.File.Create(file);
if (mp3tag.Tag.Title != null && mp3tag.Tag.Title.Length > 1)
{
title = mp3tag.Tag.Title;
}
else
{
mp3tag.Tag.Title = String.Empty;
}
if (mp3tag.Tag.Performers[0].Length < 1 || mp3tag.Tag.Performers[0] == null)
{
mp3tag.Tag.Performers[0] = null;
mp3tag.Tag.Performers = new[] { String.Empty };
mp3tag.Save();
}
if (mp3tag.Tag.Performers[0].Length > 1)
{
string[] performers = mp3tag.Tag.Performers;
if (title.Length > 2 && performers[0].Length > 1)
{
tagTitle = title;
tagArtist = performers[0].ToString();
Log.Info("ID3 Artist: " + "[" + tagArtist + "]");
Log.Info("ID3 Title: " + "[" + tagTitle + "]");
Log.Info("Tag data OK");
}
}
//Get artist from filename
if (mp3tag.Tag.Performers[0].Length < 1 || mp3tag.Tag.Performers == null)
{
mp3tag.Tag.Performers = new[] { String.Empty };
string prevArtist = String.Empty;
if (tempRegFilename.Contains("-"))
{
Log.Info("Artist data missing...");
string[] words = tempRegFilename.Split('-');
{
words[0] = words[0].Trim();
string perf = words[0];
mp3tag.Tag.Performers = new[] { perf };
Log.Info("Artists changed from \'" + prevArtist + "\' to " + "'" + perf + "'" + "\r\n");
mp3tag.Save();
}
}
mp3tag.Save();
}
}
catch (Exception ex)
{
Log.Error("TAG EXCEPTION: " + ex.Message + "Data: " + "'" + ex.Data + "'" + " for " + fileName + "\r\n" + ex.HelpLink);
}
Can anyone see what's wrong? I don't have much experience and could use the help. Thanks.
You seem to be assuming in a number of places that mp3Tag.Tag.Performers will have at least one element in it. If it doesn't, then you'll get the exception that you mention whenever you try to access mp3tag.Tag.Performers[0]
It looks like you may be trying to catch that possibility with this code:
if (mp3tag.Tag.Performers[0].Length < 1 || mp3tag.Tag.Performers[0] == null)
{
mp3tag.Tag.Performers[0] = null;
mp3tag.Tag.Performers = new[] { String.Empty };
mp3tag.Save();
}
But your logic is incorrect: you're getting the first element from the array (apparently a string) and checking its length, instead of checking the length of the array itself. Try this:
if (mp3tag.Tag.Performers.Length < 1 || mp3tag.Tag.Performers[0] == null)
{
mp3tag.Tag.Performers = new[] { String.Empty };
mp3tag.Save();
}
PS: It'll be much easier for you to see where your errors are if your log includes the stack trace of the exception, rather than just its message. I typically find it best to just use the ToString() on the exception itself.

Seeing if a ajax call returns true or false after a soapException

NOW SOLVED
Hi I am calling a c# web method via Ajax.
I want to handle a returned value of true and false in Ajax but I cannot seem to find a way of interrogating my returned data.
Sorry if this is a easy question, I am quite the novice.
My code is
$.ajax({
url: "Subscriptions.aspx/AddSub",
data: "{ 'strReportPath': '" + Path +
"' , strEmail: '" + $('#EmailAddress').val() +
"' , strDayofWeek: '" + daysSelected +
"' , strInterval: '" + intervalSelected +
"' , intTimeofDay: '" + timeofDay +
"' , strDayofMonth: '" + dayofMonth +
"'}",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data[0] == true) {
alert("Subscription added");
} else {
alert("There has been a error");
}
// Enable button again
$(".AddSub").removeAttr("disabled");
},
error: function (xhr, status, err) {
alert("Error adding subscription: " + err);
// Enable button again
$(".AddSub").removeAttr("disabled");
},
async: false
});
and the web method is
[WebMethod]
public static bool AddSub(string strReportPath, string strEmail, string strDayofWeek, string strInterval, int intTimeofDay, int strDayofMonth)
{
// Create webservice object
ReportService2005.ReportingService2005 rs = new ReportingService2005();
rs.Credentials = System.Net.CredentialCache.DefaultCredentials;
try
{
// Make sure their is a semi colon at the end of the email
if (strEmail.EndsWith(";"))
{
// Do nothing
}
else
{
strEmail = strEmail + ";";
}
string _reportName = strReportPath;
DateTime topDatetime = DateTime.Now;
ExtensionSettings extensionSettings = new ExtensionSettings();
List<ParameterValue> extParameters = new List<ParameterValue>();
List<ParameterValue> parameters = new List<ParameterValue>();
string description = "Email: " + strEmail;
string eventType = "TimedSubscription";
extensionSettings.Extension = "Report Server Email";
// If report is monthly default its run time to 7am
if (strInterval == "Monthly")
{
intTimeofDay = 7;
}
string scheduleXml = "<ScheduleDefinition><StartDateTime>" + topDatetime.ToString("yyyy-MM-dd") + "-" + (intTimeofDay-1) +":00" + "</StartDateTime>";
// Set up the timing of the report.
switch(strInterval)
{
case "Daily":
scheduleXml += "<WeeklyRecurrence>" +
"<WeeksInterval> 1 </WeeksInterval>" +
"<DaysOfWeek>" + "<Monday>true</Monday>" +
"<Tuesday>true</Tuesday>" +
"<Wednesday>true</Wednesday>" +
"<Thursday>true</Thursday>" +
"<Friday>true</Friday>" + "</DaysOfWeek>" +
"</WeeklyRecurrence>";
break;
case "Weekly":
scheduleXml += "<WeeklyRecurrence>" +
"<WeeksInterval> 1 </WeeksInterval>" +
"<DaysOfWeek>" + strDayofWeek + "</DaysOfWeek>" +
"</WeeklyRecurrence>";
break;
case "Monthly":
scheduleXml += "<MonthlyRecurrence>" +
"<Days>" + strDayofMonth + "</Days>" +
"<MonthsOfYear>" +
"<January>true</January>" +
"<February>true</February>" +
"<March>true</March>" +
"<April>true</April>" +
"<May>true</May>" +
"<June>true</June>" +
"<July>true</July>" +
"<August>true</August>" +
"<September>true</September>" +
"<October>true</October>" +
"<November>true</November>" +
"<December>true</December>" +
"</MonthsOfYear>" +
"</MonthlyRecurrence>";
break;
}
scheduleXml += "</ScheduleDefinition>";
extParameters.Add(new ParameterValue() { Name = "RenderFormat", Value = "EXCELOPENXML" });
extParameters.Add(new ParameterValue() { Name = "TO", Value = strEmail });
extParameters.Add(new ParameterValue() { Name = "IncludeReport", Value = "True" });
extParameters.Add(new ParameterValue() { Name = "Subject", Value = "subject - " + " (" + strReportPath + ")" });
extensionSettings.ParameterValues = extParameters.ToArray();
//Create the subscription
rs.CreateSubscription(_reportName, extensionSettings, description, eventType, scheduleXml, parameters.ToArray());
// Success
return true;
}
catch(SoapException e)
{
// Failure
return false;
}
}
Thank you
ANSWER
Ah solved it!!!
I now return the data as a string variable in the web method
//Create the subscription
rs.CreateSubscription(_reportName, extensionSettings, description, eventType, scheduleXml, parameters.ToArray());
string bob = "true";
// Success
return bob;
}
catch(SoapException e)
{
string bob = "false";
// Failure
return bob;
}
Then in ajax use the name followed by the .d suffix.
success: function (bob) {
if (bob.d == "true") {
alert("Subscription added");
} else {
alert("There has been a error");
}
Thanks stackoverflow

Categories

Resources