httpChannel.setRequestHeader with httpChannel.redirectTo - redirect

I'm having trouble with my Firefox-Addon.
With my extension, I'd like to redirect requests that match a certain pattern. So far, the redirection is working fine with
httpChannel.redirectTo()
Now I'd like to add / modify the request headers for the redirection (as explained here: https://developer.mozilla.org/en-US/docs/Setting_HTTP_request_headers )
My code so far:
console.log("start");
const {Cu,Ci} = require('chrome');
Cu.import('resource://gre/modules/Services.jsm');
var httpRequestObserver =
{
observe: function(subject, topic, data)
{
var httpChannel, requestURL;
if (topic == "http-on-modify-request") {
httpChannel = subject.QueryInterface(Ci.nsIHttpChannel);
requestURL = httpChannel.URI.spec;
if (requestURL.indexOf('www.3und80.de') > -1) {
console.log("match url");
newURL = 'http://www.genialschenken.de/';
/*This has no effect*/
httpChannel.setRequestHeader("X-Hello", "World", false);
console.log("redirecting...");
httpChannel.redirectTo(Services.io.newURI(newURL, null, null));
}
return;
}
}
};
Services.obs.addObserver(httpRequestObserver, "http-on-modify-request", false);
Sadly, the line
httpChannel.setRequestHeader("X-Hello", "World", false);
has no effect.
What am I doing wrong?
Thanks in advance!

From IRC:
00:58 Fallen noida: nsIChannelEventSink
00:58 Fallen and nsIInterfaceRequestor
00:59 Fallen I didn't read the link though
01:00 Fallen noida: http://mxr.mozilla.org/comm-central/source/calendar/providers/caldav/calDavCalendar.js#2828
#3und80 Let's research this more and develop an solution here.

Related

Google form that turns on and off each day automatically

