Java scripting in SharePoint custom lists - sharepoint-2007

In SharePoint lists, you are not permitted to upload files which have any kind of special characters in their file name. (For eg: file&.doc cannot be uploaded)
So I have a JavaScript code that validates the file name on submitting the list and creates a dialogue box that tells the user to rename the files before uploading and only then you can proceed.
My issue is, the code only works for 1 document, if more than 1 document is uploaded. it does not validate the second item. I need help so that I can upload n number of items and it validates eac
<Script type="text/javascript">
function PreSaveAction()
{
var attachment;
var filename="";
var fileNameSpecialCharacters = new RegExp("[~#%&*{}<>;?/+|\"]");
try {
attachment = document.getElementById("idAttachmentsTable").getElementsByTagName("span")[0].firstChild;
filename = attachment.data;
}
catch (e) {
}
if (fileNameSpecialCharacters.test(filename)) {
alert("Please remove the special characters like ~#%&*{}<>;?/+|\ from the file attachment name and reattach the file.");
return false;
}
else {
return true;
}
}
</script>

allow only certain files in 2007 sharepoint list
Edit: included code from comment:
<Script type="text/javascript">
function PreSaveAction()
{
var attachment;
var filename="";
try
{
attachment = document.getElementById("idAttachmentsTable")
.getElementsByTagName("span")[0]
.fi‌​rstChild;
filename = attachment.data;
}
catch (e) { }
if (!filename.match(/^(.+?\.xlsx?)$/i))
{
alert("Please attach only excel files.");
return false;
}
else
{
return true;
}
}
</script>

You cant loop through the list of documents? Put all the file names into a structure / Array / something and look at them all?

I created a modified version that will check for all attachments. The one liste here, only checks for the first attachment.
Here is mine
function chechAttachments() {
var spanTag;
var filename="";
var fileNameSpecialCharacters = new RegExp("[~#%&*{}<>;?/+|\"]");
try {
spanTag = document.getElementById("idAttachmentsTable").getElementsByTagName("span");
for (var i = 0; i < spanTag.length; i++) {
filename = spanTag[i].innerHTML;
}
}
catch (e) {
}
if (fileNameSpecialCharacters.test(filename)) {
alert('Attachments cannot contain special characters such as "[~#%&*{<>;?/+|\"]".\n\nPlease remove the special characters from the file attachment name.');
return false;
}
}

Related

Cordova: What is the right location to store recorded Audio files in iOS?

I am using media plugin to record sounds.
var my_media = new Media('test.wav');
my_media.startRecord();
my_media.stopRecord() // after few seconds
my_media.release();
my_media.play();//works fine
// But when I try to Check if test.wav file exist I always get false as status.
//File name of our important data file we didn't ship with the app
var fileName = "test.wav";
function init() {
console.log("Checking for data file.");
//Check for the file.
window.resolveLocalFileSystemURL(fileName, onSuccess, onFail);
}
function onSuccess() {
console.log("Great! This file exists");
}
function onFail() {
console.log('Sorry! File not Found');
}
// I always get this message: Sorry! File not Found
What is right way to do this? After recording I want user to be able to see list of available recorded sounds and user should be able to play it. For that I need to check if file exists or not.
So how should we implement that?
You can display list of recorded files as:
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem) {
fileSystem.root.getDirectory(YOUR_PATH, {
create: true
}, function(directory) {
root_path = fileSystem.root.toURL();
var directoryReader = directory.createReader();
directoryReader.readEntries(function(entries) {
var i;
for (i = 0; i < entries.length; i++) {
//Get file URL as: entries[i].toURL()); & display using creating dynamic tag.
}
}, function(error) {
alert(error.code);
});
});
}, function(error) {
alert("can't even get the file system: " + error.code);
});

Creating a hyperlink in active cell from uploaded file

