Google script Type error when try to move files to folder - file

I'm trying to select multiple files depending on the mime type (JPG and Google Docs in this example) and move to specific folders for each type. So I tried the following:
function test() {
var srcfolderId = "abcdefghi";
var jpgFolderID=DriveApp.getFolderById(srcfolderId).createFolder("jpgfiles").getId();
var gdocFolderID=DriveApp.getFolderById(srcfolderId).createFolder("gdocfiles").getId();
var jpgfiles=DriveApp.getFolderById(srcfolderId).getFilesByType(MimeType.JPEG);
var gdocfiles=DriveApp.getFolderById(srcfolderId).getFilesByType(MimeType.GOOGLE_DOCS);
jpgfiles.moveTo(jpgFolderID);
gdocfiles.moveTo(gdocFolderID);
}
But this creates the error:
TypeError: jpgfiles.moveTo is not a function
What should I need to do to escape from this error? Should I use a different way to move multiple files to a specific folder?

Modification points:
The reason for your issue of TypeError: jpgfiles.moveTo is not a function is due to that the argument of moveTo is the folder object. In your script, the folder ID is used.
DriveApp.getFolderById(srcfolderId) can be declared as one variable.
getFilesByType returns FileIterator.
When these points are reflected in your script, it becomes as follows.
Modified script:
function test() {
var srcfolderId = "abcdefghi";
var folder = DriveApp.getFolderById(srcfolderId);
var jpgFolder = folder.createFolder("jpgfiles");
var gdocFolder = folder.createFolder("gdocfiles");
var jpgfiles = folder.getFilesByType(MimeType.JPEG);
while (jpgfiles.hasNext()) {
jpgfiles.next().moveTo(jpgFolder);
}
var gdocfiles = folder.getFilesByType(MimeType.GOOGLE_DOCS);
while (gdocfiles.hasNext()) {
gdocfiles.next().moveTo(gdocFolder);
}
}
References:
getFilesByType(mimeType)
moveTo(destination)

