Why does R# tell me, "Not all code paths return a value" in a click handler? - onclick

At the end of my submit button click handler, Resharper warns that, "Not all code paths return a value."
What value would it be expecting from an event handler?
In deference to full disclosure, this is that event handler:
$("#submit_button").click(function() {
// http://stackoverflow.com/questions/18192288/how-can-i-compare-date-time-values-using-the-jqueryui-datepicker-and-html5-time
var begD = $.datepicker.parseDate('mm/dd/yy', $('#BeginDate').val());
var endD = $.datepicker.parseDate('mm/dd/yy', $('#EndDate').val());
if (begD > endD) {
alert('Begin date must be before End date');
$('#BeginDate').focus();
return false;
}
else if (begD.toString() == endD.toString()) {
var dteString = begD.getFullYear() + "/" + (begD.getMonth() + 1) + "/" + begD.getDate();
var begT = new Date(dteString + " " + $('#BeginTime').val());
var endT = new Date(dteString + " " + $('#EndTime').val());
if (begT > endT) {
alert('Begin date must be before End date');
$('#BeginTime').focus();
return false;
}
}
$("#NumberOfResults").css("visibility", "visible");
$("#NumberOfResults").html("Please wait...");
EnableButton("submit_button", false);
// If all are selected, don't enumerate them; just set it at "All" (change of case shows that the logic did execute)
var deptsList = $('#depts').checkedBoxes();
if (deptsList.length < deptsArray.length) {
$('#deptHeader span').html(deptsList.join(", "));
}
else if (deptsList.length == deptsArray.length) {
$('#deptHeader span').html("All");
}
// " "
var sitesList = $('#sites').checkedBoxes();
$('#sitesHeader span').html(sitesList.join(", "));
if (sitesList.length < sitesArray.length) {
$('#sitesHeader span').html(sitesList.join(", "));
}
else if (sitesList.length == sitesArray.length) {
$('#sitesHeader span').html("All");
}
$('#hiddenDepts').val(deptsList);
$('#hiddenSites').val(sitesList);
var UPCs = $('#UPC').val();
if (UPCs == "All") {
$('#UPC').val("1"); // take everything (1 and greater)
}
var resultsText = jQuery.trim($("#spanNumberOfResults").text());
if (resultsText != "") {
$("#NumberOfResults").css("visibility", "visible");
if (resultsText == "0") {
$("#NumberOfResults").css("color", "red");
} else {
var href = '/#ConfigurationManager.AppSettings["ThisApp"]/CCRCriteria/LoadReport';
// report_parms (sic) is referenced from LoadReport
var report_parms = {
GUID: "#Model.GUID",
SerialNumber: "#Model.SerialNumber",
ReportName: "#Model.ReportName"
};
window.open(href, "report_window", "resizable=1, width=850, left=" + (screen.width / 2 - 425));
}
}
}); // end of submit button click

Resharper isn't aware of event handlers.
It sees that your function will sometimes return false and sometimes won't return anything, and it complains.
It doesn't realize that this pattern is perfectly fine for event handlers.

Ignore it. Click handlers "can" return a boolean value indicating whether to process the click normally (true) or ignore it (false).
Resharper sees any return in the function as a clue that it should always return something.

Related

Using Page Hits for Segmentation in Adobe CQ5

I am trying to set up personalised content in CQ5 using segmentation. When I use the out of the box "Page Hits" option it doesn't work. Is there some extra configuration I have to do to use Page Hits?
I've set up two segments applied to two teaser pages. For the first one I've used
number of page hits is less than 4.
For the second I've used number of page hist is greater than 3.
Note, the teasers show up when I use Referral Keywords to test so I think the rest of the configuration is correct.
Can anyone give some advice about how to get the Page Hits segmentations to work?
Just in case anyone else has this same problem, I solved it by using a session store and set a cookie on the users browser to record how many times they had been to a particular page. Using that, I was able to configure my segments and personalise areas of the page based on number of visits the user had made to that page.
Code for the session store:
//Create the session store
if (!CQ_Analytics.MyStore) {
CQ_Analytics.MyStore = new CQ_Analytics.PersistedSessionStore();
CQ_Analytics.MyStore.STOREKEY = "MYSTORE";
CQ_Analytics.MyStore.STORENAME = "myclientstore";
CQ_Analytics.MyStore.data={};
CQ_Analytics.MyStore.findPageName = function(){
var locationName = location.pathname;
var n = location.pathname.indexOf("html");
if(n !== -1){
locationName = locationName.split('.')[0];
}
return locationName.split("/").slice(-1);
}
CQ_Analytics.MyStore.title = CQ_Analytics.MyStore.findPageName() + "-pageviews";
CQ_Analytics.MyStore.loadData = function(pageViewed) {
CQ_Analytics.MyStore.data = {"pageviewed":pageViewed};
}
CQ_Analytics.MyStore.getCookie = function(cname) {
console.log("getting the cookie");
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0){
console.log("return value for cookie is " + c.substring(name.length,c.length) );
return c.substring(name.length,c.length);
}
}
return "";
}
CQ_Analytics.MyStore.setCookie = function(cname, cvalue, exdays) {
console.log("setting the cookie");
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
CQ_Analytics.MyStore.checkCookie = function() {
console.log("checking for cookie");
var pViewd = CQ_Analytics.MyStore.getCookie(CQ_Analytics.MyStore.title);
if (pViewd != "") {
console.log("cookie is found and Viewed is " + pViewd);
pViewd = parseInt(pViewd) + 1;
CQ_Analytics.MyStore.setCookie(CQ_Analytics.MyStore.title, pViewd, 365);
CQ_Analytics.MyStore.loadData(pViewd.toString());
} else {
if (pViewd === "" || pViewd === null) {
console.log("cookie not found");
CQ_Analytics.MyStore.setCookie(CQ_Analytics.MyStore.title, "1", 365);
CQ_Analytics.MyStore.loadData("1");
}
}
}
CQ_Analytics.MyStore.checkCookie();
}
//register the session store
if (CQ_Analytics.CCM){
CQ_Analytics.CCM.register(CQ_Analytics.MyStore)
}
The most useful documentation I found was this: https://docs.adobe.com/docs/en/cq/5-6-1/developing/client_context_detail.html#par_title_34

