When I execute the code I developed to call an Async method of the linq2Twitter, I am getting a System.Aggregate Exception, the code is below:
static async Task<List<myTwitterStatus>> getRetweets(ulong tweetID, TwitterContext twitterCtx)
{
List<myTwitterStatus> reTweets = new List<myTwitterStatus>();
var publicTweets =
await
(from tweet in twitterCtx.Status
where tweet.Type == StatusType.Retweets &&
tweet.ID == tweetID
select tweet)
.ToListAsync();
if (publicTweets != null)
publicTweets.ForEach(tweet =>
{
if (tweet != null && tweet.User != null)
{
myTwitterStatus tempStatus = new myTwitterStatus();
tempStatus.Country = tweet.Place.Country;
tempStatus.createdAt = tweet.CreatedAt;
tempStatus.FavoriteCount = long.Parse(tweet.FavoriteCount.ToString());
tempStatus.ID = tweet.ID;
tempStatus.isTruncated = tweet.Truncated;
tempStatus.Lang = tweet.Lang;
tempStatus.MaxID = tweet.MaxID;
tempStatus.PlaceFullname = tweet.Place.FullName;
tempStatus.RetweetCount = tweet.RetweetCount;
tempStatus.ScreenName = tweet.ScreenName;
tempStatus.Text = tweet.Text;
tempStatus.UserFriends = tweet.User.FriendsCount;
tempStatus.UserCreated = tweet.User.CreatedAt;
tempStatus.UserFollowers = tweet.User.FollowersCount;
tempStatus.UserFavorities = tweet.User.FavoritesCount;
tempStatus.UserFriends = tweet.User.FriendsCount;
tempStatus.UserLocation = tweet.User.Location;
tempStatus.UserName = tweet.User.Name;
tempStatus.UserTweetCount = tweet.User.StatusesCount;
reTweets.Add(tempStatus);
}
});
return reTweets;
}
The issue is when I called the method
var authorizer = new SingleUserAuthorizer
{
CredentialStore = new InMemoryCredentialStore
{
ConsumerKey = SM.Default.Consumer_key2.ToString(),
ConsumerSecret = SM.Default.Consumer_secret2.ToString(),
OAuthToken = SM.Default.Access_token2.ToString(),
OAuthTokenSecret = SM.Default.Access_secret2.ToString()
}
};
TwitterContext twitterCtx = new TwitterContext(authorizer);
Task<List<myTwitterStatus>> task = Task<List<myTwitterStatus>>.Factory.StartNew(() => getRetweets(ulong.Parse(tweet.StringId), twitterCtx).Result);
task.Wait();
List<myTwitterStatus> tempList = task.Result.ToList<myTwitterStatus>();
foreach (var ret in tempList)
{
un = file.RemoveSpecialCharacters(ret.UserName);
sn = file.RemoveSpecialCharacters(ret.ScreenName);
tweets.AppendLine(account + "," + getWE(ret.createdAt) + "," + Text + "," + un + "," + sn + "," + ret.createdAt + "," +
file.RemoveSpecialCharacters(ret.UserLocation) + ",,,1,," + ret.UserTweetCount + "," +
ret.RetweetCount + "," + ret.FavoriteCount + "," + ret.UserFollowers);
I would appreciate any kind of assistance about it, I have no idea how to solve it.
Can you add a try/catch so see what the inner exception is.
try
{
//Perform your operation here
}
catch (AggregateException aex)
{
//Dive into inner exception
}
Thanks to all for the help, I activate the breakpoints for the specific exception and an additional validation was added, the issue was not in the async process, it was because it was trying to handle a null as an string, to hendle this error this line was modified sn = file.RemoveSpecialCharacters(ret.ScreenName ?? string.Empty);
The full code is below:
private void getRetweets(TwitterStatus tweet)
{
Text = file.RemoveSpecialCharacters(tweet.Text);
tweetID = tweet.StringId;
#region Get retweets
RetweetsOptions retOpt = new RetweetsOptions();
if (int.Parse(tweet.RetweetCountString.ToString()) > 1)
retOpt.Count = int.Parse(tweet.RetweetCountString.ToString()) + 1;
else
retOpt.Count = 1;
String errorText = "";
DateTime fromDate, toDate;
if (radDate.Checked == true)
{
fromDate = dtpFrom.Value;
toDate = dtpTo.Value;
}
else
{
fromDate = tweet.CreatedDate;
toDate = DateTime.Now;
}
TwitterResponse<TwitterStatusCollection> retweet = null;
if (int.Parse(tweet.RetweetCountString.ToString()) > 100)
{
var authorizer = new SingleUserAuthorizer
{
CredentialStore = new InMemoryCredentialStore
{
ConsumerKey = SM.Default.Consumer_key2.ToString(),
ConsumerSecret = SM.Default.Consumer_secret2.ToString(),
OAuthToken = SM.Default.Access_token2.ToString(),
OAuthTokenSecret = SM.Default.Access_secret2.ToString()
}
};
TwitterContext twitterCtx = new TwitterContext(authorizer);
//HELPER: https://www.youtube.com/watch?v=IONqMWGn9-w
try
{
Task<List<myTwitterStatus>> task = null;
Parallel.Invoke(
() =>
{
task = getRetweets(ulong.Parse(tweet.StringId), twitterCtx);
while (!task.IsCompleted)
{
Thread.Sleep(250);
}
});
List<myTwitterStatus> tempList = task.Result.ToList<myTwitterStatus>();
foreach (var ret in tempList)
{
un = file.RemoveSpecialCharacters(ret.UserName);
sn = file.RemoveSpecialCharacters(ret.ScreenName ?? string.Empty);
tweets.AppendLine(account + "," + getWE(ret.createdAt) + "," + Text + "," + un + "," + sn + "," + ret.createdAt + "," +
file.RemoveSpecialCharacters(ret.UserLocation) + ",,,1,," + ret.UserTweetCount + "," +
ret.RetweetCount + "," + ret.FavoriteCount + "," + ret.UserFollowers);
}
}catch(Exception ex){
Console.WriteLine("Error: " + ex.Message+ Environment.NewLine + ex.StackTrace);
}
return;
}
else
retweet= TwitterStatus.Retweets(tokensRet, Decimal.Parse(tweet.Id.ToString()), retOpt);
if (retweet.Result.ToString() == "Success" && retweet.ResponseObject.Count > 0 && retweet!=null)
{
int retPages = int.Parse(tweet.RetweetCountString.ToString()) + 1 / 20;
for (int page = 0; page <= retPages; page++)
{
try
{
//List<TwitterStatus> retList = new List<TwitterStatus>(retweet.ResponseObject.Page = page);
retweet.ResponseObject.Page = page;
List<TwitterStatus> retList = retweet.ResponseObject.ToList<TwitterStatus>();
foreach (var ret in retList)
{
try
{
if (ret.CreatedDate.CompareTo(fromDate) >= 0 && ret.CreatedDate.CompareTo(toDate) <= 0)
{
#region Get UN Sync
getUN(ret, ref un, ref sn);
#endregion
tweets.AppendLine(account + "," + getWE(ret.CreatedDate) + "," + Text + "," + un + "," + sn + "," + ret.CreatedDate + "," +
file.RemoveSpecialCharacters(ret.User.Location.ToString()) + ",,,1,," + ret.User.NumberOfStatuses.ToString() + "," +
ret.RetweetCount + "," + ret.User.NumberOfFavorites.ToString() + "," + ret.User.NumberOfFollowers.ToString());
}
else if (tweet.CreatedDate.CompareTo(toDate) <= 0)//if the tweet's created date is lower than the from's date, exits the loop
break;
}
catch (NullReferenceException ex)
{
errorText = ex.Source + Environment.NewLine + ex.StackTrace;
continue;
}
}
}
catch (Exception ex)
{
errorText = ex.Source + Environment.NewLine + ex.StackTrace;
//MessageBox.Show(ex.Message + Environment.NewLine + "Rate Limit was reached!" + Environment.NewLine +
// "Wait an hour or try a shorter date range", "Rate Limit Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
else if (error == false && retweet.Result.ToString() != "Success")
{
errorText = retweet.Result.ToString();
MessageBox.Show("Retweets: Something went wrong!" + Environment.NewLine + errorText, "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
error = true;
}
#endregion
}
Related
I'm trying to get data from a website that does not have an API documentation. I used selenium to login and navigate. Today I found the data I need, it appears after a post request.
There's any way I can get the exact post parameters to do it in my node program?
Data I need
edit 1:
the code that works from console browser scrap the data from the page and save a csv file:
const timeElapsed = Date.now();
const today = new Date(timeElapsed);
let updateTime;
let dataStudents = "";
let anoSerie;
let turma;
let prova;
let disciplina;
class AlunoProva {
constructor(nome, Status, anoSerie, turma, prova, disciplina, modalidadeEnsino, data) {
this.nome = nome;
this.Status = Status;
this.anoSerie = anoSerie;
this.turma = turma;
this.prova = prova;
this.disciplina = disciplina;
this.modalidadeEnsino = modalidadeEnsino;
this.data = data;
}
}
var saveData = (function () {
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
return function (data, fileName) {
blob = new Blob([data], { type: "ext/csv;charset=utf-8;" }),
url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
};
}());
const atualState = "Finalizado - Digital, Não iniciado, Em progresso - Digital"
function getTurma() {
let Turma = prompt("Informe a letra da turma atual", "A");
while (Turma == null || Turma == "") {
alert("Truma inválida! Por favor, informe uma turma válida.");
Turma = prompt("Informe a letra da turma atual", "A");
}
return Turma;
}
turma = getTurma().toUpperCase();
function getCombo(id) {
let combo = document.getElementById(id);
let dataComboSelected = combo.options[combo.selectedIndex].text;
return dataComboSelected;
}
String.prototype.hashCode = function () {
var hash = 0, i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
let aluno = new AlunoProva()
function dataMount(data) {
if (data !== "ESTUDANTE" && data !== "PARTICIPAÇÃO")
if (!atualState.includes(data)) {
aluno.nome = data;
dataStudents += data + ",";
}
else {
aluno.Status = data;
dataStudents += data + ",";
aluno.anoSerie = anoSerie;
dataStudents += anoSerie + ","
aluno.turma = turma;
dataStudents += turma + ","
aluno.prova = prova;
dataStudents += prova + ","
aluno.disciplina = disciplina;
dataStudents += disciplina + ","
if (anoSerie.includes("EF")) {
aluno.modalidadeEnsino = "Fundamental";
dataStudents += "Fundamental,"
}
else {
aluno.modalidadeEnsino = "Médio";
dataStudents += "Médio,"
}
aluno.data = today.toLocaleDateString();
dataStudents += today.toLocaleDateString() + "\n"
}
}
prova = getCombo('selectnn74f9d641c4DADOS.VL_FILTRO_AVALIACAO')
disciplina = getCombo('select3lw7fc885326DADOS.VL_FILTRO_DISCIPLINA')
anoSerie = getCombo('selecty0fuc3bed07cDADOS.VL_FILTRO_ETAPA')
Array.from($$("body table tr *")).forEach((el) => {
el = String(el.innerHTML)
if (el.indexOf('Atualizado') === 0) {
updateTime = el;
} else if (el.length != 0 && el != undefined) {
dataMount(el);
}
});
let hashname = (anoSerie + turma + prova + disciplina + JSON.stringify(today.toLocaleDateString())).toString();
fileName = `${anoSerie} - ${turma} - ${prova} - ${disciplina}"${hashname.hashCode()}".csv`
saveData(dataStudents, fileName);
I'm having a problem with selectors on node, just rebember that I'm not conected with the site, I'm simulating a navigation with selenium. All the frameworks I checked to help me with selectors needed that I provide an url, but I can't, the only way I found to enter the system is from selenium navigation to simulating a real user.
I am facing some issue when I published over azure it's not working please tell me if any person have a solution about it.
public ActionResult GenerateReport(string ReportName)
{
LocalReport localReport = new LocalReport();
localReport.ReportPath = Server.MapPath(#"~/Areas/RemoteAnalysis/rptAlarm.rdlc");
List<clsReport> lstOverallData = new List<clsReport>();
using (DBClass context = new DBClass())
{
context.AddParameter("#FileID", Convert.ToInt32(Session["FileID"]));
context.AddParameter("#UserID", Session["UserName"]);
DataTable dtReportData = context.getData("GetRouteDetailForReport", CommandType.StoredProcedure);
if (dtReportData.Rows.Count > 0)
{
foreach (DataRow dr in dtReportData.Rows)
{
try
{
lstOverallData.Add(new clsReport
{
FileID = Convert.ToInt32(dr["Fileid"]),
PlantID = Convert.ToString(dr["PlantID"]),
PlantName = Convert.ToString(dr["PlantName"]),
AreaID = Convert.ToString(dr["AreaID"]),
AreaName = Convert.ToString(dr["AreaName"]),
TrainID = Convert.ToString(dr["TrainID"]),
TrainName = Convert.ToString(dr["TrainName"]),
MachineID = Convert.ToString(dr["MachineID"]),
MachineName = Convert.ToString(dr["MachineName"]),
PointID = Convert.ToString(dr["PointID"]),
PointName = Convert.ToString(dr["PointName"]),
AalrmID = Convert.ToInt32(dr["PointAlarmID"]),
AlarmName = Convert.ToString(dr["AlarmName"]),
HighValue = Convert.ToDouble(dr["HighValue"]),
LowValue = Convert.ToDouble(dr["LowValue"]),
MeasurementTime = Convert.ToDateTime("2018-04-17 14:44:02.293"),
OverallChnlA = Convert.ToDouble(dr["OverallValueChnlA"]),
UnitChnlA = Convert.ToString(dr["OverallUnitChnlA"]),
OverallChnlB = Convert.ToDouble(dr["OverallValueChnlB"]),
UnitChnlB = Convert.ToString(dr["OverallUnitChnlB"]),
DataID = Convert.ToInt32(dr["DataID"])
});
}
catch (Exception ex)
{
throw ex;
}
}
}
}
//code changes from here on 5 march 2021..
ReportDataSource reportDataSource = new ReportDataSource("dsOverall", lstOverallData);
localReport.DataSources.Add(reportDataSource);
localReport.Refresh();
string reportType = ""; //"PDF"; //Enter downloading format according to your choice/if condition
string mimeType;
string encoding;
string fileNameExtension;
string format = "";
string filename = "";
string deviceInfo = "";
//The DeviceInfo settings should be changed based on the reportType
if (ReportName == "pdf")
{
reportType = "PDF";
format = "application/pdf";
filename = "AlaramReport.pdf";
deviceInfo = "<DeviceInfo>" +
" <OutputFormat>pdf</OutputFormat>" +
" <PageTitle> Report</PageTitle>" +
" <PageWidth>9.5in</PageWidth>" +
" <PageHeight>11in</PageHeight>" +
" <MarginTop>0.5in</MarginTop>" +
" <MarginLeft>0.5in</MarginLeft>" +
" <MarginRight>0.5in</MarginRight>" +
" <MarginBottom>0.5in</MarginBottom>" +
"</DeviceInfo>";
}
else if (ReportName == "doc")
{
reportType = "Word";
format = "application/doc";
filename = "AlaramReport.doc";
deviceInfo = "<DeviceInfo>" +
" <OutputFormat>doc</OutputFormat>" +
" <PageTitle> Report</PageTitle>" +
" <PageWidth>9.5in</PageWidth>" +
" <PageHeight>11in</PageHeight>" +
" <MarginTop>0.5in</MarginTop>" +
" <MarginLeft>0.5in</MarginLeft>" +
" <MarginRight>0.5in</MarginRight>" +
" <MarginBottom>0.5in</MarginBottom>" +
"</DeviceInfo>";
}
else if (ReportName == "xls")
{
reportType = "Excel";
format = "application/xls";
filename = "AlaramReport.xls";
deviceInfo = "<DeviceInfo>" +
" <OutputFormat>xls</OutputFormat>" +
" <PageTitle> Report</PageTitle>" +
" <PageWidth>9.5in</PageWidth>" +
" <PageHeight>11in</PageHeight>" +
" <MarginTop>0.5in</MarginTop>" +
" <MarginLeft>0.5in</MarginLeft>" +
" <MarginRight>0.5in</MarginRight>" +
" <MarginBottom>0.5in</MarginBottom>" +
"</DeviceInfo>";
}
else if (ReportName == "jpg")
{
reportType = "Image";
format = "application/jpg";
filename = "AlaramReport.jpg";
deviceInfo = "<DeviceInfo>" +
" <OutputFormat>jpg</OutputFormat>" +
" <PageTitle> Report</PageTitle>" +
" <PageWidth>9.5in</PageWidth>" +
" <PageHeight>11in</PageHeight>" +
" <MarginTop>0.5in</MarginTop>" +
" <MarginLeft>0.5in</MarginLeft>" +
" <MarginRight>0.5in</MarginRight>" +
" <MarginBottom>0.5in</MarginBottom>" +
"</DeviceInfo>";
}
else
{
reportType = "PDF";
format = "application/pdf";
filename = "AlaramReport.pdf";
deviceInfo = "<DeviceInfo>" +
" <OutputFormat>pdf</OutputFormat>" +
" <PageTitle> Report</PageTitle>" +
" <PageWidth>9.5in</PageWidth>" +
" <PageHeight>11in</PageHeight>" +
" <MarginTop>0.5in</MarginTop>" +
" <MarginLeft>0.5in</MarginLeft>" +
" <MarginRight>0.5in</MarginRight>" +
" <MarginBottom>0.5in</MarginBottom>" +
"</DeviceInfo>";
}
//Render the report
Warning[] warnings;
string[] streams;
byte[] renderedBytes;
renderedBytes = localReport.Render(reportType, deviceInfo, out mimeType, out encoding, out fileNameExtension, out streams, out warnings);
ViewBag.Title = "Alarm Report";
return File(renderedBytes, format, filename);
}
The above one is my code which is used to generate a report on local serer but when I publish on Azure then it was not working and shows me an error like server error. How to resolve this issue please anyone tell me. tried lots of code for this issue but nothing to work.
I need optimized solution to increment and decrement alphanumeric string value as we do in excel. When I specify alphanumeric string with range then it should give me both decremented n incremented list of values. For e.g I need range of +-10 of alphanumeric string as.
PN - Alpha character may come in start / middle /end
1. A2000018 -> A2000008 to A2000028
2. A39999 -> A39989 to A40009
3. A00005 -> A00001 to A00015
4. AZ00005 -> AZ00001 to AZ00015
5. A342S0004 -> A342S0001 to A342S0014
6. A342S9999 -> A342S9989 to A342S10009
7. 1234A -> 1224A to 1244A
8. 0003A -> 0001A to 0013A
public static List<String> getRangeList(String docNumber, int range) {
List<String> rangeList = new ArrayList<>();
System.out.println("Document Number Received " + docNumber);
/**
* REGEX checks for String value starting with 1 character as alpha and rest numeric
*/
boolean trailingAlphabet = false;
boolean leadingNtrailingAlphabet = false;
boolean leadingNtrailingNumber = false;
String patternStr = "";
if (docNumber.trim().matches("[a-zA-Z]{1,5}[0-9]{1,20}[a-zA-Z]{1,5}$")) { //String docNumber = "AD234SD1234 ";
patternStr = "(.*?)(\\d+)(.*?)$";
leadingNtrailingAlphabet = true;
} else if (docNumber.trim().matches("[0-9]{1,20}[a-zA-Z]{1,5}[0-9]{1,20}+$")) { //String docNumber = "1234AD1234 ";
patternStr = "(\\d+)(.*?)(\\d+)$";
leadingNtrailingNumber = true;
} else if (docNumber.trim().matches("[0-9]{1,20}[a-zA-Z]{1,4}+$")) { //String docNumber = "1234A ";
patternStr = "(\\d+)(.*?)$";
trailingAlphabet = true;
} else if (docNumber.trim().matches("[a-zA-Z]{1,5}[0-9]+$")
|| docNumber.trim().matches("[a-zA-Z]{1,5}[0-9]{1,20}[a-zA-Z]{1,4}[0-9]+$")) {
patternStr = "(.*?)(\\d+)$";
}
Pattern pattern = Pattern.compile(patternStr);
Matcher matcher = pattern.matcher(docNumber.trim());
if (matcher.find()) {
String firstAlpha = "";
String origNumber = "";
String lastAlpha = "";
if (trailingAlphabet) {
firstAlpha = matcher.group(2);
origNumber = matcher.group(1);
} else if (leadingNtrailingAlphabet) {
firstAlpha = matcher.group(1);
origNumber = matcher.group(2);
lastAlpha = matcher.group(3);
} else if (leadingNtrailingNumber) {
firstAlpha = matcher.group(1);
lastAlpha = matcher.group(2);
origNumber = matcher.group(3);
} else {
firstAlpha = matcher.group(1);
origNumber = matcher.group(2);
}
//System.out.println("1 Alpha : " + firstAlpha + " origNNum : " + origNumber + " lastAlpha : " + lastAlpha);
String incrNumStr = origNumber;
String dcrNumStr = origNumber;
for (int i = 0; i < range; i++) {
if (Integer.parseInt(dcrNumStr) - 1 <= 0) {
break;
}
dcrNumStr = String.format("%0" + dcrNumStr.length() + "d", Integer.parseInt(dcrNumStr) - 1);
if (leadingNtrailingNumber) {
rangeList.add(firstAlpha + lastAlpha + dcrNumStr);
} else if (leadingNtrailingAlphabet) {
rangeList.add(firstAlpha + dcrNumStr + lastAlpha);
} else if (trailingAlphabet) {
rangeList.add(dcrNumStr + firstAlpha);
} else {
rangeList.add(firstAlpha + dcrNumStr);
}
}
for (int i = 0; i < range; i++) {
incrNumStr = String.format("%0" + incrNumStr.length() + "d", Integer.parseInt(incrNumStr) + 1);
if (leadingNtrailingNumber) {
rangeList.add(firstAlpha + lastAlpha + incrNumStr);
} else if (leadingNtrailingAlphabet) {
rangeList.add(firstAlpha + incrNumStr + lastAlpha);
} else if (trailingAlphabet) {
rangeList.add(incrNumStr + firstAlpha);
} else {
rangeList.add(firstAlpha + incrNumStr);
}
}
Collections.sort(rangeList);
System.out.println(rangeList);
}
return rangeList;
}
public double getMinCBQta(long enteCod, long artCod) throws FailureException {
logger.debug("getMinCBqta() - ENTER");
double minCBQta = 0;
final TypedQuery<Double> query = em.createQuery("select NVL(Min(c.qtaCapienza),0) " + "from CapienzaBanco c "
+ "where c.id.enteCod = :ENTECOD AND c.id.artCod = :ARTCOD "
+ "AND c.id.nrPromo = 0 AND c.id.annoPromo = 0 AND c.qtaCapienza!= 0 ", Double.class);
try {
query.setParameter(CommonConstants.ENTECOD, enteCod);
query.setParameter(CommonConstants.ARTCOD, artCod);
minCBQta = query.getSingleResult();
} catch (final NoResultException ne) {
logger.warn("getMinCBQta :No result received from CAPIENZA_BANCO with enetCod " + enteCod + "artCod: " + artCod);
} catch (final Exception e) {
logger.error("getMinCBQta : Error Retriving data from CAPIENZA_BANCO " + e.getMessage());
throw new FailureException("getMinCBQta : Error Retriving data from CAPIENZA_BANCO " + e);
}
logger.debug("getMinCBqta()" + " EXIT");
return minCBQta;
}
I have a button that does the following:
1) Delete the current information in the form.
2) Runs javascript to create new entries in the form.
The information is displayed in a viewpanel. The problem is that the information that is displayed is incomplete and old. I added an additional button that only does a partial refresh. Once the first button is finished running, I click on the second panel and this second refresh displays the latest data. I have been playing with putting variations of XSP.partialRefreshGet("#{id:WrapperPanel}", {}); in the oncomplete event of the first button - to no avail.
Here is the code:
<xp:button id="button34"
value="Check Teacher Information"
styleClass="BlueButtonSmall">
<xp:eventHandler event="onclick"
submit="true" refreshMode="complete" id="eventHandler50">
<xp:this.action><![CDATA[#{javascript:var serverName:NotesDatabase = database.getServer();
var PosdbName = new Array(serverName,"Position.nsf");
var CamdbName = new Array(serverName,"Campus.nsf");
var currentDB:NotesDatabase=session.getCurrentDatabase();
//Delete old records
var i = 0;
var crview = database.getView("ChangeReport");
var crvec:NotesViewEntryCollection = crview.getAllEntries();
var crentry:NotesViewEntry = crvec.getFirstEntry();
while (crentry != null) {
crDoc = crentry.getDocument();
crDoc.remove(true);
crDoc.recycle();
if (i > 100) {
print("Possible Loop HRMainX - breaking");
break;
}
i++
var tmpentry:NotesViewEntry = crvec.getNextEntry(crentry);
crentry.recycle();
crentry = tmpentry;
}
database.updateFTIndex(false);
var aview = database.getView("NISDTeacher");
var vec:NotesViewEntryCollection = aview.getAllEntries();
var entry:NotesViewEntry = vec.getFirstEntry();
var i = 0;
while (entry != null) {
var Enumber:string = entry.getDocument().getItemValueString("TeacherEnumber");
var Firstname = entry.getDocument().getItemValueString("TeacherFirst");
var Lastname = entry.getDocument().getItemValueString("TeacherLast");
var Active = #DbLookup(PosdbName,"All",Enumber,"Posd_Active");
var Status = #DbLookup(PosdbName,"All",Enumber,"Posd_Status");
if (Active === "Y" || Status === "A") {
var CurrCampusNum = #DbLookup(PosdbName,"ActiveID",Enumber,"Posd_Campus");
var CurrCampusType = #DbLookup(CamdbName,"Campus",CurrCampusNum,"Cmp_Level");
if (CurrCampusType === "SP" || CurrCampusType === "EL" || CurrCampusType === "MS" || CurrCampusType === "HS") {
var CampusNum = entry.getDocument().getItemValueString("CampusNum");
var PositionCode = entry.getDocument().getItemValueString("TeacherPCode");
var CurrFirstname = #Trim(#ProperCase(#DbLookup(PosdbName,"ActiveID",Enumber,"Posd_FName")));
var CurrLastname = #Trim(#ProperCase(#DbLookup(PosdbName,"ActiveID",Enumber,"Posd_lname")));
var CurrPositionCode = #DbLookup(PosdbName,"ActiveID",Enumber,"Posd_Job_Code");
if (CurrFirstname !== Firstname) {
var reportDate = session.createDateTime(#Now());
var changeDoc = currentDB.createDocument();
changeDoc.replaceItemValue("Form","ChangeReport");
changeDoc.replaceItemValue("DateReported",reportDate);
var Change = Enumber + " " + Firstname + " " + Lastname + " has a new Firstname of " + CurrFirstname;
changeDoc.replaceItemValue("Change",Change)
changeDoc.save();
}
if (CurrLastname !== Lastname) {
var reportDate = session.createDateTime(#Now());
var changeDoc = currentDB.createDocument();
changeDoc.replaceItemValue("Form","ChangeReport");
changeDoc.replaceItemValue("DateReported",reportDate);
var Change = Enumber + " " + Firstname + " " + Lastname + " has a new Lastname of " + CurrLastname;
changeDoc.replaceItemValue("Change",Change)
changeDoc.save();
}
if (CurrCampusNum !== CampusNum) {
var reportDate = session.createDateTime(#Now());
var changeDoc = currentDB.createDocument();
changeDoc.replaceItemValue("Form","ChangeReport");
changeDoc.replaceItemValue("DateReported",reportDate);
var CampusName = entry.getDocument().getItemValueString("CampusName");
var CurrCampusName = #DbLookup(CamdbName,"Campus",CurrCampusNum,"Cmp_ShortName");
var Change = Enumber + " " + Firstname + " " + Lastname + " was teaching at " + CampusName + " (" + CampusNum + ") " +
"and is now teaching at " + CurrCampusName + " (" + CurrCampusNum + ")";
changeDoc.replaceItemValue("Change",Change)
changeDoc.save();
}
if (CurrPositionCode !== PositionCode) {
var reportDate = session.createDateTime(#Now());
var changeDoc = currentDB.createDocument();
changeDoc.replaceItemValue("Form","ChangeReport");
changeDoc.replaceItemValue("DateReported",reportDate);
var PositionTitle = entry.getDocument().getItemValueString("TeacherPTitle");
var CurrPositionTitle = #DbLookup(PosdbName,"ActiveID",Enumber,"Posd_Title");
var Change = Enumber + " " + Firstname + " " + Lastname + " was teaching " + PositionTitle + " (" + PositionCode + ") " +
"and is now teaching " + CurrPositionTitle + " (" + CurrPositionCode + ")";
changeDoc.replaceItemValue("Change",Change)
changeDoc.save();
}
} else {
var reportDate = session.createDateTime(#Now());
var changeDoc = currentDB.createDocument();
changeDoc.replaceItemValue("Form","ChangeReport");
changeDoc.replaceItemValue("DateReported",reportDate);
var Change = Enumber + " " + Firstname + " " + Lastname + " no longer works as a classroom teacher.";
changeDoc.replaceItemValue("Change",Change);
changeDoc.save();
}
} else {
var reportDate = session.createDateTime(#Now());
var changeDoc = currentDB.createDocument();
changeDoc.replaceItemValue("Form","ChangeReport");
changeDoc.replaceItemValue("DateReported",reportDate);
var Change = Enumber + " " + Firstname + " " + Lastname + " no longer works at the district.";
changeDoc.replaceItemValue("Change",Change)
changeDoc.save();
}
var tmpentry:NotesViewEntry = vec.getNextEntry(entry);
entry.recycle();
entry = tmpentry;
if (i > 2000) {
print("Possible Loop HRMainX - breaking");
break;
}
i++
}
database.updateFTIndex(false);
//view.postScript("alert('Done checking teacher information.')");
viewScope.resultsCellVis = true;
//view.postScript("partialRefreshPost('#{id:WrapperPanel}')")
}]]></xp:this.action>
<xp:this.onComplete><![CDATA[XSP.partialRefreshGet("#{id:WrapperPanel}", {});]]></xp:this.onComplete>
</xp:eventHandler>
</xp:button>
Thanks for any pointers.
---Lisa&
I'm not sure if this will work, but it may be that it's caching the view content (effectively doing a setAutoUpdate(false) on the view). What may work is, instead of the onComplete event doing a partial refresh, adding a server-side call at the end of your SSJS to context.reloadPage(). That will recreate all the components again. Theoretically, I would expect that to dump it's cached version of the view and retrieve it from scratch. You should also be able to do this with a partial refresh rather than the complete refresh you currently have coded.
See this blog post I did explaining the differences between full refresh, context.reloadPage, context.redirectToPage() etc http://www.intec.co.uk/viewscope-full-refresh-reloadpage/.