Try adding something like this:
while(jpgfiles.hasNext()) {
let file = jpgfiles.next();
file.mmoveTo()....

Related

Why would the ASP.NET MVC HttpFileCollection return an array of strings rather than a Collection of HttpPostedFile?

I have an AngularJS + ASP.NET MVC 5 application where I am attempting to implement single file uploading.
On the client side I have the following code:
api.uploadFileV2 = function (alias, file, fnSuccess, fnError) {
var formData = new FormData();
formData.append(file.name, file);
$http.post('/api/V2/Upload/' + alias, formData, {
transformRequest: angular.identity,
headers: { 'Content-Type': undefined }
}).success(function (data) {
if (fnSuccess)
fnSuccess(data);
}).error(function (data) {
if (fnError)
fnError(data);
});
}
The file parameter is passed in from a function invoked by a button click and when executing in Chrome and in Edge I can see that the file parameter is in fact a file object.
Back on the server side I have a route to a controller defined as follows:
config.Routes.MapHttpRoute(
name: "V2UploadApi",
routeTemplate: "api/V2/Upload/{alias}/{id}",
defaults: new { controller = "Upload", id = RouteParameter.Optional }
);
Back on the server side I have my UploadController in which I have the following method defined:
public JArray Upload(string Alias)
{
JArray results = new JArray();
try
{
HttpRequest r = HttpContext.Current.Request;
HttpFileCollection c = r.Files;
foreach (var item in r.Files)
{
string theType = item.GetType().Name;
}
}
...
}
NOTE: The reason for the odd method signature with the Alias parameter is that ultimately the uploaded file will be managed by a Powershell script the selection and security level of which depends on the alias value.
Upon execution of the UploadController.Upload method I see the Alias value I'm expecting.
I do not see my file object. So var item does not resolve to the type HttpPostedFile as I expect but instead it resolves to a string type and so the variable "theType" contains "string" and not "HttpPostedFile". The HttpFileCollection doesn't actually contain a collection of HttpPostedFile objects and attempting cast the items in the collection results to the type HttpPostedFile results in an exception being thrown.
What could be causing this bizarre behavior on the server side and what can I do o correct it?
Something as basic as uploading a file should not be this difficult so I must be missing something obvious - trouble is I'm not seeing it.
So after another debugging session I altered the code to:
HttpRequest r = HttpContext.Current.Request;
HttpFileCollection c = r.Files;
foreach (string key in r.Files.Keys)
{
var item = r.Files[key];
string theType = item.GetType().Name;
}
This code not only works but also appeals to my old fashioned coding style of NOT lazily leaving absolutely everything up to the compiler using var. I wrongly assumed the enumerator of the HttpFileCollection to return (string)Key/(HttpPostedFile)Value pairs but I was wrong.

Move, Remove, and Replace information from Google Sheets with new entries using Google Script

I have created a Google Form that logs Timestamps, a numerical value, and an image file from its respondents to a Google Sheet. The image files are saved to an "imageFolder", but when I get too many responses, my imageFolder and Google Sheet get too large. Ideally, I want my imageFolder and its Google Sheet to stay below 50 entries.
I want to move the 10 oldest images in imageFolder to waitFolder. I want to save an array of those oldest values from column "How many?" before the entry is deleted. Then I want any new entries to replace the oldest ones who's information I have already save to waitFolder and the howMany() array (myArray10).
I know I have to move 10 images from "imageFolder" to "waitFolder" using functions along the lines of:
var text1 = "Response Form";
var text2 = "imageFolder";
var text3 = "Copy of imageFolder";
var text4 = "Wait Folder"
function moveFiles(sourceFileId, targetFolderId) {
var myFolder = DriveApp;
var files = myFolder.getFileById(sourceFileId).getFiles()
while (files.hasNext()) {
var file = files.next());
var dest = myFolder.getFolderById(targetFolderId);
dest.addFile(file);
var pull = DriveApp.getFolderById(sourceFolderId);
pull.removeFile(file);
}
}
function getMyId(text) {
var Ids = [];
var myFolder = DriveApp;
var folderIter = myFolder.getFoldersByName(text);
var folder = folderIter.next();
var folderIter = folder.getFiles();
while(folderIter.hasNext()) {
var file = folderIter.next();
var fileId = file.getId();
Ids.push(fileId);
}
return Ids
}
function getMyId10(text) {
var Ids = [];
var myFolder = DriveApp;
var folderIter = myFolder.getFoldersByName(text);
var folder = folderIter.next();
var folderIter = folder.getFiles();
for (var i = 0; i < 10; i++) { //Take the first 10
while(folderIter.hasNext()) {
var file = folderIter.next();
var fileId = file.getId();
Ids.push(fileId);
}
}
return Ids
}
function main() {
var imageFolderId = getMyId(text2);
var imageFolderId10 = getMyId10(text2);
var waitFolderId = getMyId(text4);
var Copy_imageFolderId = getMyId(text3);
moveFiles(imageFolderId, Copy_imageFolderId); //make a copy of imageFolder
moveFiles(imageFolderId10, waitFolderId); //Move first 10, remove from original
}
How can I move images from imageFolder to Copy_imageFolder?
How can I move the 10 oldest images from imageFolder to waitFolder?
How can I remove the 10 oldest images from imageFolder?
How can I limit the number of rows in my spreadsheet using Google script?
How can I overwrite my oldest rows with new entries/rows?
edit1: I am getting unexpected tokens in every function, and I am unsure why? It seems to pop up in the while loop of my function getMyId().
edit2: I see now why I was getting unexpected tokens. It seems that I was being irresponsible with my loops. I have replaced my 'while's with 'for's to amend this mistake.
edit3: I removed some unnecessary snippets of code to make it easier to follow.
edit4: Here is what my Form Response looks like in my Spreadsheet. The images are saved to subfolder imageFolder. But I can't grab the 10 array elements I want from the spreadsheet using howMany(). I also can't seem to move any of the files anywhere. When I call on moveFiles(), I get an unexpected error as soon as it asks for my DriveApp. How do I make my moveFiles() move my images from source to target folders?
Perhaps this is what you were looking for:
function moveFiles(sourceFolderId, targetFolderId) {
var srcFolder=DriveApp.getFolderById(sourceFolderId);
var desFolder=DriveApp.getFolderById(targetFolderId);
var files=srcFolder.getFiles();
while(files.hasNext()) {
var file=files.next();
desFolder.addFile(file);
srcFolder.removeFile(file)
}
}

how to change filename of exported SSRS report

