cookie is always not set - javascript

I am using the following code to set cookie, however, when I use document.cookie in console, it doesn't print the key-value pair I passed via setItem(). Anybody know what is the matter?
var docCookies = {
getItem: function (sKey) {
return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
},
setItem: function (sProperties) {
var cookieString = "";
var sExpires = "";
for (var sKey in sProperties){
console.log("inside for");
if (sProperties.hasOwnProperty(sKey)) {
// alert("Key is " + k + ", value is" + target[k]);
console.log("inside if");
cookieString += encodeURIComponent(sKey) + "=" + encodeURIComponent(sProperties[sKey])+"; ";
}
}
console.log("outside for");
document.cookie = cookieString.substring(0,cookieString.length-2);
return true;
},
hasItem: function (sKey) {
return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
}
};
var expireDate = (new Date((new Date()).getTime() + (60*24*60*60*1000))).toUTCString();
var sProperties = [];
sProperties['_country'] = _country ;
sProperties['_language'] = _language ;
sProperties['_pageName'] = _pageName ;
sProperties['_products'] = _products ;
sProperties['_events'] = _events ;
sProperties['_server'] = _server ;
sProperties['_href'] = _href ;
sProperties['expires'] = expireDate ;
docCookies.setItem(sProperties);

the cookie you want to save should be an Object
var sProperties = {};

Related

If evaluation not working properly

I have an if statement that when I print the result in the console, I can see sometimes its true, and sometimes its false.
However, whats inside the IF, its never executed and the resulting array is always empty.
var createQuery = function(viewFields,clientCode) {
return '<View Scope="RecursiveAll">' + viewFields +
'<Query>' +
'<Where>' +
'<And>' +
'<Eq>' +
'<FieldRef Name="ClientCode" />' +
'<Value Type="Text">'+ clientCode + '</Value>' +
'</Eq>' +
'<Neq>' +
'<FieldRef Name="ContentType" />' +
'<Value Type="Computed">Bill Cycle</Value>' +
'</Neq>' +
'</And>' +
'</Where>' +
'</Query>' +
'</View>';
};
var createListItemValues = function(filter) {
return function(listItems,selectProperties) {
var listItemsWithValues = [];
if (listItems) {
var enumerator = listItems.getEnumerator();
while (enumerator.moveNext()) {
var listItem = enumerator.get_current();
var listItemValues = [];
selectProperties
.forEach(function (propertyName) {
var value = listItem.get_item(propertyName);
if (propertyName === "JobCodesMulti") {
jobvalue = "";
value.forEach(function (jobvalues) {
jobvalue += jobvalues.get_lookupValue() + ";";
})
listItemValues[propertyName] = jobvalue;
} else {
listItemValues[propertyName] = value;
}
});
if(filter(listItemValues)){//only push if filter returns true
listItemsWithValues.push(listItemValues);
}
}
}
return listItemsWithValues;
};
};
var processListItemWithValue = function(listItemsWithValues) {
return function(listItem) {
var fileDirRef = listItem["FileRef"];
var id = listItem["ID"];
var title = listItem["Title"];
var serverUrl = _spPageContextInfo.webAbsoluteUrl.replace(_spPageContextInfo.webServerRelativeUrl, "");
var dispFormUrl = serverUrl + "/sites/billing/_layouts/15/DocSetHome.aspx?id=" + fileDirRef;
var parentLink = listItem["FileRef"];
//!!!PLEASE NOTE: made arrayofstrings a local variable
var arrayofstrings = parentLink.split("/");
var billCycleFolderName = arrayofstrings[arrayofstrings.length - 2];
arrayofstrings.pop();
var hyperLink = '' + billCycleFolderName + '';
listItem["Bill Cycle"] = hyperLink;
listItemsWithValues["Document Type"] = getContentTypeOfCurrentItem(listItem.ID.toString());
}
};
function GetRelatedBillingDocumentsFromList(selectProperties, currentBillCyclePath, clientCode, jobCodes, engagementCode, enhanceFunctions) {
$log.info("Retrieving related billing documents for bill cycle with name [" + currentBillCyclePath + "]");
//pass filter function to createListItemValues to get a new function that
// creates filtered list item values
var createFilteredListItemsWithValues = createListItemValues(
function(listItemValues) {
var x1=listItemValues && typeof listItemValues.FileRef === "string" && listItemValues.FileRef.split("/")[4];
var x2= currentBillCyclePath.split("/")[8]
console.log(x1===x2);
return !(//pass filter function to createListItemValues
listItemValues &&
typeof listItemValues.FileRef === "string" &&
listItemValues.FileRef.split("/")[4]
) === currentBillCyclePath.split("/")[8];
}
);
var webUrl = _spPageContextInfo.webAbsoluteUrl;
selectProperties = selectProperties.concat("ContentTypeId");
var viewFields = spService.ConvertSelectPropertiesToViewFields(selectProperties);
// query must return the documents for the same client but in other bill cycles not the current one
var camlQuery = createQuery(viewFields,clientCode);
var billCyclesListId = "{c23bbae4-34f7-494c-8f67-acece3ba60da}";
//return a promise like here so the caller knows if something went wrong
return spService.GetListItems(billCyclesListId, camlQuery, selectProperties)
.then(
function(listItems){
console.log("currentBillCyclePath:",currentBillCyclePath);
var listItemsValues = createFilteredListItemsWithValues
(listItems,selectProperties);
return $q.all(listItemsValues.map(addContentType))
.then(function(){ return listItemsValues; })//finished asynchronously mutating array of listItems
}
).then(
function(listItemsWithValues) {
listItemsWithValues.forEach(processListItemWithValue(listItemsWithValues));
return $q.all(
spService.SpSearchQuery.EnhanceSearchResults(listItemsWithValues, enhanceFunctions)
)
}
)
}
the important lines are: var createFilteredListItemsWithValues and if(filter(listItemValues))
You filter function will always return false because you're checking if a String value equals a boolean value.
!(
listItemValues &&
typeof listItemValues.FileRef === "string" &&
listItemValues.FileRef.split("/")[4]
)
Is a boolean, while
currentBillCyclePath.split("/")[8];
is a string.

