Showing posts with label internet. Show all posts
Showing posts with label internet. Show all posts

Mar 5, 2014

Running scripts on google drive documents

Hi.

I admit I have always looked to "cloud based" document editing (such as google drive, Microsoft Office 365, etc) with certain dislike, mainly due to the misconception that these applications would not allow me to use my precious scripts (after all, any true developer shall use scripts everywhere, right? ;)

Even though I somewhat disliked the idea, I ended up ceding (the convenience of having it available anywhere is so hard to ignore :) and,for some time, I have been using one spreadsheet to store a piece of information I use on a monthly basis.

It happens that last week I decided that one of the tasks involving that spreadsheet should be automated (basically, given some condition I'd like to add some information to a specific cell, which is a perfect job for a script) so I was considering moving the spreadsheet to my box and use LibreOffice (which I highly recommend, by the way) to edit it. 

While I was poking around my google spreadsheet menus, I stumbled in "Tools/Script Editor" menu option and realized that my resistance in using such online solutions had no ground whatsoever, i.e, it was just prejudice from my side :( I just selected that menu option and voila, scripts with debugging support!

That is all I needed! Some time (and a lot of keystrokes) later and I had my first script running; but the best was yet to come: not only I was able to reference my newly created function, but I could also schedule it to run from time to time! (that's exactly what I was looking for).

Following you can see my script:
function checkDate() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheets()[0];       
    
  var range = sheet.getRange("A1");
  
  var now = new Date();
  
  if (now.getHours() <= 10 || (now.getHours() >= 15 && now.getMinutes() > 30) || (now.getHours() >= 13 && (now.getHours() <= 14 && now.getMinutes() < 30)) ) {    
    range.setBackground("ORANGE");
    range.setValue("CLOSED");
  }
  else {
    range.setBackground("GREEN");
    range.setValue("OPEN");
  }
}
And it worked like a charm.

To my astonishment, today I figured it out that I can even execute WebServices (SOAP) from within my scripts (and of course I put it in action immediately) ! 

Happy Coding!

(Leia, uma versão extendida, deste post em portugues)

Executando scripts em documentos do google drive

(If you don't read Portuguese, you can read a simplified version of this post in english)

Ola.

Sempre tive certo "desdém" por soluções de edição de documentos (principalmente planilhas) nas "nuvens" (tipo google drive e/ou office 365), motivado, principalmente, por acreditar que as mesmas não me permitiriam incluir meus tão úteis scripts (afinal de contas, desenvolvedor que se prese tem que usar scripts em tudo ;)

Mesmo assim, ha algum tempo venho usando uma planilha no google drive para controlar ordens de pagamento; acontece que, na semana passada eu estava considerando passar a usar o LibreOffice (que por sinal eu recomendo) para fazer minhas edições nesta planilha pois eu queria modificar a cor de uma das células caso uma determinada condição fosse satisfeita (e isso, é claro, é tarefa para scripts). 

Não sei porque (ou como) eu acabei descobrindo que esta minha resistência em usar o google drive não passava de puro preconceito! Se você for no menu "Tools" (deve ser "Ferramentas" no bom e velho português) encontrará a opção "Script Editor"! Ou seja, pelo menos as planilhas do google drive, suportam scripts! E o melhor, até dupuração!)

Pronto! É tudo que eu precisava; depois de alguns minutos (e um punhado de teclas pressionadas) meu primeiro script estava pronto. E sabe da melhor? É possível referenciar scripts em fórmulas ou até mesmo agendar o mesmo para executar de tempo em tempo (exatamente o que eu buscava).

Abaixo segue o código que usei:
function checkDate() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheets()[0];       
    
  var range = sheet.getRange("A1");
  
  var now = new Date();
  
  if (now.getHours() <= 10 || (now.getHours() >= 15 && now.getMinutes() > 30) || (now.getHours() >= 13 && (now.getHours() <= 14 && now.getMinutes() < 30)) ) {    
    range.setBackground("ORANGE");
    range.setValue("FECHADO");
  }
  else {
    range.setBackground("GREEN");
    range.setValue("ABERTO");
  }
}
Hoje eu encontrei mais um motivo para eu criar mais um script nesta planilha: sempre que recebo ordens de pagamento eu quero saber a cotação do dolar no momento. Normalmente o que eu fazia era abrir o browser e navegar para algum site de cotação. 

O problema com esta solução é que a mesma é ...  digamos.... é manual (e não usa scripts :)). A solução mais óbvia para a questão? Encontrar alguma empresa que disponibilize a cotação do dolar através de um WebService e escrever um script para chamar este WebService.

Para minha surpresa, ao fazer uma busca na web, encontrei este post que descreve como acessar o WebService do Banco Central do Brasil (que eu nem imaginava que existisse) para obter tal informação. Perfeito, agora eu só tive que descobrir uma forma de executar o mesmo e fazer o parse dos dados retornados (o que não foi tão simples quanto parecia pois não consegui encontrar documentação do WebService em lugar algum).

O Código final ficou mais ou menos assim (não me preocupei em fazer tratamento de erros, muito menos em ser eficiente, só queria que o mesmo funcionasse :)
function getDolarExchangeRate() {
  Logger.clear();
  
  var wsdl = SoapService.wsdl("https://www3.bcb.gov.br/sgspub/JSP/sgsgeral/FachadaWSSGS.wsdl");  
  var service = wsdl.getService("FachadaWSSGSService");  
  var result = service.invokeOperation("getUltimosValoresSerieVO", ["1", "1"]);
    
  var i = 0;
  while (typeof result.Envelope.Body.multiRef[i] != 'undefined' ) {
    if (typeof result.Envelope.Body.multiRef[i].svalor != 'undefined')
      return result.Envelope.Body.multiRef[i].svalor.getText();
    i++;
  }
  
  return "Could not find 'svalor' element";
}
Agora tudo que tive  que fazer foi escolher uma célula na planilha e entrar a formula =getDolarExchangeRate() na mesma e bum, lá estava a cotação do dolar.

Happy Coding!