Exemplo - agendar um relatório
Para agendar um relatório usando o Software Development Kit, crie um objeto schedule e defina os valores apropriados para suas propriedades. Em seguida, use o método add(parentPath, objects,
options) para adicioná-lo ao armazenamento de conteúdo.
Esses exemplos de código mostram como agendar um relatório. Por exemplo, alguns grupos em sua organização podem precisar dos dados em um relatório atualizado a cada minuto. Para atender a essa necessidade, você configura uma visualização de relatório, programa o relatório para ser executado a cada minuto e, em seguida, verifica se ele está programado corretamente.
Métodos
Você pode usar o método add(parentPath,
objects, options) para agendar um relatório.
Consulte o capítulo Métodos no Guia do Desenvolvedor do Kit de Desenvolvimento de Software para obter as permissões e os recursos necessários para esse método.
Código Java
Para ver o código no contexto, veja o exemplo a seguir:
installation_location/sdk/vb/Scheduler/NewScheduler.java
Os seguintes trechos de código Java™ demonstram como você pode agendar um relatório.
Etapas de um programa Java
- Certifique-se de que a conta conectada no momento tenha uma credencial e obtenha uma referência a essa credencial.
if (! Credentials.hasCredential(connection)) { Credentials newCred = new Credentials(); newCred.addCredential(connection); } Account logonInfo = Logon.getLogonAccount(connection); Credential credential = new Credential(); StringProp credentialPath = new StringProp(); String credentialPathString = logonInfo.getSearchPath().getValue(); credentialPathString = credentialPathString + "/credential[@name='Credential']"; credentialPath.setValue(credentialPathString); credential.setSearchPath(credentialPath); BaseClassArrayProp credentials = new BaseClassArrayProp(); credentials.setValue(new BaseClass[] {credential} ); - Defina a data e a hora de início da programação.
public DateTimeProp setScheduleStartDate(Calendar startOnDate) { DateTimeProp startDate = new DateTimeProp(); //If start date not passed set to today/now if (startOnDate != null) startDate.setValue(startOnDate); else startDate.setValue(Calendar.getInstance()); return startDate; } - Defina a data e a hora de término da programação.
public DateTimeProp setScheduleEndDate( Calendar endOnDate, String endOnTime) { DateTimeProp endDate = new DateTimeProp(); if (endOnTime.compareToIgnoreCase("onDate") == 0) if (endOnDate != null) { endDate.setValue(endOnDate); } else System.out.println( "Parameter endOnTime cannot be onDate if no enddate provided"); return endDate; } public NmtokenProp setScheduleEndTime(String endOnTime) { NmtokenProp endTime = new NmtokenProp(); if (endOnTime != null) { endTime.setValue(endOnTime); } else System.out.println( "Parameter endOnTime cannot be null! Options: indefinite or onDate"); return endTime; } - Atribuir o usuário atual como proprietário.
BaseClass[] owners = new BaseClass[] { Logon.getLogonAccount(connection) }; BaseClassArrayProp ownersProp = new BaseClassArrayProp(); ownersProp.setValue(owners); - Defina as opções.
OptionArrayProp roap = new OptionArrayProp(); String reportPath = report.getBaseClassObject().getSearchPath().getValue(); //Set options roap.setValue( this.setSchedulerOptions( outFormat, delivery, reportPath, printerName, saveasName, pageOrientation, paper, emails, connection)); ... RunOptionSaveAs saveAs = new RunOptionSaveAs(); MultilingualToken[] obj = new MultilingualToken[1]; //Set the name of the reportView obj[0] = new MultilingualToken(); obj[0].setLocale("en-us"); //If no name provided use default if (saveasName != null) { obj[0].setValue(saveasName); } else { obj[0].setValue("View of Report " + reportPath); } //Save the object as report view with name saveasName saveAs.setName(RunOptionEnum.saveAs); saveAs.setObjectClass(ReportSaveAsEnum.reportView); saveAs.setObjectName(obj); saveAs.setParentSearchPath(csh.getParentPath(connection, reportPath)); - Defina as propriedades do objeto
schedulee adicione-o ao relatório.newSchedule.setActive(isActive); newSchedule.setCredential(credentials); newSchedule.setEndDate(this.setScheduleEndDate(endOnDate, endOnTime)); newSchedule.setEndType(this.setScheduleEndTime(endOnTime)); newSchedule.setOwner(ownersProp); newSchedule.setParameters(pv); newSchedule.setOptions(roap); newSchedule.setStartDate(this.setScheduleStartDate(startOnDate)); newSchedule.setType(howOften); // add the schedule to the report AddOptions ao = new AddOptions(); ao.setUpdateAction(UpdateActionEnum.replace); BaseClass newBc = connection.getCMService().add( new SearchPathSingleObject(reportPath), new BaseClass[] { newSchedule }, ao)[0];
Código C#
Para ver o código no contexto, veja o exemplo a seguir:
local_de_instalação/sdk/csharp/Schedule/Schedule.cs
Antes de usar esse exemplo, é necessário criar um objeto de credencial para a conta que você usará para executar o exemplo. Para obter mais informações sobre a criação de credenciais, consulte o Guia de Administração e Segurança.
Os seguintes trechos de código C# demonstram como você pode agendar um relatório.
Etapas de um programa C#
- Certifique-se de que a conta conectada no momento tenha uma credencial e obtenha uma referência a essa credencial.
//get the credential for the schedule credential schedCred = connection.getCredential(); baseClassArrayProp credentials = new baseClassArrayProp(); credentials.value = new baseClass[] {schedCred}; newSched.credential = credentials; - Defina as datas e horários de início e término da programação.
// set schedule time to now + 2 minutes System.DateTime startTime = new DateTime(); startTime = DateTime.Now; startTime = startTime.AddMinutes(2); dateTimeProp schedStartTime = new dateTimeProp(); schedStartTime.value = startTime; newSched.startDate = schedStartTime; // set schedule end time to now + 5 minutes System.DateTime endTime = new DateTime(); endTime = DateTime.Now; endTime = endTime.AddMinutes(5); dateTimeProp schedEndTime = new dateTimeProp(); schedEndTime.value = endTime; newSched.endDate = schedEndTime; // set the schedule end type nmtokenProp endType = new nmtokenProp(); endType.value = "onDate"; newSched.endType = endType; - Atribuir o usuário atual como proprietário.
//set the owner baseClassArrayProp ownersProp = new baseClassArrayProp(); baseClass[] owners = new baseClass[] { SamplesConnect.getLogonAccount(connection) }; ownersProp.value = owners; newSched.owner = ownersProp; - Defina as opções.
//Set the name of the reportView multilingualToken[] reportViewName = new multilingualToken[1]; reportViewName[0] = new multilingualToken(); reportViewName[0].locale = "en-us"; reportViewName[0].value = "View of Report " + reportToSchedule.baseclassobject.defaultName.value; //Save the output as report view with name saveasName runOptionSaveAs saveAs = new runOptionSaveAs(); saveAs.name = runOptionEnum.saveAs; saveAs.objectClass = reportSaveAsEnum.reportView; saveAs.objectName = reportViewName; saveAs.parentSearchPath = reportToSchedule.parentPath.value; //Turn off prompting runOptionBoolean prompt = new runOptionBoolean(); prompt.name = runOptionEnum.prompt; prompt.value = false; //set the output format runOptionStringArray format = new runOptionStringArray(); format.name = runOptionEnum.outputFormat; format.value = new string[] { "HTML" }; //put the run options where they need to go runOption[] schedRunOptArr = new runOption[3]; schedRunOptArr[0] = saveAs; schedRunOptArr[1] = prompt; schedRunOptArr[2] = format; runOptionArrayProp schedRunOptions = new runOptionArrayProp(); schedRunOptions.value = schedRunOptArr; newSched.runOptions = schedRunOptions; - Defina as propriedades do objeto
schedulee adicione-o ao relatório.//mark the schedule as active booleanProp isActive = new booleanProp(); isActive.value = true; newSched.active = isActive; //Set the type of schedule cognosdotnet_10_2.nmtokenProp scheduleType = new nmtokenProp(); scheduleType.value = "daily"; newSched.type = scheduleType; //make the schedule for every x minutes nmtokenProp period = new nmtokenProp(); period.value = "minute"; newSched.dailyPeriod = period; //set that every x minutes to be every 1 minute positiveIntegerProp runFreqProp = new positiveIntegerProp(); runFreqProp.value = "1"; newSched.everyNPeriods = runFreqProp; ... searchPathSingleObject reportSearchPath = new searchPathSingleObject(); reportSearchPath.Value = ((baseClass) reportToSchedule.baseclassobject).searchPath.value; // add the schedule to the report addOptions ao = new addOptions(); ao.updateAction = updateActionEnum.replace; baseClass newBc = connection.CBICMS.add( reportSearchPath, new baseClass[] { newSched }, ao)[0];
Explicação
Para criar a agenda, primeiro você cria um objeto schedule e especifica valores para suas propriedades. A seguir, exemplos de propriedades que podem ser especificadas:
activecredentialdailyPeriodendDateendTypeeveryNPeriodsoptionsstartDate
Consulte a descrição da classe schedule no capítulo sobre classes do Guia do Desenvolvedor do Kit de Desenvolvimento de Software para obter uma lista completa e uma descrição das propriedades.
Se o relatório contiver prompts, você também deverá especificar parâmetros na propriedade parameters .
A programação em uma matriz schedule é passada para o método add(parentPath,
objects, options) e a programação é criada no armazenamento de conteúdo.
Etapas para escrever seus próprios programas
- Crie uma matriz de objetos
schedule. - Crie um novo objeto
schedule. - Crie um novo objeto
addOptions. - Crie um objeto
dateTimeProppara a data e a hora de início do objetoschedulee defina seu valor como a data e a hora de início necessárias. Atribua esse objetodateTimePropà propriedadestartDatedo cronograma. - Crie uma matriz de objetos
optionpara o objetoschedule. Essas opções serão aplicadas sempre que o relatório agendado for executado. Atribua essa matriz à propriedadevalueda propriedadeoptionsdo objetoschedule. - Defina os valores das outras propriedades do objeto
schedule. - Adicione o objeto
scheduleà matrizschedule. - Defina os valores desejados para as propriedades do objeto
addOptions. - Chame o método
add(parentPath, objects, options), passando o caminho de pesquisa, a matrizschedulee o objetoaddOptionscomo parâmetros.