I'm designing a shared Google Sheets for our team to keep track of each piece of content we produce. I want to implement a feature that allows people to upload a preview clip and have a hyperlink automatically created within the active cell.
My script so far serves up HTML as a user interface with a file upload and name entry. This part works fine and allows anyone to upload straight to Google Drive.
I've been having trouble getting it to automatically create a hyperlink in the active cell to the uploaded file. Been searching around, but haven't had a great deal of luck.
function onOpen() {
SpreadsheetApp.getUi()
.createMenu('File Upload')
.addItem('Open', 'openDialog')
.addToUi();
}
function openDialog() {
var html = HtmlService.createHtmlOutputFromFile('form.html')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
SpreadsheetApp.getUi()
.showModalDialog(html, 'Upload A File');
}
function uploadFiles(form) {
try {
var dropbox = "Clips";
var folder, folders = DriveApp.getFoldersByName(dropbox);
if (folders.hasNext()) {
folder = folders.next();
} else {
folder = DriveApp.createFolder(dropbox);
}
var blob = form.myFile;
var file = folder.createFile(blob);
file.setDescription("Uploaded by " + form.myName);
return "File uploaded successfully " + file.getUrl();
} catch (error) {
return error.toString();
}
}
My suggestion is to modify the return value from uploadFiles() to be an object, then use the URL to populate a spreadsheet HYPERLINK() formula.
return "File uploaded successfully " + file.getUrl();
Becomes:
return {
result: "File uploaded successfully",
fileURL: file.getUrl(),
fileDesc: file.getDescription() // Could be other values
};
Next, a function that sets the formula. This server-side function would be called with the values to be used in the formula, which were previously returned from uploadFiles(). I'm assuming this is from your client-side JavaScript, but that's just a guess, since you didn't include that in your question.
function setHyperlink( fileURL, fileDesc ) {
var formula = '=HYPERLINK("' + fileURL + '","' + fileDesc + '")';
SpreadsheetApp.getActiveCell()
.setFormula( formula );
return true;
}
I ended up solving this issue using the GAS Properties Service - creating 2 new User Properties to contain URL and Name data.
I also found a few issues with getActiveCell - it kept placing the link in A1. Although I had used Google's suggested method for returning the active cell, I was able to use the fix suggested here:
http://bit.ly/20Gc7l6
Here's my final script
function onOpen() {
SpreadsheetApp.getUi()
.createMenu('File Upload')
.addItem('Open', 'openDialog')
.addToUi();
}
function openDialog() {
var html = HtmlService.createHtmlOutputFromFile('form.html')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
SpreadsheetApp.getUi()
.showModalDialog(html, 'Upload A File');
}
function uploadFiles(form) {
try {
var dropbox = "Blacksand Clips";
var folder, folders = DriveApp.getFoldersByName(dropbox);
if (folders.hasNext()) {
folder = folders.next();
} else {
folder = DriveApp.createFolder(dropbox);
}
var blob = form.myFile;
var file = folder.createFile(blob);
file.setDescription(file.getDescription());
var userProperties = PropertiesService.getUserProperties();
var link = file.getUrl();
var name = file.getName();
userProperties.setProperty('link', link);
userProperties.setProperty('name', name);
setHyperlink();
return "File uploaded successfully ";
} catch (error) {
return error.toString();
}
}
function setHyperlink() {
var userProperties = PropertiesService.getUserProperties();
var link = userProperties.getProperty('link');
var displayName = userProperties.getProperty('name');
var value = 'hyperlink("' + link + '","' + displayName + '")'
var ss = SpreadsheetApp.getActiveSheet();
var cell = ss.getActiveCell().activate();
cell.setFormula( value )
return true;
}

List all indexeddb for one host in firefox addon