I love Google Forms I can play with them for hours. I have spent days trying to solve this one, searching for an answer. It is very much over my head. I have seen similar questions but none that seemed to have helped me get to an answer. We have a café where I work and I created a pre-order form on Google Forms. That was the easy part. The Café can only accept pre-orders up to 10:30am. I want the form to open at 7am and close at 10:30am everyday to stop people pre ordering when the café isn't able to deal with their order. I used the very helpful tutorial from http://labnol.org/?p=20707 to start me off I have added and messed it up and managed to get back to the below which is currently how it looks. It doesn't work and I can't get my head around it. At one point I managed to turn it off but I couldn't turn it back on!! I'm finding it very frustrating and any help in solving this would be amazing. To me it seems very simple as it just needs to turn on and off at a certain time every day. I don't know! Please help me someone?
FORM_OPEN_DATE = "7:00";
FORM_CLOSE_DATE = "10:30";
RESPONSE_COUNT = "";
/* Initialize the form, setup time based triggers */
function Initialize() {
deleteTriggers_();
if ((FORM_OPEN_DATE !== "7:00") &&
((new Date()).getTime("7:00") < parseDate_(FORM_OPEN_DATE).getTime ("7:00"))) {
closeForm("10:30");
ScriptApp.newTrigger("openForm")
.timeBased("7:00")
.at(parseDate_(FORM_OPEN_DATE))
.create(); }
if (FORM_CLOSE_DATE !== "10:30") {
ScriptApp.newTrigger("closeForm")
.timeBased("10:30")
.at(parseDate_(FORM_CLOSE_DATE))
.create(); }
if (RESPONSE_COUNT !== "") {
ScriptApp.newTrigger("checkLimit")
.forForm(FormApp.getActiveForm())
.onFormSubmit()
.create(); } }
/* Delete all existing Script Triggers */
function deleteTriggers_() {
var triggers = ScriptApp.getProjectTriggers();
for (var i in triggers) {
ScriptApp.deleteTrigger(triggers[i]);
}
}
/* Allow Google Form to Accept Responses */
function openForm() {
var form = FormApp.getActiveForm();
form.setAcceptingResponses(true);
informUser_("Your Google Form is now accepting responses");
}
/* Close the Google Form, Stop Accepting Reponses */
function closeForm() {
var form = FormApp.getActiveForm();
form.setAcceptingResponses(false);
deleteTriggers_();
informUser_("Your Google Form is no longer accepting responses");
}
/* If Total # of Form Responses >= Limit, Close Form */
function checkLimit() {
if (FormApp.getActiveForm().getResponses().length >= RESPONSE_COUNT ) {
closeForm();
}
}
/* Parse the Date for creating Time-Based Triggers */
function parseDate_(d) {
return new Date(d.substr(0,4), d.substr(5,2)-1,
d.substr(8,2), d.substr(11,2), d.substr(14,2));
}
I don't think you can use .timebased('7:00'); And it is good to check that you don't have a trigger before you try creating a new one so I like to do this. You can only specify that you want a trigger at a certain hour like say 7. The trigger will be randomly selected somewhere between 7 and 8. So you really can't pick 10:30 either. It has to be either 10 or 11. If you want more precision you may have to trigger your daily triggers early and then count some 5 minute triggers to get you closer to the mark. You'll have to wait to see where the daily triggers are placed in the hour first. Once they're set they don't change.
I've actually played around with the daily timers in a log by creating new ones until I get one that close enough to my desired time and then I turn the others off and keep that one. You have to be patient. As long as you id the trigger by the function name in the log you can change the function and keep the timer going.
Oh and I generally created the log file with drive notepad and then open it up whenever I want to view the log.
function formsOnOff()
{
if(!isTrigger('openForm'))
{
ScriptApp.newTrigger('openForm').timeBased().atHour(7).create()
}
if(!isTrigger('closeForm'))
{
ScriptApp.newTrigger('closeForm').timeBased().atHour(11)
}
}
function isTrigger(funcName)
{
var r=false;
if(funcName)
{
var allTriggers=ScriptApp.getProjectTriggers();
var allHandlers=[];
for(var i=0;i<allTriggers.length;i++)
{
allHandlers.push(allTriggers[i].getHandlerFunction());
}
if(allHandlers.indexOf(funcName)>-1)
{
r=true;
}
}
return r;
}
I sometimes run a log entry on my timers so that I can figure out exactly when they're happening.
function logEntry(entry,file)
{
var file = (typeof(file) != 'undefined')?file:'eventlog.txt';
var entry = (typeof(entry) != 'undefined')?entry:'No entry string provided.';
if(entry)
{
var ts = Utilities.formatDate(new Date(), "GMT-6", "yyyy-MM-dd' 'hh:mm:ss a");
var s = ts + ' - ' + entry + '\n';
myUtilities.saveFile(s, file, true);//this is part of a library that I created. But any save file function will do as long as your appending.
}
}
This is my utilities save file function. You have to provide defaultfilename and datafolderid.
function saveFile(datstr,filename,append)
{
var append = (typeof(append) !== 'undefined')? append : false;
var filename = (typeof(filename) !== 'undefined')? filename : DefaultFileName;
var datstr = (typeof(datstr) !== 'undefined')? datstr : '';
var folderID = (typeof(folderID) !== 'undefined')? folderID : DataFolderID;
var fldr = DriveApp.getFolderById(folderID);
var file = fldr.getFilesByName(filename);
var targetFound = false;
while(file.hasNext())
{
var fi = file.next();
var target = fi.getName();
if(target == filename)
{
if(append)
{
datstr = fi.getBlob().getDataAsString() + datstr;
}
targetFound = true;
fi.setContent(datstr);
}
}
if(!targetFound)
{
var create = fldr.createFile(filename, datstr);
if(create)
{
targetFound = true;
}
}
return targetFound;
}

bing maps upgrading from v7 to v8 error with userMapView

