Monday, March 21, 2011

Demystifying Time Zones in Apps Script - Part 2

In the last post, we went over the basic concepts of time zones in Apps Script. In this post, we will cover a few facts and best practices regarding time zones.

  • The browser’s time zone is used only once in the entire life of a script, as it is the default value for the script’s initial time zone.

  • Spreadsheets and scripts have their own time zone property. Formulas use the spreadsheet’s time zone while custom functions use the script’s time zone.

  • The time zone of a script can be fetched by executing Session.getTimezone().

  • A JavaScript Date is created using var date = new Date(). The newly created date objects inherits the time zone of the script.

  • Triggers use their script’s time zone by default. However, when a script’s time zone is modified, the associated triggers still maintain their original time zone. The only way to change time zone of a trigger is by recreating the trigger.

  • A Google Calendar has its own time zone. The Calendar service uses JavaScript Date objects for all methods that take a date as a parameter. Javascript Date objects have an associated time zone. This is utilized by the Calendar service to perform time zone conversions.

  • CalendarEvent.getStartDate() will return a Date object that has the script’s time zone (not the calendar’s time zone.)

  • The time zone of a user executing a script has no effect on the time zone of a script’s execution environment.

  • Using Utilities.formatDate() will help you convert Date objects to strings while performing time zone conversions. This method uses the specification used in Java’s Data Format.

  • Standard Time Zones should be used when creating Google Calendars via the Calendar service.


We hope that these tips help you gain better understanding of time zones in Apps Script. For further questions, check out the documentation and the forum.

Posted by Saurabh Gupta, Google Developer Relations

Thursday, March 17, 2011

Fun Scripting in Apps Script Hackathon @ NC State

Editor’s Note: Guest Author Md. Ahsanur Rashid is a MS student in the department of Computer Science at North Carolina State University. He recently participated in Google Apps Script Hackathon.

When Google Apps Script Hackathon arrived at NC State, I took up the opportunity to learn Google Apps Script. In school, one of the problems that every group of friends always face is finding the best time to meet somewhere and have fun. Of course, we can use Google Calendar but what we needed was a collaborative way to choose best time and location for all of us to meet. Without a script or some sort of automation this can get kind of crazy and especially in large group settings. Lots of phone calls, emails, endless pings, buzzes and knocks. But it does not need to be this way because we can use Google Apps Script. So, here is how we solved the problem by writing a Google Apps Script.

Step 1 - Every weekend, each friend on the list will be sent an email with a link where he/she can choose the desired time before a preset cutoff. To make the form more user friendly, we designed the form to allow users to choose from a list box rather than directly entering a value.

function sendReminder() {
// get the sheet and last row data
var sheet = SpreadsheetApp.getActiveSheet();
var lastRow = sheet.getLastRow();
for ( var i = 2; i <= lastRow; i++) {
// get the email and name for each row of the form
var userEmail = sheet.getRange(i, getColIndexByName("Email")).getValue();
var userName = sheet.getRange(i, getColIndexByName("Name")).getValue();
// send an email to the user
MailApp.sendEmail(userEmail, "Please send us your best time!",
"Hi" + userName +",\n\n" + "Please fill the form at ....",
{name : "Best Time Chooser"});
}
}


Step 2 - At the cutoff time, our script will process all the responses from all the friends. We configured an Apps Script trigger which will execute the getBestTime() function at the cutoff time on Sunday. The script reads the selected time preferences from the spreadsheet using Spreadsheet Service in Apps Script. The most popular response wins. In case of a tie, a default time (Sunday) is chosen.


Step 3 - After calculating the most popular time preference, the script uses Mail Services to send an email to each friend. All the friends are sent an email to let them know the chosen date.

A very useful feature in Apps Script is debugging. And it could not have been easier to debug in Google Apps Script. We can use Logger.log(); to log the values and debug based on those. Using View->Logs inside the script editor we can see the log file.

To summarize, it was an interesting experience using Apps Script at Google Apps Script Hackathon. Google Apps Script is quite intuitive and great for automating manual tasks.