I figured if the devtool can list all created IndexedDB, then there should be an API to retrieve them...?
Dose anyone know how I get get a list of names with the help of a firefox SDK?
I did dig into the code and looked at the source. unfortunately there wasn't any convenient API that would pull out all the databases from one host.
The way they did it was to lurk around in the user profiles folder and look at all folder and files for .sqlite and make a sql query (multiple times in case there is an ongoing transaction) to each .sqlite and ask for the database name
it came down this peace of code
// striped down version of: https://dxr.mozilla.org/mozilla-central/source/devtools/server/actors/storage.js
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
const {async} = require("resource://gre/modules/devtools/async-utils");
const { setTimeout } = require("sdk/timers");
const promise = require("sdk/core/promise");
// A RegExp for characters that cannot appear in a file/directory name. This is
// used to sanitize the host name for indexed db to lookup whether the file is
// present in <profileDir>/storage/default/ location
const illegalFileNameCharacters = [
"[",
// Control characters \001 to \036
"\\x00-\\x24",
// Special characters
"/:*?\\\"<>|\\\\",
"]"
].join("");
const ILLEGAL_CHAR_REGEX = new RegExp(illegalFileNameCharacters, "g");
var OS = require("resource://gre/modules/osfile.jsm").OS;
var Sqlite = require("resource://gre/modules/Sqlite.jsm");
/**
* An async method equivalent to setTimeout but using Promises
*
* #param {number} time
* The wait time in milliseconds.
*/
function sleep(time) {
let deferred = promise.defer();
setTimeout(() => {
deferred.resolve(null);
}, time);
return deferred.promise;
}
var indexedDBHelpers = {
/**
* Fetches all the databases and their metadata for the given `host`.
*/
getDBNamesForHost: async(function*(host) {
let sanitizedHost = indexedDBHelpers.getSanitizedHost(host);
let directory = OS.Path.join(OS.Constants.Path.profileDir, "storage",
"default", sanitizedHost, "idb");
let exists = yield OS.File.exists(directory);
if (!exists && host.startsWith("about:")) {
// try for moz-safe-about directory
sanitizedHost = indexedDBHelpers.getSanitizedHost("moz-safe-" + host);
directory = OS.Path.join(OS.Constants.Path.profileDir, "storage",
"permanent", sanitizedHost, "idb");
exists = yield OS.File.exists(directory);
}
if (!exists) {
return [];
}
let names = [];
let dirIterator = new OS.File.DirectoryIterator(directory);
try {
yield dirIterator.forEach(file => {
// Skip directories.
if (file.isDir) {
return null;
}
// Skip any non-sqlite files.
if (!file.name.endsWith(".sqlite")) {
return null;
}
return indexedDBHelpers.getNameFromDatabaseFile(file.path).then(name => {
if (name) {
names.push(name);
}
return null;
});
});
} finally {
dirIterator.close();
}
return names;
}),
/**
* Removes any illegal characters from the host name to make it a valid file
* name.
*/
getSanitizedHost: function(host) {
return host.replace(ILLEGAL_CHAR_REGEX, "+");
},
/**
* Retrieves the proper indexed db database name from the provided .sqlite
* file location.
*/
getNameFromDatabaseFile: async(function*(path) {
let connection = null;
let retryCount = 0;
// Content pages might be having an open transaction for the same indexed db
// which this sqlite file belongs to. In that case, sqlite.openConnection
// will throw. Thus we retey for some time to see if lock is removed.
while (!connection && retryCount++ < 25) {
try {
connection = yield Sqlite.openConnection({ path: path });
} catch (ex) {
// Continuously retrying is overkill. Waiting for 100ms before next try
yield sleep(100);
}
}
if (!connection) {
return null;
}
let rows = yield connection.execute("SELECT name FROM database");
if (rows.length != 1) {
return null;
}
let name = rows[0].getResultByName("name");
yield connection.close();
return name;
})
};
module.exports = indexedDBHelpers.getDBNamesForHost;
If anyone want to use this then here is how you would use it
var getDBNamesForHost = require("./getDBNamesForHost");
getDBNamesForHost("http://example.com").then(names => {
console.log(names);
});
Think it would be cool if someone were to build a addon that adds indexedDB.mozGetDatabaseNames to work the same way as indexedDB.webkitGetDatabaseNames. I'm not doing that... will leave it up to you if you want. would be a grate dev tool to have ;)

Performing an AJAX call from JS in asp.net MVC without Jquery