I'm upgrading a project from using the bing maps v7 ajax api to using the v8 api. I've run into a problem where I'm getting back a message saying that "The waypoint you entered cannot be found." So I backed up and modified a sample screen to do what I'm doing and it works fine. So I've narrowed it down (with fiddler) to the REST calls that are made for each waypoint getting an error saying the userMapView is out of range in the first case but works fine in the second. I'm not really sure why this might be different in the sample code versus my actual app. Here are the two URLs. The first is the one that fails:
https://dev.virtualearth.net/REST/v1/Locations/?q=Cincinnati%2C%20OH&o=json&culture=en-US&jsonp=Microsoft.Maps.NetworkCallbacks.f5de44&key=MY_BING_MAPS_KEY&maxResults=5&userMapView=39.18820190429691,-180,39.18820190429691,-180&inclnb=0&incl=
https://dev.virtualearth.net/REST/v1/Locations/?q=cincinnati%2C%20oh&o=json&culture=en-US&jsonp=Microsoft.Maps.NetworkCallbacks.f66617&key=MY_BING_MAPS_KEY&maxResults=5&userMapView=39.02836016935031,-85.12275695800781,39.34768093312603,-85.12275695800781&inclnb=0&incl=
If I replace the userMapView parameter of the first URL with those of the second, the first URL works too. It seems obvious that the "-180" degree part is incorrect, but I don't know how it is getting there.
BTW, both of these URLs were generated using my dev key.
Thanks for any help!
EDIT:
Here's the bulk of the code that runs into trouble. Prior to this I've new'd the Map. This code is the callback from the loadModule of the Directions module. The code is a little convoluted beyond that though as I'm plugging in origins and destinations from the form. Also note, not that it makes much difference, that userAddress is passed into this function as true.
function createDrivingRoute(useAddress) {
directionsManager = new Microsoft.Maps.Directions.DirectionsManager(bmap);
locs = [];
var fromWayPoint;
fromWayPoint = new Microsoft.Maps.Directions.Waypoint({ address: fromAddressSearch });
locs.push(fromWayPoint);
directionsManager.addWaypoint(fromWayPoint);
if (toLocationArray != null) {
if (toLocationArray.length == 1) {
if (toLocationArray[0] == false) {
toLocationArray = [];
}
}
}
if (useAddress) {
if (toLocationArray != null) {
for (i = 0; i < toLocationArray.length; i++) {
//var toWayPointLoc = new Microsoft.Maps.Directions.Waypoint({ location: toLocationArray[i] });
var toWayPointLoc = new Microsoft.Maps.Directions.Waypoint({ address: toLocationArray[i] });
locs.push(toWayPointLoc);
directionsManager.addWaypoint(toWayPointLoc);
}
for (i = 0; i < toAddressArray.length; i++) {
var toWayPoint = new Microsoft.Maps.Directions.Waypoint({ address: toAddressArray[i] });
locs.push(toWayPoint);
directionsManager.addWaypoint(toWayPoint);
}
} else {
for (i = 0; i < toAddressArray.length; i++) {
var toWayPoint = new Microsoft.Maps.Directions.Waypoint({ address: toAddressArray[i] });
locs.push(toWayPoint);
directionsManager.addWaypoint(toWayPoint);
}
}
} else {
if (toLocationArray != null) {
for (i = 0; i < toLocationArray.length; i++) {
//var toWayPointLoc = new Microsoft.Maps.Directions.Waypoint({ location: toLocationArray[i] });
var toWayPointLoc = new Microsoft.Maps.Directions.Waypoint({ address: toLocationArray[i] });
locs.push(toWayPointLoc);
directionsManager.addWaypoint(toWayPointLoc);
}
}
for (i = 0; i < toAddressArray.length; i++) {
var toWayPoint = new Microsoft.Maps.Directions.Waypoint({ address: toAddressArray[i] });
locs.push(toWayPoint);
directionsManager.addWaypoint(toWayPoint);
}
}
if ($get("<%= chkReturnOrigin.ClientID %>").checked) {
var returnWayPoint = new Microsoft.Maps.Directions.Waypoint({ address: fromAddressSearch });
directionsManager.addWaypoint(fromWayPoint);
}
// Set the element in which the itinerary will be rendered
directionsManager.setRenderOptions({ itineraryContainer: '#directions' });
// Specify a handler for when the directions are calculated
if (directionsUpdatedEventObj) {
Microsoft.Maps.Events.removeHandler(directionsUpdatedEventObj);
directionsUpdatedEventObj = null;
}
directionsUpdatedEventObj = Microsoft.Maps.Events.addHandler(directionsManager, 'directionsUpdated', onDirectionsDisplayedEvent);
if (directionsErrorEventObj) {
Microsoft.Maps.Events.removeHandler(directionsErrorEventObj);
directionsErrorEventObj = null;
}
directionsErrorEventObj = Microsoft.Maps.Events.addHandler(directionsManager, 'directionsError', onDirectionsErrorEvent);
loadedRoute = null;
loadedSteps = [];
directionsManager.calculateDirections();
var destAddress = $get("<%= DestAddressList.ClientID %>").value;
if (destAddress == null || destAddress == "") {
document.getElementById("DistTotal").innerHTML = '';
}
}
Haven't seen this issue before, very odd. Take a look at your code, if you are using the Search module to do the geocoding, don't set the bounds option and see if it that corrects the issue. The bounds property is used to set the userMapView property of the REST request. If that works, then there is likely an issue with the LocationRect object being passed in, or how the search module uses it. I'll take a look into the source code to see if there is a bug that might be causing this.
Update 1: Now that I see your edit and see that you are using the directions manager I'm able to see that the userMapView is automatically added from the map. Not sure why it would be adding such incorrect values though. It looks like they are adding the same coordinate twice rather than adding the northwest and southeast coordinates. Will see if I can verify this by digging through the code.
Update 2: I've found the bug in the code. I have logged this with the development team so that they can resolve it the next time they touch the code for the search manager. The issue is that the west value is being added to the userMapView request twice, but not adding east value.
Update 3: Good news, this bug is now resolved in the experimental branch of Bing Maps. You can try this out by adding "&branch=experimental" to the map script URL. This will be added to the release branch in the next regular update planned for February.