I have created SSRS report and want to change the name of file with adding Date to it. I really appreciate your help.
Already tried https://reportsyouneed.com/ssrs-adding-date-to-exported-filenames/ solution and it doesn't work.
An easy alternative might be
An alternative approach to creating unique files for every delivery is to include a timestamp in the file name. To do this, add the #timestamp variable to the file name (for example, CompanySales#timestamp). With this approach, the file name is unique by definition, so it will never be overwritten.
See https://learn.microsoft.com/en-us/sql/reporting-services/subscriptions/file-share-delivery-in-reporting-services?view=sql-server-ver15
I got a perfect solution for this Issue.
This link works (very well) only if there is no parameter required before export.
Code in this link try to get the file name when you click on the file, means when download not ready and report looking for initial inputs.
But my file has date parameters in the beginning to input.
So I modify the code to wait till download is available and added to the end of "C:\Program Files\Microsoft SQL Server\MSRS10_50.MSSQLSERVER\Reporting Services\ReportManager\js\ReportingServices.js" file
function ModifyExportFileName(){
var rv=null;
var r= null;
var today =new Date();
var day= ("0" + today.getDate()).slice(-2);
var month = ("0"+ (today.getMonth() + 1)).slice(-2);
var year = ("0"+ today.getFullYear()).slice(-2);
var text= "DD";
try{
rv=this.$find("ctl31");
r=rv._getInternalViewer();
var url=r.ExportUrlBase;
var i = url.indexOf("FileName=");
}
catch(err)
{
//console.log(err);
setTimeout(ModifyExportFileName,2000);
return;
}
if(r==null)
{
setTimeout(ModifyExportFileName,2000);
return;
}
else
{
var url=r.ExportUrlBase;
var i = url.indexOf("FileName=");
var j = url.indexOf("&",i+1);
var oldFileName= url.substring(i+9,j);
var filename=text.concat(year,month,day)
r.ExportUrlBase= url.substring(0,i) + 'FileName=' + filename+ url.substring(j);
}
//console.log(filename);
setTimeout(ModifyExportFileName,2000);
}
ModifyExportFileName();
I need date as a filename so date is added as "filename". you can change it as required

sort files by datecreated and remove old files with google apps script

Trying to make a simple google apps script to get files by name and order them by date created. If there are more than 5 files by the same name, delete all but the 5 newest files.
function tryme(){
var files = DriveApp.getFilesByName('thisFile');
var created = files.getDateCreated();
for(i in created) {
if(created[i] > 4){
file.setTrashed(true);}
}
}
You're trying to use a File method on a File Iterator (returns from getFilesByName() method).
Here is a solution for your issue:
function tryme(){
// Get the file Iterator
var files = DriveApp.getFilesByName('New Text File');
var fileArray = [];
// Put file on array
while(files.hasNext()){
var file = files.next();
fileArray.push([file, file.getDateCreated()]);
}
//While you have more than 5 files
while(fileArray.length>5){
var older = ["",new Date()];
var olderIndex;
// Get the older file
for(var i in fileArray){
if(fileArray[i][1].getTime() < new Date(older[1]).getTime()){
olderIndex = i;
older = fileArray[i];
}
}
// Delete the older file
fileArray.splice(olderIndex,1);
older[0].setTrashed(true);
}
}
Edit: I made a mistake by using DriveApp.removeFile() instead of File.setTrashed(true)

Get Active Directory Object Description Value

I'm trying to get the "Description" attribute of a user object in our domain but it's resulting to a blank value even if it has a value in Active Directory Users and Computers.
I'm using the following code. I can't remember where I got it though. I modified it to quickly call it in other functions.
function Getattrib(srchattrib, user, resattrib)
{
var srchou = "OU=TheUsers,DC=MainDom,DC=net";
var conn = new ActiveXObject("ADODB.Connection");
conn.Open("Provider=ADsDSOObject");
var rs = conn.Execute("<LDAP://"+srchou+">;("+srchattrib+"="+user+");"+resattrib+"");
var i;
if (!rs.EOF)
{
rs.MoveFirst();
while(!rs.EOF)
{
return rs.Fields.Item(resattrib);
rs.MoveNext();
}
}
}
It works perfectly when I do this:
TexBox1.value = Getattrib('cn', 'James Sullivan', 'displayName');
But when I use:
TexBox1.value = Getattrib('cn', 'James Sullivan', 'description');
Nothing comes up. I made sure that James has a description in the object properties in Active Directory between Display Name and Office.

Resources