Posted by Md. Ahsanur Rashid

Friday, March 11, 2011

Demystifying Time Zones in Apps Script - Part 1

Dealing across time zones is complicated not only in real life but also in software programming. In Apps Script, we have support multiple time zones while keeping it simple. When you are writing scripts, you may have to manage time zone conversions because each service you use may operate in its own time zone.

In Apps Script, there are a few basic concepts when it comes to time zones.

  1. A script has its own independent time zone property. It does not share the time zone with either a user’s browser or a spreadsheet. A script’s time zone can be modified using the File > Properties menu in the Script Editor.

  2. A script executes in its own time zone context. Each script is guaranteed an execution environment that uses the script’s predefined time zone. For example, different scripts executing var date = new Date(); may get different dates depending on the time zone of the respective script.
Stay tuned for part 2!

Saurabh Gupta, Google Developer Relations

Tuesday, March 8, 2011

Improving Revevol’s Productivity with Google Apps Script

Repost from Google Enterprise Blog

Editor’s Note: Guest authors Lynn Jaber and Romain Vialard work at Revevol, the first international service provider dedicated to Google Apps. Each day, they imagine new ways to improve their business processes with Google technology!




At Revevol, we train clients’ employees who have just migrated to Google Apps, to help them get the most out of their new system. The more Revevol grows, the more customer trainings we have to handle, so we need to quickly find available trainers depending on parameters like the training date, language, location of trainers and trainer skills.

Google Apps Script, a cloud scripting language based on JavaScript, is wired into almost every Google product, so it’s a perfect solution for checking calendars and spreadsheets, and solving our scheduling problems. In the early days, we were using a simple Google Form. It was really easy to put together and simple to use, but one thing was missing: the form just collected data -- there was no way it could automatically take action based on information submitted. Someone had to manually process the information.

This is where Apps Script came to the rescue -- with a little JavaScript code we could build an interactive form that we so badly needed. In a single day, Apps Script let us build a shiny new graphical user interface for our tool, which lets let us dynamically search for available trainers across all skill levels and categories.

How did we do it? We recreated our form using Ui Services in Apps Script. We added a panel next to the form, to show the search results of trainers that match our queries. By using Spreadsheet Services in Apps Script, we could search and fetch data from a spreadsheet that serves as our database of trainers. We also added the ability to sort the search results of trainers by skill level and distance from the training location.






Thanks to integration with Google Maps Services in Apps Script, we're even able to display a map to help our project managers find the closest trainer. Project managers can select more than one trainer from search results and each selected trainer will receive a calendar invitation. The first to respond “Yes” gets the training assignment. It was incredibly easy to build and deploy this application. In one click, we published it so anyone at Revevol can access the tool in their browsers. Apps Script helped us automate this tedious business process!








Posted by Romain Vialard and Lynn Jaber, Revevol

Wednesday, February 23, 2011

Apps Script's New Debugger, improved Contacts, and more...

Last night we released a new version of Apps Script with a major new feature - the Apps Script Debugger.  A debugger is a tool that helps you to understand what's happening as your code runs, and it can be a huge help in figuring out why your code isn't running the way you intended.

At its most basic, the debugger lets you set a 'breakpoint', and then inspect the state of the script at that point.  A breakpoint is a signal to Apps Script to stop running your code, and you can set a breakpoint on any line of code, just by clicking on the line number.


Then, simply run the script using the 'bug' toolbar icon instead of the usual 'play' button, and the script will run only as far as the first breakpoint.  The debugger panel then allows you to inspect the state of all of the variables in the script.  You can find a more detailed introduction to the debugger in the user guide.

We have also made a major update to the Google Contacts Service.  Along with the numerous bug fixes you'll also see a performance increase and better memory utilization.  The other significant change relates to how we handle 'lists' inside an individual contact - now you can correctly handle multiple email addresses, postal addresses, IM addresses, phone numbers, urls and even dates.

Lastly, we have been listening to feedback, reading the forums, and watching the issue tracker very closely.  We have addressed over 200 bugs and feature requests so far this year; a detailed list of visible changes is available in our release notes.  All that to say that we truly value your feedback - thank you for helping us make Apps Script even better.