amend all comments of all commits of a repository

I'm moving our on premise tfs repositories to visualstudio online. In the process I'd prefer to convert everything to git.
I found this (*) post online and everything works. But now I would like to use libgit2sharp to amend all the comments so to point to the correct work items.
I've cobbled together a bit of code that should do the trick:
Dictionary<string,string> links; //contains all links between new and old workitems, keys: old workitems, values: new workitems
using (var repo = new Repository(#"D:\gittfs\testproject"))
{
foreach (var commit in repo.Commits)
{
var commitMessage = commit.Message;
var regex = new Regex(#"#[0-9]*");
foreach (Match match in regex.Matches(commitMessage))
{
string newId;
if (links.TryGetValue(match.ToString(), out newId))
{
commitMessage = commitMessage.Replace(match.ToString(), newId);
}
}
var c = repo.Commit(commitMessage, new CommitOptions { AmendPreviousCommit = true });
}
}
This code runs without a problem and if I compare c.Message with commit.Message, I can see several of these being replaced. The problem is that after the program has ran, none of the amended commits are in the repository. So I think I'm still doing something wrong?
(*)https://www.microsoft.com/en-gb/developers/articles/week02mar2014/migrating-a-tfs-tfvc-based-team-project-to-a-git-team-project-retaining-as-much-source-and-work-item-history-as-possible/
I think you might rather be after some git filter-branch like feature.
LibGit2Sharp exposes this through the HistoryRewriter type.
You can peek at the FilterBranchFixture test suite for inspiration.
following code did the trick for me. thnx nulltoken!
var rewriteHistoryOptions = new RewriteHistoryOptions()
{
CommitHeaderRewriter = commit =>
{
var commitMessage = commit.Message;
bool stuffreplaced = false;
var r = new Regex(#"#[0-9]*\ ");
foreach (Match match in r.Matches(commit.Message))
{
string value;
if (links.TryGetValue(match.ToString().TrimEnd(), out value))
{
commitMessage = commitMessage.Replace(match.ToString().Trim(), value);
Console.WriteLine(commit.Id + ": " + match.ToString() + " replaced by " + value);
stuffreplaced = true;
counter++;
}
}
if (stuffreplaced)
{
return CommitRewriteInfo.From(commit, message: commitMessage);
}
else
{
return CommitRewriteInfo.From(commit);
}
}
};
repo.Refs.RewriteHistory(rewriteHistoryOptions, repo.Commits);

tinymce.dom.replace throws an exception concerning parentNode

I'm writing a tinyMce plugin which contains a section of code, replacing one element for another. I'm using the editor's dom instance to create the node I want to insert, and I'm using the same instance to do the replacement.
My code is as follows:
var nodeData =
{
"data-widgetId": data.widget.widgetKey(),
"data-instanceKey": "instance1",
src: "/content/images/icon48/cog.png",
class: "widgetPlaceholder",
title: data.widget.getInfo().name
};
var nodeToInsert = ed.dom.create("img", nodeData);
// Insert this content into the editor window
if (data.mode == 'add') {
tinymce.DOM.add(ed.getBody(), nodeToInsert);
}
else if (data.mode == 'edit' && data.selected != null) {
var instanceKey = $(data.selected).attr("data-instancekey");
var elementToReplace = tinymce.DOM.select("[data-instancekey=" + instanceKey + "]");
if (elementToReplace.length === 1) {
ed.dom.replace(elementToReplace[0], nodeToInsert);
}
else {
throw new "No element to replace with that instance key";
}
}
TinyMCE breaks during the replace, here:
replace : function(n, o, k) {
var t = this;
if (is(o, 'array'))
n = n.cloneNode(true);
return t.run(o, function(o) {
if (k) {
each(tinymce.grep(o.childNodes), function(c) {
n.appendChild(c);
});
}
return o.parentNode.replaceChild(n, o);
});
},
..with the error Cannot call method 'replaceChild' of null.
I've verified that the two argument's being passed into replace() are not null and that their parentNode fields are instantiated. I've also taken care to make sure that the elements are being created and replace using the same document instance (I understand I.E has an issue with this).
I've done all this development in Google Chrome, but I receive the same errors in Firefox 4 and IE8 also. Has anyone else come across this?
Thanks in advance
As it turns out, I was simply passing in the arguments in the wrong order. I should have been passing the node I wanted to insert first, and the node I wanted to replace second.

Unable to write to file with phonegap

Using the methods found on the phonegap api I'm trying to write to a file. This works in Android, but on an iOS device the writer is returning an error. Whenever I call writeFile() it returns an error, and the param passed into writeFail is -1. I cannot see why -1 is being passed into the error function, or why it's even failing to begin with. Has anyone else used the fileWriter on an iOS device, or can you see what I might be doing wrong?
function writeFile() {
var paths = navigator.fileMgr.getRootPaths();
var writer = new FileWriter(paths[0] + "write.txt");
writer.onwrite = writeSuccess;
writer.onerror = writeFail;
writer.write("some sample text");
// The file is now 'some sample text'
}
function writeSuccess() {
console.log("Write has succeeded");
}
function writeFail(evt) {
console.log(evt);
console.log(evt.target.error.code);
}
I had the same problem but I crawled through the mailing list and finally found the solution:
var writer = new FileWriter("write.txt");
This is it. Simply don't prepend the "Documents"-path. The documentation is wrong on that (still).
And don't forget to not use "readAsDataURL" as it would silently not work (on iOS). Hope I could help you.
If you want to write to a file this is the function(phonegap 2.5)
function fileWrite(filePath, text) {
var onFSWin = function(fileSystem) {
fileSystem.root.getFile(filePath, {create: true, exclusive: false}, onGetFileWin, onFSFail);
}
var onGetFileWin = function(fileEntry) {
fileEntry.createWriter(gotFileWriter, onFSFail);
}
var gotFileWriter = function(writer) {
writer.write(text);
}
var onFSFail = function(error) {
console.log(error.code);
}
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFSWin, onFSFail);
}