Group query to get specific order - c#

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";

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.

Display List into Console

I trying to display a List into Console
My List code:
var order = new List<Orders>();
order.Add(new Orders { Date = "" + orders[0].date_created, Name = ""+ orders[0].billing.first_name , Adress = ""+ orders[0].shipping.address_1 + " " + orders[0].shipping.address_2 });
order.Add(new Orders { Date = "" + orders[1].date_created, Name = "" + orders[1].billing.first_name, Adress = "" + orders[1].shipping.address_1 + " " + orders[1].shipping.address_2 });
order.Add(new Orders { Date = "" + orders[2].date_created, Name = "" + orders[2].billing.first_name, Adress = "" + orders[2].shipping.address_1 + " " + orders[2].shipping.address_2 });
order.Add(new Orders { Date = "" + orders[3].date_created, Name = "" + orders[3].billing.first_name, Adress = "" + orders[3].shipping.address_1 + " " + orders[3].shipping.address_2 });
order.Add(new Orders { Date = "" + orders[4].date_created, Name = "" + orders[4].billing.first_name, Adress = "" + orders[4].shipping.address_1 + " " + orders[4].shipping.address_2 });
return order;
I have tried to display it like this:
Debug.WriteLine(order.ToString());
and like this:
order.ForEach(i => Debug.WriteLine(i.ToString()));
But gives the warning:
Unreachable code
How I can display the list?
Using Linq, as in your second try is close to the actual printing, you just need to format the string properly instead of simply call ToString method:
order.ForEach(o => Debug.WriteLine("Date: " + o.Date + " Adress: " + o.Adress + "Name: " + o.Name));
And I know it is not the point of the question, but I suggest you to use a ForEach instruction to populate the list too, as it will add more flexibility to your code.
Try this one:
foreach (var item in order)
{
Debug.WriteLine(item.ToString());
}
Or if you have mulitple properties as mentioned above, you can try like this:
foreach (var item in order)
{
Debug.WriteLine("Date : {0}, Name : {1}, Adress : {2}",item.Date.ToString(), item.Name.ToString(), item.Adress.ToString());
}

How to get the DDLlist Selected Value in MVC C# Controller

My coding are as following.
I cannot get the selected value of AreaDetails_code dropdownlist selected value.
I got the null value only. Pls help me. Thanks in advance.
In my Create.cshtml
<div id="hsp-planner"></div>
<script type="text/javascript">
$('#butGenerate').click(`function generateTimeLine() {
$('#hsp-planner').html('');
var _location = $('#pAreaInfoId').val();
var _staff = $('#pStaff').val();
var _selVal = $('#AreaDetails_code').val();
$.ajax({
url: '#Url.Action("GetAjaxPlanner", "HourlyShiftPlanner")',
data: { location: _location, staff: _staff, selectval: _selVal },
//dataType: 'json',
success: function (data) {
$('#hsp-planner').html(data);
},
failure: function (response) {
alert(response);
}
});
});
});
`
</script>
In my Controller.cs
public string GetAjaxPlanner()
{
string locationId = Request.QueryString["location"];
string staffId = Request.QueryString["staff"];
string selectVal = Request.QueryString["selectval"];
//String str = (String)req.getParameter("AreaDetails_code");
if (locationId != null && locationId != "")
{
List<ShiftAllocation> saList = new ShiftAllocationRepository().FindByAreaInfoId(int.Parse(locationId));
if (saList.Count > 0)
{
string result = "";
result = "<table>";
result += "<tr>";
result += "<td>Time Period<br/>(From-To)</td>";
result += "<td>Duty Location</td>";
//result += "<td>Remark</td>";
result += "<td>Staff</td>";
result += "</tr>";
int i = 1;
foreach (ShiftAllocation sa in saList)
{
HourlyShiftPlanner objHsp = null;
string dutyLocation = "";
string remark = "";
if (staffId != null && staffId != "")
{
objHsp = new HourlyShiftPlannerRepository().FindStaff(int.Parse(staffId), int.Parse(locationId), sa.ShiftAllocationId);
}
if (objHsp != null)
{
dutyLocation = objHsp.DutyLocation;
remark = objHsp.Remark;
}
result += "<tr>";
result += "<td>" + sa.FromShift.ToString("HH:mm") + "-" + sa.ToShift.ToString("HH:mm") + "</td>";
result += "<td>" + this.GetLocDetailsListWithDDL(i) + "</td>";
result += "</tr>";
result += "<input type='hidden' name='hidSAId" + i + "' id='hid-sa-id" + i + "' value='" + sa.ShiftAllocationId + "'/>";
i++;
}
result += "</table>";
return result;
}
}
return null;
}
private string GetLocDetailsListWithDDL(int idx2)
{
List<AreaInfoDetails> _areaDetailsList = db.AreaInfosDetails.ToList();
if (_areaDetailsList.Count == 0) return "";
string result = "";
result = "<select name='AreaDetails_code" + idx2 + "' id='AreaDetails_code" + idx2 + "'>";
result += "<option value=>--Select item--</option>";
foreach (AreaInfoDetails _ad in _areaDetailsList)
{
result += "<option value='" + _ad.AreaInfoDetailsId + "'>" + _ad.AreaDetailsCode + " </>";
}
result += "</select>";
//result += "<input type=submit id=submit value=Submit </>";
return result;
}`
In your controller you have this line:
result = "<select name='AreaDetails_code" + idx2 + "' id='AreaDetails_code" + idx2 + "'>";
where idx2 is a variable int, when you're trying to obtain the value with jquery:
var _selVal = $('#AreaDetails_code').val();
you are not appending this idx2 value in the selector and thus jquery assigns the value of null because it can't find it.
If you delete this placeholder from your controller, then you'll end up with multiple elements with the same id...no bueno. You must find a better naming convention or somehow pass that value to your view/javascript so it can know which element to get the value of.
Hope that helps.

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

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

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.

Categories

Resources