Monday, December 20, 2010

DocsList, Notifications and Performance

Have you ever wondered how you can manage permissions of your Files and Folders (aka DocsList) in bulk using Apps Script? And at night, when you are about to go sleep, have you wondered if your script is failing? And you must have wished if your script could run a bit faster. If yes, then we have three really good pieces of news to share with you.

Today, we are enhancing features in DocsList Services, introducing Notification of failed events and increasing the performance of Apps Script when they use other Google services.

Enhancements to DocsList Services
DocsList Services in Google Apps Script provides a powerful API to manage user’s documents list - this week we’re adding functionality to modify file and folder permissions. We’ve added methods to Add and Remove permissions for both editing and viewing.

Why is this important? Two very interesting uses of this functionality are:
  1. Ability to automate changes to File permissions based on logic in your script.
  2. Ability to make file permission changes in bulk (since we needed to give a break to administrators!!).

These new methods are very easy to implement as you only need to provide an array of Users or Email Addresses and you are done! For example:

// Get all VIEWERS of a File or Folder

Folder myFolder = DocsList.getFolder("myFolder");

File myFile = myFolder.getFiles()[0];

User[] fileViewers = myFile.getViewers();

myFile.addEditor("myfriend@mydomain.com");

myFile.addViewer("myOtherFriend@mydomain.com");

// Similarly you can make permission changes in bulk

myFolder.addEditors(fileViewers);

myFolder.addViewer(fileViewers);


Notification of Failed Events
Most of you love and use Triggers for periodic execution of your scripts. We have now gone a step further by allowing you to configure Notifications when your scripts fail. You can setup a periodic email notification which will aggregate failures events thrown by your scripts and email it back to you. This is a really cool feature which will let you sleep at night!.

Increased Performance in accessing other Google Services
The fun thing about Apps Script is that it is an easy way to integrate various Google services like Contacts, Calendar, DocsList and Sites. We have just made this integration a lot more fun. Performance in communicating to these various Google Services has been optimized so that your scripts that access these services can run faster. Services like DocsList can be executed up to 3x faster. A big thanks to the team for that!

Saurabh Gupta, Developer Relations, Google Apps Script

Thursday, October 28, 2010

Google Apps Script and Recurring Calendar Events

Apps Script has added support for recurring calendar events. Users can now write scripts that create, retrieve, update, and delete recurring events in calendars. We’ve also made the interface for this feature simple and easy to use. Let’s look at some examples.

The following code snippet creates a calendar event for all days that are Friday the 13th, so you can remember to avoid bad luck on those days.

var calendar = CalendarApp.getCalendarsByName("My Calendar")[0];
var fridayTheThirteenth = CalendarApp.newRecurrence();
fridayTheThirteenth.addDateExclusion(new Date())
.addDailyRule()
.onlyOnWeekday(CalendarApp.Weekday.FRIDAY)
.onlyOnMonthDay(13);
calendar.createAllDayEventSeries("Bad luck!", new Date(), fridayTheThirteenth);

The next code snippet adds an event to your calendar to remind you of election day in the United States.

var calendar = CalendarApp.getCalendarsByName("My Calendar")[0];
var usaElectionDay = CalendarApp.newRecurrence();
usaElectionDay.addDateExclusion(new Date())
.addYearlyRule()
.interval(4)
.onlyInMonth(CalendarApp.Month.NOVEMBER)
.onlyOnWeekday(CalendarApp.Weekday.TUESDAY)
.onlyOnMonthDays([2, 3, 4, 5, 6, 7, 8]);
calendar.createAllDayEventSeries("Go vote!!!", new Date(), usaElectionDay);

The interface to interact with recurring events is very straight forward and powerful. We were able to easily select all days matching the parameters Friday the 13th, and also to match all Tuesdays in each occurrence of November having a date between 2 and 8, every four years. You can quickly and easily describe dates and times of recurring events you’re looking for. For more information, please check out the release notes and updated documentation.