I want to block certain characters in javascript validation?

I want to block ][#{}'". But somehow I'm not able to put it in my code. What should I declare in place of val. Also when I put val = /^[0-9]+$/;. It blocks numbers when I put them alone. But when I concatenate a number with an alphabet, it gets accepted. For ex- abc123 gets accepted whereas 123 does not.
function Allvalidate()
{
var input;
var controlId = document.getElementById("<%=TextBox1.ClientID %>");
input = controlId.value;
var val = //????//
if (input == "")
{
alert("Please Enter a Value" + "\n");
return false;
}
else if (val.test(input))
{
alert("It does not accept these characters" + "\n");
return false;
}
else
{
return true;
}
}
</script>
$(document).keydown(function (e) {
if (e.which == [here you can write the key code of the characters that you want allow]) {
// TO DO Your Logic
}
});
Here I have used e.which and e.keycode because of browser compatibility [ firefox and IE may give the different code]
I hope this will work . .

Disable collision for certain event sources in fullcalendar

Hi I want to have an event source which allows overlaying(collision with) other event sources without resizing.
But the other event sources should still be using the normal collision detection and resizing?
Did somebody have the same problem?
Ok I found the solution:
First change the function segCollide(seg1, seg2) in fullcalendar to:
function segsCollide(seg1, seg2) {
if(seg1.allowCollision || seg2.allowCollision)
{
return false
}
else
{
return seg1.end > seg2.start && seg1.start < seg2.end;
}
}
And sliceSegs() to:
function sliceSegs(events, visEventEnds, start, end) {
var segs = [],
i, len=events.length, event,
eventStart, eventEnd,
segStart, segEnd,
isStart, isEnd;
for (i=0; i<len; i++) {
event = events[i];
allowCollision = event.source.allowCollision;
eventStart = event.start;
eventEnd = visEventEnds[i];
if (eventEnd > start && eventStart < end) {
if (eventStart < start) {
segStart = cloneDate(start);
isStart = false;
}else{
segStart = eventStart;
isStart = true;
}
if (eventEnd > end) {
segEnd = cloneDate(end);
isEnd = false;
}else{
segEnd = eventEnd;
isEnd = true;
}
segs.push({
event: event,
start: segStart,
end: segEnd,
allowCollision: allowCollision,
isStart: isStart,
isEnd: isEnd,
msLength: segEnd - segStart
});
}
}
return segs.sort(segCmp);
}

Show static non-clickable heading in AutoCompleteExtender list

I have an AutoCompleteExtender from the Ajax Control Toolkit. I need to have a heading in the dropdown list that shows how many items found, but it should not be selectable as an item.
I have tried this using jQuery, but even when I just add as a div, it is still selected as an item into the text box when I click on it:
function clientPopulated(sender, e) {
var completionList = $find("AutoCompleteEx").get_completionList();
var completionListNodes = completionList.childNodes;
for (i = 0; i < completionListNodes.length; i++) {
completionListNodes[i].title = completionListNodes[i]._value.split(':')[2];
}
var resultsHeader;
if(completionListNodes.length==1000)
resultsHeader = 'Max count of 1000 reached.<br/>Please refine your search.';
else if(completionListNodes.length>0)
resultsHeader = completionListNodes.length + ' hits.';
else
resultsHeader = msg_NoObjectsFound ;
jQuery(completionListNodes[0]).before('<div>' + resultsHeader + '</div>');
}
Add OnClientItemSelected and OnClientShowing events handlers and try script below:
function itemSelected(sender, args) {
if (args.get_value() == null) {
sender._element.value = "";
}
}
function clientShowing() {
var extender = $find("AutoCompleteEx");
var optionsCount = extender.get_completionSetCount();
var message = "";
if (optionsCount == 1000) {
message = 'Max count of 1000 reached.<br/>Please refine your search.';
}
else if (optionsCount > 0) {
message = optionsCount + " hits."
}
else {
message = "oops."
}
jQuery(extender.get_completionList()).prepend("<li style='background-color:#ccc !important;'>" + message + "</li>");
}
Added:
you even can do this without OnClientItemSelected handler:
function clientShowing() {
var extender = $find("AutoCompleteEx");
var oldSetText = extender._setText;
extender._setText = function (item) {
if (item.rel == "header") {
extender._element.value = "";
return;
}
oldSetText.call(extender, item);
};
var optionsCount = extender.get_completionSetCount();
var message = "";
if (optionsCount == 1000) {
message = 'Max count of 1000 reached.<br/>Please refine your search.';
}
else if (optionsCount > 0) {
message = optionsCount + " hits."
}
else {
message = "oops."
}
jQuery(extender.get_completionList()).prepend("<li rel='header' style='background-color:#ccc !important;'>" + message + "</li>");
}
We can give a better answer if you post the output html of your autocomplete control. Anyway if its a dropdown control;
jQuery(completionListNodes[0]).before('
<option value="-99" disabled="disabled">your message here</option>'
);
The answer by Yuriy helped me in solving it so I give him credit although his sollution needed some changes to work.
First of all, the clientShowing event (mapped by setting OnClientShowing = "clientShowing" in the AutoExtender control) is executed on initialization. Here we override the _setText method to make sure nothing happens when clicking on the header element. I have used the overriding idea from Yuriy's answer that really did the trick for me. I only changed to check on css class instead of a ref attribute value.
function clientShowing(sender, e) {
var extender = sender;
var oldSetText = extender._setText;
extender._setText = function (item) {
if (jQuery(item).hasClass('listHeader')) {
// Do nothing. The original version sets the item text to the search
// textbox here, but I just want to keep the current search text.
return;
}
// Call the original version of the _setText method
oldSetText.call(extender, item);
};
}
So then we need to add the header element to the top of the list. This has to be done in the clientPopulated event (mapped by setting OnClientPopulated = "clientPopulated" in the AutoExtender control). This event is executed each time the search results have been finished populated, so here we have the correct search count available.
function clientPopulated(sender, e) {
var extender = sender;
var completionList = extender.get_completionList();
var completionListCount = completionList.childNodes.length;
var maxCount = extender.get_completionSetCount();
var resultsHeader;
if(completionListCount == maxCount)
resultsHeader = 'Max count of ' + maxCount + ' reached.<br/>'
+ 'Please refine your search.';
else if(completionListCount > 0)
resultsHeader = completionListCount + ' hits.';
else
resultsHeader = 'No objects found';
jQuery(completionList).prepend(
'<li class="listHeader">' + resultsHeader + '</li>');
}
I have also created a new css class to display this properly. I have used !important to make sure this overrides the mousover style added from the AutoExtender control.
.listHeader
{
background-color : #fafffa !important;
color : #061069 !important;
cursor : default !important;
}

How to get ClientID of a TreeNode in a TreeView?

How to get ClientID of a TreeNode in a TreeView based on one of its rendered attributes,
for example, its title attribute (In my case it's unique)
,using either Server-Side or Client-Side code?
I go with this code, but it doesn't work, any suggestion?
// Retrieves TreeNode ClientID.
function GetTreeNodeID(nodeTitle)
{
var treeNodes = document.getElementById('tvMenu').childNodes;
var treeLinks;
for(var i=0 ; i<treeNodes.length ; i++)
{
treeLinks = treeNodes[i].getElementsByTagName('a');
for(var j=0 ; j<treeLinks.length ; j++)
{
if(nodeTitle == treeLinks[j].title && treeLinks[j].title != "");
{
alert("Par: " + nodeTitle);
alert("Title: " + treeLinks[j].title);
return treeLinks[j].id;
}
}
}
}
The above code that is mentioned with the question always returns the id of root node, any suggestion?
innerText or innerHtml or textContent ? Wich browser do you use ?
function GetTreeNodeID(nodeInnerText)
{
var tree = document.getElementById('tvMenu');
var treeLinks = tree.getElementsByTagName('A');
for(var element in treeLinks )
{
if((nodeInnerText == treeLinks[element].innerText) && (treeLinks[element].innerText != ""))
{
alert("Par: " + nodeInnerText);
alert("innerText: " + treeLinks[element].title);
return treeLinks[element].id;
}
}
}
Look here for a sample code.

Resources