I am developing an app that will be used on an old WInCE devices where IE Embedded doesn't support Jquery, which is why I can use it. So, my question is, what is the way to perform an AJAX call from within a js file.
Code:
html
#using (Html.BeginForm("", "SomeAction", FormMethod.Post, new { id = "myId" }))
{
input field 1: <input type="text" name="somename1"><br>
}
What I need to do is call a validate routine and return a string when the user clicks enter on the somename1 input field.
Normally, this would be done with Jquery, so how do I do it without only utilizing what the MVC asp has to offer (again, the ajax might not work at all on the old browser, but I would like to give it a shot and avoid refreshing the whole page).
Step 1: Get a XMLHttp Object using:
function getXMLHttpRequest() {
var xmlHttpReq = false;
// to create XMLHttpRequest object in non-Microsoft browsers
if (window.XMLHttpRequest) {
xmlHttpReq = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
xmlHttpReq = new ActiveXObject("Msxml2.XMLHTTP");
} catch (exp1) {
try {
// to create XMLHttpRequest object in older versions
// of Internet Explorer
xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
} catch (exp2) {
xmlHttpReq = false;
}
}
}
return xmlHttpReq;
}
Then do this (Just an example for downloading a file ajax request)
function myFunction(){
var xmlHttpRequest = getXMLHttpRequest();
xmlHttpRequest.onreadystatechange = getReadyStateHandler_download_file(xmlHttpRequest,file_indicator);
xmlHttpRequest.open("GET", "/wasa-app/DownloadServlet?pmuId="+pmuID+"&dlDate=" + formatted_date+"&check_flag=1"+"&file_indicator="+file_indicator, true);
xmlHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlHttpRequest.send(null);
}
function getReadyStateHandler_download_file(xmlHttpRequest, fileIndicator) {
return function() {
if (xmlHttpRequest.readyState == 4) {
if (xmlHttpRequest.status == 200) {
populateSchedule();
var resp = xmlHttpRequest.responseText;
if (resp == ""){
document.getElementById("save_" + fileIndicator).disabled = false;
document.getElementById("message").innerHTML = "";
}
else{
document.getElementById("save_" + fileIndicator).disabled = true;
document.getElementById("message").innerHTML = xmlHttpRequest.responseText;
}
} else {
alert("HTTP error -- " + xmlHttpRequest.status + ": " + xmlHttpRequest.statusText);
}
}
};

Firefox SDK: How to make trigger for certain domain

I need to catch requests on sites with URLs *.net and take some actions (stop request and put HTML code from disk, but this I can do). How do I catch these requests?
I tried to use progress listeners, but something is wrong:
const STATE_START = Ci.nsIWebProgressListener.STATE_START;
var myListener = {
QueryInterface: XPCOMUtils.generateQI(["nsIWebProgressListener",
"nsISupportsWeakReference"]),
onStateChange: function(aWebProgress, aRequest, aFlag, aStatus) {
if (aFlag & STATE_START) {
// actions
}
}
use nsIHTTPChannel and observer service. copy paste it. however .net can be included in resources like javascript things, if you want to test if its specfically a window you have to check for some load flags of LOAD_INITIAL_DOCUMENT_URI, also will want to chec
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;
var newRequestURL, i;
if (httpChannel.loadFlags & httpChannel.LOAD_INITIAL_DOCUMENT_URI) {
//ok continue because loadFlags is a document
} else {
//its not a document, probably a resource like a js file image or css or something, but maybe could be ajax call
return;
}
if (requestURL.indexOf('.net')) {
var goodies = loadContextGoodies(httpChannel);
if (goodies) {
httpChannel.cancel(Cr.NS_BINDING_ABORTED);
goodies.contentWindow.location = self.data.url('pages/test.html');
} else {
//dont do anything as there is no contentWindow associated with the httpChannel, liekly a google ad is loading or some ajax call or something, so this is not an error
}
}
return;
}
}
};
Services.obs.addObserver(httpRequestObserver, "http-on-modify-request", false);
//this function gets the contentWindow and other good stuff from loadContext of httpChannel
function loadContextGoodies(httpChannel) {
//httpChannel must be the subject of http-on-modify-request QI'ed to nsiHTTPChannel as is done on line 8 "httpChannel = subject.QueryInterface(Ci.nsIHttpChannel);"
//start loadContext stuff
var loadContext;
try {
var interfaceRequestor = httpChannel.notificationCallbacks.QueryInterface(Ci.nsIInterfaceRequestor);
//var DOMWindow = interfaceRequestor.getInterface(Components.interfaces.nsIDOMWindow); //not to be done anymore because: https://developer.mozilla.org/en-US/docs/Updating_extensions_for_Firefox_3.5#Getting_a_load_context_from_a_request //instead do the loadContext stuff below
try {
loadContext = interfaceRequestor.getInterface(Ci.nsILoadContext);
} catch (ex) {
try {
loadContext = subject.loadGroup.notificationCallbacks.getInterface(Ci.nsILoadContext);
} catch (ex2) {}
}
} catch (ex0) {}
if (!loadContext) {
//no load context so dont do anything although you can run this, which is your old code
//this probably means that its loading an ajax call or like a google ad thing
return null;
} else {
var contentWindow = loadContext.associatedWindow;
if (!contentWindow) {
//this channel does not have a window, its probably loading a resource
//this probably means that its loading an ajax call or like a google ad thing
return null;
} else {
var aDOMWindow = contentWindow.top.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIWebNavigation)
.QueryInterface(Ci.nsIDocShellTreeItem)
.rootTreeItem
.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIDOMWindow);
var gBrowser = aDOMWindow.gBrowser;
var aTab = gBrowser._getTabForContentWindow(contentWindow.top); //this is the clickable tab xul element, the one found in the tab strip of the firefox window, aTab.linkedBrowser is same as browser var above //can stylize tab like aTab.style.backgroundColor = 'blue'; //can stylize the tab like aTab.style.fontColor = 'red';
if (aTab == null) {
return null;
}
else {
var browser = aTab.linkedBrowser; //this is the browser within the tab //this is where the example in the previous section ends
return {
aDOMWindow: aDOMWindow,
gBrowser: gBrowser,
aTab: aTab,
browser: browser,
contentWindow: contentWindow
};
}
}
//end loadContext stuff
}

Resources