Multiple Group By using two look-up columns which have multi valued selection enabled on an SP 2013 list using JavaScript

So I'm working on SP 2013 and have a document library which has three Lookup columns viz : Business Unit, Axis Product and Policy form. What I'm trying to do is I have managed to group by the List items first by Business Unit column and then by the Axis Product Column. This works fine but recently I'm trying to show the count of the number of items inside a particular Axis Product. Which would be like - Axis Product : "Some Value" (Count).
I'm able to show this count with Business Unit, but not able to do this with Axis Product. So I tried querying the library with both Business Unit and Axis Product to get the count for Axis Product, I'm not sure about this approach and currently I'm getting an error message:
'collListItemAxisProduct' is undefined.
Any help would be appreciated as I've been stuck on this for a long time now. Here is my code below :
// JavaScript source code
$(function () {
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', oGroupBy.GetDataFromList);
});
function GroupBy()
{
this.clientContext = "";
this.SiteUrl = "/sites/insurance/products";
this.lookUpLIst = "AxisBusinessUnit";
this.AxisProductlookUpList = "AXIS Product";
this.lookUpItems = [];
this.lookUpColumnName = "Title";
this.AxisProductlookupItems = [];
this.AProducts = [];
this.index = 0;
this.secondindex = 0;
this.parentList = "AXIS Rules Library";
this.html = "<div id='accordion'><table cellspacing='35' width='100%'><tr><td width='8%'>Edit</td><td width='13%'>Name</td><td width='13%'>Modified</td><td width='13%'>Underwriting Comments</td><td width='13%'>Policy Form Applicability</td><td width='13%'>AXIS Product</td><td width='13%'>Business Unit</td></tr>";
}
function MultipleGroupBy()
{
this.AxProducts = [];
this.SecondaryGroupBy = [];
this.count = "";
this.BusinessUnit = "";
this.html = "";
}
function UI()
{
this.id = "";
this.name = "";
this.modified = "";
this.acturialComments = "";
this.underWritingComments = "";
this.policyFormApplicability = [];
this.axisProduct = [];
this.businessUnit = [];
this.itemcheck = "";
this.Count = 0;
this.header = "";
this.AxisProductCount = 0;
this.trID = "";
this.SecondaryID = "";
this.LandingUrl = "&Source=http%3A%2F%2Fecm%2Ddev%2Fsites%2FInsurance%2FProducts%2FAXIS%2520Rules%2520Library%2FForms%2FGroupBy%2Easpx";
}
var oUI = new UI();
var oGroupBy = new GroupBy();
var oMultipleGroupBy = new MultipleGroupBy();
GroupBy.prototype.GetDataFromList = function () {
oGroupBy.clientContext = new SP.ClientContext(oGroupBy.SiteUrl);
var oList = oGroupBy.clientContext.get_web().get_lists().getByTitle(oGroupBy.lookUpLIst);
var APList = oGroupBy.clientContext.get_web().get_lists().getByTitle(oGroupBy.AxisProductlookUpList);
var camlQuery = new SP.CamlQuery();
this.collListItem = oList.getItems(camlQuery);
var secondcamlQuery = new SP.CamlQuery();
this.secondListItem = APList.getItems(secondcamlQuery);
oGroupBy.clientContext.load(collListItem);
oGroupBy.clientContext.load(secondListItem);
oGroupBy.clientContext.executeQueryAsync(Function.createDelegate(this, oGroupBy.BindDataFromlookUpList), Function.createDelegate(this, oGroupBy.onError));
}
GroupBy.prototype.BindDataFromlookUpList = function (seneder,args) {
var listenumerator = collListItem.getEnumerator();
while (listenumerator.moveNext()) {
var currentitem = listenumerator.get_current();
oGroupBy.lookUpItems.push(currentitem.get_item(oGroupBy.lookUpColumnName));
}
oGroupBy.GetDataFromParent(oGroupBy.lookUpItems);
}
GroupBy.prototype.GetDataFromParent = function(lookUpItems)
{
var oList1 = oGroupBy.clientContext.get_web().get_lists().getByTitle(oGroupBy.parentList);
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml('<View><Query><Where><Eq><FieldRef Name=\'Business_x0020_Unit\'/>' +
'<Value Type=\'LookupMulti\'>' + oGroupBy.lookUpItems[oGroupBy.index] + '</Value></Eq></Where></Query></View>');
this.collListItem1 = oList1.getItems(camlQuery);
oGroupBy.clientContext.load(this.collListItem1, 'Include(ID, Business_x0020_Unit, Title, FileLeafRef, ModifiedDate, Policy_x0020_Form_x0020_Applicability, AXIS_x0020_Product, Underwriting_x0020_Comments)');
oGroupBy.clientContext.executeQueryAsync(Function.createDelegate(this, oGroupBy.CreateHTMLGroupBy), Function.createDelegate(this, oGroupBy.onError));
}
GroupBy.prototype.CreateHTMLGroupBy = function (sender,args)
{
var listenumerator = this.collListItem1.getEnumerator();
var axisproductlistenumarator = secondListItem.getEnumerator();
while (axisproductlistenumarator.moveNext()) {
var currentitem = axisproductlistenumarator.get_current(); oGroupBy.AxisProductlookupItems.push(currentitem.get_item(oGroupBy.lookUpColumnName));
}
oUI.Count = this.collListItem1.get_count();
if (oGroupBy.lookUpItems[oGroupBy.index] != undefined && oUI.Count > 0) {
oUI.trID = oGroupBy.lookUpItems[oGroupBy.index];
oMultipleGroupBy.BusinessUnit = oGroupBy.lookUpItems[oGroupBy.index];
oGroupBy.html = oGroupBy.html + "<table style='cursor:pointer' id='" + oUI.trID.replace(" ", "") + "' onclick='javascript:oUI.Slider(this.id)'><tr><td colspan='7'><h2 style='width:1100px;font-weight: bold;border-bottom:1px solid #888888;padding:5px;'>Business Unit : " + oGroupBy.lookUpItems[oGroupBy.index] + " " + "<span> (" + oUI.Count + ")</span></h2></td></tr></table>";
}
oUI.businessUnit.length = 0;
oMultipleGroupBy.SecondaryGroupBy.length = 0;
oMultipleGroupBy.SecondaryGroupBy.push(oUI.trID);
oMultipleGroupBy.html = "";
if (oUI.Count > 0) {
if (listenumerator != undefined) {
while (listenumerator.moveNext()) {
var currentitem = listenumerator.get_current();
if (currentitem != undefined) {
oUI.id = currentitem.get_item("ID");
oUI.name = currentitem.get_item("FileLeafRef");
oUI.modified = currentitem.get_item("ModifiedDate");
//oUI.policyFormApplicability = currentitem.get_item("Policy_x0020_Form_x0020_Applicability");
oUI.underWritingComments = currentitem.get_item("Underwriting_x0020_Comments");
//oUI.axisProduct = currentitem.get_item("AXIS_x0020_Product");
var lookupPolicyFormApplicability = currentitem.get_item("Policy_x0020_Form_x0020_Applicability");
var lookupField = currentitem.get_item("Business_x0020_Unit");
var lookupAxisProduct = currentitem.get_item("AXIS_x0020_Product");
oUI.businessUnit.length = 0;
for (var i = 0; i < lookupField.length; i++) { oUI.businessUnit.push(lookupField[i].get_lookupValue());
}
oUI.axisProduct.length = 0;
for (var m = 0; m < lookupAxisProduct.length; m++) { oUI.axisProduct.push(lookupAxisProduct[m].get_lookupValue());
}
oUI.policyFormApplicability.length = 0;
for (var a = 0; a < lookupPolicyFormApplicability.length; a++)
{
oUI.policyFormApplicability.push(lookupPolicyFormApplicability[a].get_lookupValue());
}
oGroupBy.CreateUI(oUI);
}
}
if (oGroupBy.lookUpItems[oGroupBy.index] != undefined && oUI.Count > 0) {
oGroupBy.html = oGroupBy.html + oMultipleGroupBy.html;
}
}
}
oGroupBy.index = oGroupBy.index + 1;
if (oGroupBy.index <= oGroupBy.lookUpItems.length) {
oGroupBy.GetDataFromParent(oGroupBy.lookUpItems);
}
if(oGroupBy.index == oGroupBy.lookUpItems.length + 1)
{
oGroupBy.html = oGroupBy.html + "</table></div>";
$("#contentBox").append(oGroupBy.html);
$(".hide,.sd-hide").hide();
}
}
UI.prototype.Slider = function (id) {
$("#MSOZoneCell_WebPartWPQ3").click();
//$(".hide").hide();
var elements = document.querySelectorAll('[data-show="' + id + '"]');
$(elements).slideToggle();
}
UI.prototype.SecondarySlider = function (id) {
var elements = document.querySelectorAll('[data-secondary="' + id + '"]');
$(elements).slideToggle();
}
GroupBy.prototype.CreateUI = function (oUI) {
var BusinessUnit = "";
var AxisProduct = "";
var Policyformapplicability = "";
var tempBUnit = "";
for (var i = 0; i < oUI.businessUnit.length; i++) {
BusinessUnit = BusinessUnit + oUI.businessUnit[i] + ",";
}
for (var m = 0; m < oUI.axisProduct.length; m++) {
AxisProduct = AxisProduct + oUI.axisProduct[m] + ",";
}
for (var a = 0; a < oUI.policyFormApplicability.length; a++) {
Policyformapplicability = Policyformapplicability + oUI.policyFormApplicability[a] + ",";
}
oGroupBy.clientContext = new SP.ClientContext(oGroupBy.SiteUrl);
var oList1SecondGroupBy = oGroupBy.clientContext.get_web().get_lists().getByTitle(oGroupBy.parentList);
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml('<View><Query><Where><And><Eq><FieldRef Name=\'Business_x0020_Unit\' /><Value Type=\'LookupMulti\'>' + oGroupBy.lookUpItems[oGroupBy.index] + '</Value></Eq>' +
'<Eq><FieldRef Name=\'AXIS_x0020_Product\' /><Value Type=\'LookupMulti\'>' + oGroupBy.AxisProductlookupItems[oGroupBy.secondindex] + '</Value></Eq></And></Where><OrderBy><FieldRef Name=\'Title\' Ascending=\'True\' /></OrderBy></Query><View>');
this.collListItemAxisProduct = oList1SecondGroupBy.getItems(camlQuery);
oGroupBy.clientContext.load(this.collListItemAxisProduct, 'Include(ID, Business_x0020_Unit, Title, FileLeafRef, ModifiedDate, Policy_x0020_Form_x0020_Applicability, AXIS_x0020_Product, Underwriting_x0020_Comments)');
if (collListItemAxisProduct != undefined) {
//oGroupBy.clientContext.load(collListItemAxisProduct);
var AxisProductlistenumerator = this.collListItemAxisProduct.getEnumerator();
if (AxisProductlistenumerator != undefined) {
oUI.AxisProductCount = this.collListItemAxisProduct.get_count();
oGroupBy.AProducts.length = 0;
if (AxisProduct != "") {
oGroupBy.AProducts = AxisProduct.split(',');
}
oGroupBy.AProducts.splice(oGroupBy.AProducts.length - 1, 1);
//alert(oGroupBy.AProducts.length);
var link = "/sites/Insurance/Products/AXIS%20Rules%20Library/Forms/EditForm.aspx?ID=" + oUI.id + oUI.LandingUrl;
var editicon = "/sites/insurance/products/_layouts/15/images/edititem.gif?rev=23";
for (var i = 0; i < oGroupBy.AProducts.length; i++) {
var SecondaryGBTableID = "";
if (oGroupBy.AProducts[i].replace(" ", "") != "") {
SecondaryGBTableID = oGroupBy.AProducts[i].replace(/\s/g, "") + oMultipleGroupBy.BusinessUnit.replace(/\s/g, "");
SecondaryGBTableID = SecondaryGBTableID.replace("&", "");
var isPresent = $.inArray(oGroupBy.AProducts[i].replace(/\s/g, ""), oMultipleGroupBy.SecondaryGroupBy);
}
oUI.SecondaryID = oUI.trID.replace("/\s/g", "") + oGroupBy.AProducts[i].replace("/\s/g", "");
if ((isPresent <= -1)) {
oMultipleGroupBy.html = oMultipleGroupBy.html + "<tr style='margin-left:10px;margin-bottom:1px solid grey;' cellspacing='36'><td ><h3 class='hide' onclick='javascript:oUI.SecondarySlider(this.id);' id='" + oUI.SecondaryID + "' data-show='" + oUI.trID.replace(" ", "") + "' style='cursor:pointer;width:100%;font-weight: bold;border-bottom:1px solid #888888;padding:5px;'>    -    AXIS Product : " + oGroupBy.AProducts[i] + " " + "<span> (" + oUI.AxisProductCount + ")</span></h3></td></tr>";
oMultipleGroupBy.html = oMultipleGroupBy.html + "<tr><td><table class='hide' data-show='" + oUI.trID.replace(" ", "") + "' width='100%' cellspacing='36' id='" + SecondaryGBTableID + "'><tr class='sd-hide' data-secondary='" + oUI.SecondaryID + "'><td width='8%'><a href='" + link + "'><img src='" + editicon + "'></a></td><td width='13%'><a href='/sites/Insurance/Products/AXIS%20Rules%20Library/" + oUI.name + "' target='_self'>" + oUI.name.replace(/\.[^/.]+$/, "") + "</a></td><td width='13%'>" + oUI.modified + "</td><td width='13%'>" + oUI.underWritingComments + "</td><td width='13%'>" + oUI.policyFormApplicability + "</td><td width='13%'>" + oUI.axisProduct + "</td><td width='13%'>" + oUI.businessUnit + "</td></tr></table></td></tr>";
}
else {
if ($("#" + SecondaryGBTableID).html() != undefined) {
$("#" + SecondaryGBTableID).append("<tr class='sd-hide' data-secondary='" + oUI.SecondaryID + "'><td width='8%'><a href='" + link + "'><img src='" + editicon + "'></a></td><td width='13%'><a href='/sites/Insurance/Products/AXIS%20Rules%20Library/" + oUI.name + "' target='_self'>" + oUI.name.replace(/\.[^/.]+$/, "") + "</a></td><td width='13%'>" + oUI.modified + "</td><td width='13%'>" + oUI.underWritingComments + "</td><td width='13%'>" + oUI.policyFormApplicability + "</td><td width='13%'>" + oUI.axisProduct + "</td><td width='13%'>" + oUI.businessUnit + "</td></tr>");
oMultipleGroupBy.html = $("#divMultiplegroupBy").html();
}
}
document.getElementById("divMultiplegroupBy").innerHTML = oMultipleGroupBy.html;
if ((isPresent <= -1) && (oGroupBy.AProducts[i] != "")) {
oMultipleGroupBy.SecondaryGroupBy.push(oGroupBy.AProducts[i].replace(/\s/g, ""));
}
}
}
}
else {
oGroupBy.secondindex = oGroupBy.secondindex + 1;
oGroupBy.CreateUI(oUI);
}
}
GroupBy.prototype.onError = function (sender, args) {
alert('Error: ' + args.get_message() + '\n');
}
// JavaScript source code
You have to call clientContext.executeQueryAsync after calling clientContext.load in order to populate any results from the SharePoint object model.
executeQueryAsync takes two parameters: first the function to execute on success, and second the function to execute if an error is encountered. Any code that depends on successfully loading values from the query should be placed in the on success function.

wpf webbrowser javascript callback

if have javascript:
function calculateValues(callback)
{
window.external.getHistoryRange(0,1,"",function(res){
var hist = eval(res);
histCount = hist.historyCount;
hist = hist.historyContent;
if (histCount == 0)
{
return;
}
$("#history_table").show();
var $row = addAlertHistoryRow(hist[0]);
var rowHeight = $row.height();
pageItemsCount = Math.floor(contentHeight / rowHeight);
curPageNum = 0;
$row.remove();
if (callback) callback();
});
}
in function calculateValues(callback) callback parameter is:
function(){statItempos = 0; gethistoryandshow(pageNum,startItemsPos,callback);}
and c# code, that works with that script (ObjectForScripting):
public string getHistoryRange(string strVar0 = "", string strVar1 = "", string strVar2 = "", string strVar3 = "")
{
string res = "";
using (DeskAlertsDbContext db = new DeskAlertsDbContext())
{
var alerts = db.HistoryAlerts.OrderBy(a => a.ReciveTime)
.Include(b => b.alert.WINDOW)
.ToList();
foreach (var alert in alerts)
{
res += ("{\"id\":" + System.Web.HttpUtility.JavaScriptStringEncode(alert.alert.Alert_id) +
",\"date\":\"" +
System.Web.HttpUtility.JavaScriptStringEncode(
alert.ReciveTime.ToString(CultureInfo.InvariantCulture)) + "\",\"alert\":\"" +
System.Web.HttpUtility.JavaScriptStringEncode(alert.alerttext) + "\",\"title\":\"" +
System.Web.HttpUtility.JavaScriptStringEncode(alert.alert.Title) + "\",\"acknow\":\"" +
System.Web.HttpUtility.JavaScriptStringEncode(alert.alert.Acknown) + "\",\"create\":\"" +
System.Web.HttpUtility.JavaScriptStringEncode(alert.alert.Create_date) + "\",\"class\":\"" +
"1" + "\",\"urgent\":\"" + System.Web.HttpUtility.JavaScriptStringEncode(alert.alert.Urgent) +
"\",\"unread\":\"" + Convert.ToInt32(alert.isclosed).ToString() + "\",\"position\":\"" +
System.Web.HttpUtility.JavaScriptStringEncode(alert.alert.Position) + "\",\"ticker\":\"" +
alert.alert.Ticker + "\",\"to_date\":\"" +
System.Web.HttpUtility.JavaScriptStringEncode(alert.alert.To_date) + "\"},");
}
res = res.TrimEnd(','); //trim right ","
res = "({\"historyCount\":" + alerts.Count.ToString() + ",\"historyContent\":[" + res + "]});";
Browserwindow.Wb.InvokeScript("eval", new object[] { strVar3 });
Browserwindow.Wb.InvokeScript("CallbackFunction", new object[] { res });
return res;
}
}
On string: "Browserwindow.Wb.InvokeScript("eval", new object[] { strVar3 });"
I try to call anonymous function from javascript and have an error.
Question is: how to make this logic. How to perform the JS function of the parameters a different function. And then continue JS. If i tryed to give name to function, and invoke it, function works, but global context(if (callback) callback();) becomes unavailible
Your callback function name is not correct.
Replace
Browserwindow.Wb.InvokeScript("CallbackFunction", new object[] { res });
With
Browserwindow.Wb.InvokeScript("calculateValues", new object[] { res });
Hmmm... Just maked my variable dynamic (not string), and all worked
public string getHistoryRange(string strVar0 = "", string strVar1 = "", string strVar2 = "", dynamic strVar3 = null)
{
string res = "";
using (DeskAlertsDbContext db = new DeskAlertsDbContext())
{
var alerts = db.HistoryAlerts.OrderBy(a => a.ReciveTime)
.Include(b => b.alert.WINDOW)
.ToList();
foreach (var alert in alerts)
{
res += ("{\"id\":" + System.Web.HttpUtility.JavaScriptStringEncode(alert.alert.Alert_id) +
",\"date\":\"" +
System.Web.HttpUtility.JavaScriptStringEncode(
alert.ReciveTime.ToString(CultureInfo.InvariantCulture)) + "\",\"alert\":\"" +
System.Web.HttpUtility.JavaScriptStringEncode(alert.alerttext) + "\",\"title\":\"" +
System.Web.HttpUtility.JavaScriptStringEncode(alert.alert.Title) + "\",\"acknow\":\"" +
System.Web.HttpUtility.JavaScriptStringEncode(alert.alert.Acknown) + "\",\"create\":\"" +
System.Web.HttpUtility.JavaScriptStringEncode(alert.alert.Create_date) + "\",\"class\":\"" +
"1" + "\",\"urgent\":\"" + System.Web.HttpUtility.JavaScriptStringEncode(alert.alert.Urgent) +
"\",\"unread\":\"" + Convert.ToInt32(alert.isclosed).ToString() + "\",\"position\":\"" +
System.Web.HttpUtility.JavaScriptStringEncode(alert.alert.Position) + "\",\"ticker\":\"" +
alert.alert.Ticker + "\",\"to_date\":\"" +
System.Web.HttpUtility.JavaScriptStringEncode(alert.alert.To_date) + "\"},");
}
res = res.TrimEnd(','); //trim right ","
res = "({\"historyCount\":" + alerts.Count.ToString() + ",\"historyContent\":[" + res + "]});";
dynamic variable = Browserwindow.Wb.InvokeScript("eval", new object[] { strVar3 });
variable(res);
return res;
}
}

Use node rework css in browser

I would like to be able to use reworkcss/css in the browser. I downloaded version 2.0.0 from github and installed the needed packages with nmp install. I have tried requireJS (which claims to be able to process the CommonJS Module Format), requiring index.js, but an error occurs regarding "exports" being undefined. I also attempted to condense it using browserify, but this is evidently not what it was intended for. Does anyone know what I should do? I can't use node.js for the project, but need the CSS module's abilities in the browser.
I ended up condensing it by hand. Here's the result, if anyone's interested. It seems to work pretty well. If there are any mistakes, please mention them in a comment so they can be fixed.
/**
* npm modules: reworkcss
* author: TJ Holowaychuk <tj#vision-media.ca>
* license: MIT
* url: https://github.com/reworkcss/css.git
*
* Package condensed for client-side use by Aaron Fjerstad, July 2014.
*/
//Compressed object
var Compressed = function (opts) {
this.options = opts || {};
//Emit 'str'
this.emit = function(str) {
return str;
};
//Visit 'node'
this.visit = function(node){
return this[node.type](node);
};
//Map visit over array of 'nodes', optionally using a 'delim'
this.mapVisit = function(nodes, delim){
var buf = '';
delim = delim || '';
for (var i = 0, length = nodes.length; i < length; i++) {
buf += this.visit(nodes[i]);
if (delim && i < length - 1) buf += this.emit(delim);
}
return buf;
};
//Compile 'node'
this.compile = function(node){
return node.stylesheet
.rules.map(this.visit, this)
.join('');
};
//Visit comment node.
this.comment = function(node){
return this.emit('', node.position);
};
//Visit import node.
this.import = function(node){
return this.emit('#import ' + node.import + ';', node.position);
};
//Visit media node.
this.media = function(node){
return this.emit('#media ' + node.media, node.position)
+ this.emit('{')
+ this.mapVisit(node.rules)
+ this.emit('}');
};
//Visit document node.
this.document = function(node){
var doc = '#' + (node.vendor || '') + 'document ' + node.document;
return this.emit(doc, node.position)
+ this.emit('{')
+ this.mapVisit(node.rules)
+ this.emit('}');
};
//Visit charset node.
this.charset = function(node){
return this.emit('#charset ' + node.charset + ';', node.position);
};
//Visit namespace node.
this.namespace = function(node){
return this.emit('#namespace ' + node.namespace + ';', node.position);
};
//Visit supports node.
this.supports = function(node){
return this.emit('#supports ' + node.supports, node.position)
+ this.emit('{')
+ this.mapVisit(node.rules)
+ this.emit('}');
};
//Visit keyframes node.
this.keyframes = function(node){
return this.emit('#'
+ (node.vendor || '')
+ 'keyframes '
+ node.name, node.position)
+ this.emit('{')
+ this.mapVisit(node.keyframes)
+ this.emit('}');
};
//Visit keyframe node.
this.keyframe = function(node){
var decls = node.declarations;
return this.emit(node.values.join(','), node.position)
+ this.emit('{')
+ this.mapVisit(decls)
+ this.emit('}');
};
//Visit page node.
this.page = function(node){
var sel = node.selectors.length
? node.selectors.join(', ')
: '';
return this.emit('#page ' + sel, node.position)
+ this.emit('{')
+ this.mapVisit(node.declarations)
+ this.emit('}');
};
//Visit font-face node.
this['font-face'] = function(node){
return this.emit('#font-face', node.position)
+ this.emit('{')
+ this.mapVisit(node.declarations)
+ this.emit('}');
};
//Visit host node.
this.host = function(node){
return this.emit('#host', node.position)
+ this.emit('{')
+ this.mapVisit(node.rules)
+ this.emit('}');
};
//Visit custom-media node.
this['custom-media'] = function(node){
return this.emit('#custom-media ' + node.name + ' ' + node.media + ';', node.position);
};
//Visit rule node.
this.rule = function(node){
var decls = node.declarations;
if (!decls.length) return '';
return this.emit(node.selectors.join(','), node.position)
+ this.emit('{')
+ this.mapVisit(decls)
+ this.emit('}');
};
//Visit declaration node.
this.declaration = function(node){
return this.emit(node.property + ':' + node.value, node.position) + this.emit(';');
};
};
//Identity object
var Identity = function (opts) {
this.options = opts || {};
//Emit 'str'
this.emit = function(str) {
return str;
};
//Visit 'node'
this.visit = function(node){
return this[node.type](node);
};
//Map visit over array of 'nodes', optionally using a 'delim'
this.mapVisit = function(nodes, delim){
var buf = '';
delim = delim || '';
for (var i = 0, length = nodes.length; i < length; i++) {
buf += this.visit(nodes[i]);
if (delim && i < length - 1) buf += this.emit(delim);
}
return buf;
};
//Compile 'node'.
this.compile = function(node){
return this.stylesheet(node);
};
//Visit stylesheet node.
this.stylesheet = function(node){
return this.mapVisit(node.stylesheet.rules, '\n\n');
};
//Visit comment node.
this.comment = function(node){
return this.emit(this.indent() + '/*' + node.comment + '*/', node.position);
};
//Visit import node.
this.import = function(node){
return this.emit('#import ' + node.import + ';', node.position);
};
//Visit media node.
this.media = function(node){
return this.emit('#media ' + node.media, node.position)
+ this.emit(
' {\n'
+ this.indent(1))
+ this.mapVisit(node.rules, '\n\n')
+ this.emit(
this.indent(-1)
+ '\n}');
};
//Visit document node.
this.document = function(node){
var doc = '#' + (node.vendor || '') + 'document ' + node.document;
return this.emit(doc, node.position)
+ this.emit(
' '
+ ' {\n'
+ this.indent(1))
+ this.mapVisit(node.rules, '\n\n')
+ this.emit(
this.indent(-1)
+ '\n}');
};
//Visit charset node.
this.charset = function(node){
return this.emit('#charset ' + node.charset + ';', node.position);
};
//Visit namespace node.
this.namespace = function(node){
return this.emit('#namespace ' + node.namespace + ';', node.position);
};
//Visit supports node.
this.supports = function(node){
return this.emit('#supports ' + node.supports, node.position)
+ this.emit(
' {\n'
+ this.indent(1))
+ this.mapVisit(node.rules, '\n\n')
+ this.emit(
this.indent(-1)
+ '\n}');
};
//Visit keyframes node.
this.keyframes = function(node){
return this.emit('#' + (node.vendor || '') + 'keyframes ' + node.name, node.position)
+ this.emit(
' {\n'
+ this.indent(1))
+ this.mapVisit(node.keyframes, '\n')
+ this.emit(
this.indent(-1)
+ '}');
};
//Visit keyframe node.
this.keyframe = function(node){
var decls = node.declarations;
return this.emit(this.indent())
+ this.emit(node.values.join(', '), node.position)
+ this.emit(
' {\n'
+ this.indent(1))
+ this.mapVisit(decls, '\n')
+ this.emit(
this.indent(-1)
+ '\n'
+ this.indent() + '}\n');
};
//Visit page node.
this.page = function(node){
var sel = node.selectors.length
? node.selectors.join(', ') + ' '
: '';
return this.emit('#page ' + sel, node.position)
+ this.emit('{\n')
+ this.emit(this.indent(1))
+ this.mapVisit(node.declarations, '\n')
+ this.emit(this.indent(-1))
+ this.emit('\n}');
};
//Visit font-face node.
this['font-face'] = function(node){
return this.emit('#font-face ', node.position)
+ this.emit('{\n')
+ this.emit(this.indent(1))
+ this.mapVisit(node.declarations, '\n')
+ this.emit(this.indent(-1))
+ this.emit('\n}');
};
//Visit host node.
this.host = function(node){
return this.emit('#host', node.position)
+ this.emit(
' {\n'
+ this.indent(1))
+ this.mapVisit(node.rules, '\n\n')
+ this.emit(
this.indent(-1)
+ '\n}');
};
//Visit custom-media node.
this['custom-media'] = function(node){
return this.emit('#custom-media ' + node.name + ' ' + node.media + ';', node.position);
};
//Visit rule node.
this.rule = function(node){
var indent = this.indent();
var decls = node.declarations;
if (!decls.length) return '';
return this.emit(node.selectors.map(function(s){ return indent + s }).join(',\n'), node.position)
+ this.emit(' {\n')
+ this.emit(this.indent(1))
+ this.mapVisit(decls, '\n')
+ this.emit(this.indent(-1))
+ this.emit('\n' + this.indent() + '}');
};
//Visit declaration node.
this.declaration = function(node){
return this.emit(this.indent())
+ this.emit(node.property + ': ' + node.value, node.position)
+ this.emit(';');
};
//Increase, decrease or return current indentation.
this.indent = function(level) {
this.level = this.level || 1;
if (null != level) {
this.level += level;
return '';
}
return Array(this.level).join(this.indentation || ' ');
};
};
//CSS object
var CSS = function () {
var commentre = /\/\*[^*]*\*+([^/*][^*]*\*+)*\//g
/**
* Trim `str`.
*/
var trim = function (str) {
return str ? str.replace(/^\s+|\s+$/g, '') : '';
}
//Adds non-enumerable parent node reference to each node.
var addParent = function (obj, parent) {
var isNode = obj && typeof obj.type === 'string';
var childParent = isNode ? obj : parent;
for (var k in obj) {
var value = obj[k];
if (Array.isArray(value)) {
value.forEach(function(v) { addParent(v, childParent); });
} else if (value && typeof value === 'object') {
addParent(value, childParent);
}
}
if (isNode) {
Object.defineProperty(obj, 'parent', {
configurable: true,
writable: true,
enumerable: false,
value: parent || null
});
}
return obj;
}
//CSS.parse()
this.parse = function(css, options){
options = options || {};
//Positional.
var lineno = 1;
var column = 1;
//Update lineno and column based on 'str'.
function updatePosition(str) {
var lines = str.match(/\n/g);
if (lines) lineno += lines.length;
var i = str.lastIndexOf('\n');
column = ~i ? str.length - i : column + str.length;
}
//Mark position and patch 'node.position'.
function position() {
var start = { line: lineno, column: column };
return function(node){
node.position = new Position(start);
whitespace();
return node;
};
}
//Store position information for a node
function Position(start) {
this.start = start;
this.end = { line: lineno, column: column };
this.source = options.source;
}
//Non-enumerable source string
Position.prototype.content = css;
//Error 'msg'.
function error(msg) {
if (options.silent === true) {
return false;
}
var err = new Error(msg + ' near line ' + lineno + ':' + column);
err.filename = options.source;
err.line = lineno;
err.column = column;
err.source = css;
throw err;
}
//Parse stylesheet.
function stylesheet() {
return {
type: 'stylesheet',
stylesheet: {
rules: rules()
}
};
}
//Opening brace.
function open() {
return match(/^{\s*/);
}
//Closing brace.
function close() {
return match(/^}/);
}
//Parse ruleset.
function rules() {
var node;
var rules = [];
whitespace();
comments(rules);
while (css.length && css.charAt(0) != '}' && (node = atrule() || rule())) {
if (node !== false) {
rules.push(node);
comments(rules);
}
}
return rules;
}
//Match 're' and return captures.
function match(re) {
var m = re.exec(css);
if (!m) return;
var str = m[0];
updatePosition(str);
css = css.slice(str.length);
return m;
}
//Parse whitespace.
function whitespace() {
match(/^\s*/);
}
//Parse comments.
function comments(rules) {
var c;
rules = rules || [];
while (c = comment()) {
if (c !== false) {
rules.push(c);
}
}
return rules;
}
//Parse comment.
function comment() {
var pos = position();
if ('/' != css.charAt(0) || '*' != css.charAt(1)) return;
var i = 2;
while ("" != css.charAt(i) && ('*' != css.charAt(i) || '/' != css.charAt(i + 1))) ++i;
i += 2;
if ("" === css.charAt(i-1)) {
return error('End of comment missing');
}
var str = css.slice(2, i - 2);
column += 2;
updatePosition(str);
css = css.slice(i);
column += 2;
return pos({
type: 'comment',
comment: str
});
}
//Parse selector.
function selector() {
var m = match(/^([^{]+)/);
if (!m) return;
/* #fix Remove all comments from selectors
* http://ostermiller.org/findcomment.html */
return trim(m[0])
.replace(/\/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*\/+/g, '')
.replace(/(?:"[^"]*"|'[^']*')/g, function(m) {
return m.replace(/,/g, '\u200C');
})
.split(/\s*(?![^(]*\)),\s*/)
.map(function(s) {
return s.replace(/\u200C/g, ',');
});
}
//Parse declaration.
function declaration() {
var pos = position();
// prop
var prop = match(/^(\*?[-#\/\*\\\w]+(\[[0-9a-z_-]+\])?)\s*/);
if (!prop) return;
prop = trim(prop[0]);
// :
if (!match(/^:\s*/)) return error("property missing ':'");
// val
var val = match(/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^\)]*?\)|[^};])+)/);
var ret = pos({
type: 'declaration',
property: prop.replace(commentre, ''),
value: val ? trim(val[0]).replace(commentre, '') : ''
});
// ;
match(/^[;\s]*/);
return ret;
}
//Parse declarations.
function declarations() {
var decls = [];
if (!open()) return error("missing '{'");
comments(decls);
// declarations
var decl;
while (decl = declaration()) {
if (decl !== false) {
decls.push(decl);
comments(decls);
}
}
if (!close()) return error("missing '}'");
return decls;
}
//Parse keyframe.
function keyframe() {
var m;
var vals = [];
var pos = position();
while (m = match(/^((\d+\.\d+|\.\d+|\d+)%?|[a-z]+)\s*/)) {
vals.push(m[1]);
match(/^,\s*/);
}
if (!vals.length) return;
return pos({
type: 'keyframe',
values: vals,
declarations: declarations()
});
}
//Parse keyframes.
function atkeyframes() {
var pos = position();
var m = match(/^#([-\w]+)?keyframes */);
if (!m) return;
var vendor = m[1];
// identifier
var m = match(/^([-\w]+)\s*/);
if (!m) return error("#keyframes missing name");
var name = m[1];
if (!open()) return error("#keyframes missing '{'");
var frame;
var frames = comments();
while (frame = keyframe()) {
frames.push(frame);
frames = frames.concat(comments());
}
if (!close()) return error("#keyframes missing '}'");
return pos({
type: 'keyframes',
name: name,
vendor: vendor,
keyframes: frames
});
}
//Parse supports.
function atsupports() {
var pos = position();
var m = match(/^#supports *([^{]+)/);
if (!m) return;
var supports = trim(m[1]);
if (!open()) return error("#supports missing '{'");
var style = comments().concat(rules());
if (!close()) return error("#supports missing '}'");
return pos({
type: 'supports',
supports: supports,
rules: style
});
}
//Parse host.
function athost() {
var pos = position();
var m = match(/^#host */);
if (!m) return;
if (!open()) return error("#host missing '{'");
var style = comments().concat(rules());
if (!close()) return error("#host missing '}'");
return pos({
type: 'host',
rules: style
});
}
//Parse media.
function atmedia() {
var pos = position();
var m = match(/^#media *([^{]+)/);
if (!m) return;
var media = trim(m[1]);
if (!open()) return error("#media missing '{'");
var style = comments().concat(rules());
if (!close()) return error("#media missing '}'");
return pos({
type: 'media',
media: media,
rules: style
});
}
//Parse custom-media.
function atcustommedia() {
var pos = position();
var m = match(/^#custom-media (--[^\s]+) *([^{;]+);/);
if (!m) return;
return pos({
type: 'custom-media',
name: trim(m[1]),
media: trim(m[2])
});
}
//Parse paged media.
function atpage() {
var pos = position();
var m = match(/^#page */);
if (!m) return;
var sel = selector() || [];
if (!open()) return error("#page missing '{'");
var decls = comments();
// declarations
var decl;
while (decl = declaration()) {
decls.push(decl);
decls = decls.concat(comments());
}
if (!close()) return error("#page missing '}'");
return pos({
type: 'page',
selectors: sel,
declarations: decls
});
}
//Parse document.
function atdocument() {
var pos = position();
var m = match(/^#([-\w]+)?document *([^{]+)/);
if (!m) return;
var vendor = trim(m[1]);
var doc = trim(m[2]);
if (!open()) return error("#document missing '{'");
var style = comments().concat(rules());
if (!close()) return error("#document missing '}'");
return pos({
type: 'document',
document: doc,
vendor: vendor,
rules: style
});
}
//Parse font-face.
function atfontface() {
var pos = position();
var m = match(/^#font-face */);
if (!m) return;
if (!open()) return error("#font-face missing '{'");
var decls = comments();
// declarations
var decl;
while (decl = declaration()) {
decls.push(decl);
decls = decls.concat(comments());
}
if (!close()) return error("#font-face missing '}'");
return pos({
type: 'font-face',
declarations: decls
});
}
//Parse import
var atimport = _compileAtrule('import');
//Parse charset
var atcharset = _compileAtrule('charset');
//Parse namespace
var atnamespace = _compileAtrule('namespace');
//Parse non-block at-rules
function _compileAtrule(name) {
var re = new RegExp('^#' + name + ' *([^;\\n]+);');
return function() {
var pos = position();
var m = match(re);
if (!m) return;
var ret = { type: name };
ret[name] = m[1].trim();
return pos(ret);
}
}
//Parse at rule.
function atrule() {
if (css[0] != '#') return;
return atkeyframes()
|| atmedia()
|| atcustommedia()
|| atsupports()
|| atimport()
|| atcharset()
|| atnamespace()
|| atdocument()
|| atpage()
|| athost()
|| atfontface();
}
//Parse rule.
function rule() {
var pos = position();
var sel = selector();
if (!sel) return error('selector missing');
comments();
return pos({
type: 'rule',
selectors: sel,
declarations: declarations()
});
}
return addParent(stylesheet());
};
//CSS.stringify()
this.stringify = function(node, options){
options = options || {};
var compiler = options.compress
? new Compressed(options)
: new Identity(options);
// source maps
if (options.sourcemap) {
var sourcemaps = require('./source-map-support');
sourcemaps(compiler);
var code = compiler.compile(node);
compiler.applySourceMaps();
return { code: code, map: compiler.map.toJSON() };
}
var code = compiler.compile(node);
return code;
};
};

Where is the bug in this cookie-clearing code?

Fiddle
Cookies.setCookie("x", "42");
var x = Cookies.getCookie("x");
alert("Meaning of life = " + x);
// BUG: This line does not in fact clear the cookie. Why?
Cookies.clearCookie("x");
x = Cookies.getCookie("x");
alert("Life should have no meaning : " + x);
And the Cookies code:
// This actually appears above, don't worry about undefined Cookies
Cookies = new function() {
var self = this;
self.getCookie = function(c_name, opt_domain) {
var i, name, value, cookies=document.cookie.split(";");
for (i=0; i < cookies.length; i++) {
name = cookies[i].substr(0, cookies[i].indexOf("="));
value = cookies[i].substr(cookies[i].indexOf("=")+1);
name = name.replace(/^\s+|\s+$/g,"");
if (name==c_name) {
if (opt_domain) {
if (!(value && value.indexOf(";domain=" + opt_domain) != -1)) {
continue;
}
}
return decodeURIComponent(value);
}
}
return null;
};
self.setCookie = function(c_name, value, opt_exdays, opt_domain) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + opt_exdays);
if (!opt_domain) {
opt_domain = document.domain;
}
var c_value = encodeURIComponent(value) + (opt_exdays? "; expires=" + exdate.toUTCString() : "") + ";path=/" + (opt_domain ? ";domain=" + opt_domain : "");
document.cookie=c_name + "=" + c_value;
};
self.clearCookie = function(c_name) {
// http://blogs.x2line.com/al/articles/316.aspx
var d = new Date(0).toUTCString();
document.cookie = c_name + "=deleted;expires=" + d + ";path=/";
};
};
I don't know for sure what the issue is with your code (it may be because you aren't setting at least the path), but according to this reference, an easier way of removing a cookie value is like this:
self.clearCookie = function(c_name) {
self.setCookie(c_name, "", -1);
}
It is because the domain is not specified.
If you change clearCookie to:
self.clearCookie = function(c_name) {
// http://blogs.x2line.com/al/articles/316.aspx
var d = new Date(0).toUTCString();
document.cookie = c_name + "=deleted;expires=" + d + ";path=/;domain=" + document.domain;
};
It clears the cookie (using document.domain).
Alternatively you can just call:
this.setCookie(c_name, "", -1);

Categories

Resources