viewpanel not showing the latest data - xpages

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/.

Related

How to solve report generation issue on Azure?

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.

Async calls in c#

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
}

prevent double meeting sharepoint calendar csom

I am trying to make it if the date and time are already booked in the calender dont book, i am using this code and nothing get displayed? Any Sugestions?
var context = SP.ClientContext.get_current();
var web = context.get_web();
var list = web.get_lists();
var targetList;
function createItem() {
targetList = list.getByTitle("AppbokningarList");
var listItemCreation = new SP.ListItemCreationInformation();
var newItem = targetList.addItem(listItemCreation);
var listItemTitle = document.getElementById('Textrubrik').value;
alert(listItemTitle);
var listItemCustom = document.getElementById('datepicker').value;
alert(listItemCustom);
var listItemFromTime = document.getElementById('timepicker').value;
alert(listItemFromTime);
var listItemtoDate = document.getElementById('datepickerto').value;
alert(listItemtoDate);
var listItemToTime = document.getElementById('timepickerTo').value;
alert(listItemToTime);
var listItemBeskrivning = document.getElementById('Textbeskrivning').value;
alert(listItemBeskrivning);
newItem.set_item('Title', listItemTitle);
var result = listItemCustom + " " + listItemFromTime;
newItem.set_item('EventDate', result);
var result2 = listItemtoDate + " " + listItemToTime;
newItem.set_item('EndDate', result2);
newItem.set_item('Description', listItemBeskrivning);
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml("<Where><Geq><FieldRef Name='EventDate' /><Value Type='DateTime'>" + result + "</Value></Geq><Leq><FieldRef Name='EndDate' /><Value Type='DateTime'>" + result2 + "</Value></Leq><FieldRef Name='RecurrenceID' /></Where>");
this.collListItem = targetList.getItems(camlQuery);
context.load(collListItem);
var property = new SP.EventProperties();
if (collListItem > 0) {
property.cancel = true;
}
newItem.update();
context.load(newItem);
context.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded),Function.createDelegate(this, this.onQueryFailed));
}
function onQuerySucceeded(sender, args) {
var succeded = "Mötet är nu bokat!";
alert(succeded);
}
function onQueryFailed(sender, args) {
var failed = "Redan bokat!";
alert(failed);
}
Look at all your set_items. Most likely your date fields need an actual date object to be stored successfully to SP.
var currDate = new Date();
listItem.set_item('DateColumn',currDate);
listItem.update();
Cool stuff here to: http://alexeybbb.blogspot.com/2012/09/sharepoint15-js-update-datetime-field.html

Xpages search displaying docs & responses

I'm trying to filter a viewPanel using its search property. The viewPanel hasn't any categorized column.
These documents are using readers and authors fields. One problem is the fact that I'm getting some empty rows in views representing the "hidden" documents.
The filter input fields are all contained in Doc. type, and as well in Response type.
var tmpArray = new Array("");
var cTerms = 0;
var dateFormatter = new java.text.SimpleDateFormat( "MM-dd-yyyy" );
if (sessionScope.compA) {
tmpArray[cTerms++] = "(Field Comp = \"*" + sessionScope.compA + "*\")";
tmpArray[cTerms++] = "(Field Compania = \"*" + sessionScope.compA + "*\")";
/* Comp - the field from Doc. & Compania - the field from Response */
}
if (sessionScope.numePro) {
tmpArray[cTerms++] = "(Field NumeProiect = \"*" + sessionScope.numePro + "*\")";
tmpArray[cTerms++] = "(Field Proiect = \"*" + sessionScope.numePro + "*\")";
/* NumeProiect - the field from Doc. & Proiect - the field from Response */
}
if (sessionScope.din && sessionScope.pana) {
tmpArray[cTerms++] = "Field _creationDate >= " + dateFormatter.format(sessionScope.din) + " AND Field _creationDate <= " + dateFormatter.format(sessionScope.pana);
}
qstring = tmpArray.join(" OR ").trim();
sessionScope.queryString = qstring;
return qstring
But I don't get the expected results, I do get something like: the correct documents for sessionScope.compA, but if I add a value for the 2nd sessionScope.numePro which isn't contained in any documents listed by the view, the results are the same, and there should be no result.
How can I achieve this?
My guess is that you just mixed up the logical connection between the ftsearch parts. The following code should work for you:
var tmpArray = new Array("");
var cTerms = 0;
var dateFormatter = new java.text.SimpleDateFormat( "MM-dd-yyyy" );
if (sessionScope.compA) {
tmpArray[cTerms++] = "((Field Comp = \"*" + sessionScope.compA + "*\") OR " +
"(Field Compania = \"*" + sessionScope.compA + "*\"))";
/* Comp - the field from Doc. & Compania - the field from Response */
}
if (sessionScope.numePro) {
tmpArray[cTerms++] = "((Field NumeProiect = \"*" + sessionScope.numePro + "*\") OR " +
"(Field Proiect = \"*" + sessionScope.numePro + "*\"))";
/* NumeProiect - the field from Doc. & Proiect - the field from Response */
}
if (sessionScope.din && sessionScope.pana) {
tmpArray[cTerms++] = "Field _creationDate >= " + dateFormatter.format(sessionScope.din) +
" AND Field _creationDate <= " + dateFormatter.format(sessionScope.pana);
}
qstring = tmpArray.join(" AND ").trim();
sessionScope.queryString = qstring;
return qstring

jquery dynamically create html table and bind sharepoint list items in it

I have scenario where i need to bind sharepoint list to the dynamically cretaed html table and use the jquery in content editor webpart to show the table in site.Please help me with this regards.I am using sharepoint 2010.Thanks in advance.
I was trying something here but no luck please help me around with this.Thanksenter code here
<script type="text/javascript" language="javascript">
var _clientContext;
var _web;
alert("Working")
//ExecuteOrDelayUntilScriptLoaded(RetrieveListItems, "sp.js");
function RetrieveListItems() {
alert("Test");
_clientContext = new SP.ClientContext.get_current();
alert(Context);
_web = _clientContext.get_web();
alert(web);
var list = _web.get_lists().getByTitle('Planning Partners');
alert(list);
// var camlQuery = new SP.CamlQuery();
var myquery = new SP.CamlQuery.createAllItemsQuery();
allItems = list.getItems(myquery);
_clientContext.load(allItems);
_clientContext.executeQueryAsync(Function.createDelegate(this, this.success), Function.createDelegate(this, this.failed));
}
function success() {
var Image = null;
var Linkurl = null;
var Title = null;
// var sHtml = "";
alert("success");
var ListEnumerator = this.allItems.getEnumerator();
while (ListEnumerator.moveNext()) {
var currentItem = ListEnumerator.get_current();
Image = currentItem.get_item('Image');
Linkurl = currentItem.get_item('Linkurl');
Title = currentItem.get_item('Title');
//var tbl = document.createElement("tbl");
var row = document.createElement("tr");
var $table = $('<table>');
$table.append('<caption>MyTable</caption>')
$table.append('<thead>');
$table.append('<tr>');
if (Image != oListItem.get_item('Image')) {
var cell = document.createElement("td");
var cellText = document.createElement("<image imgurl='" + oListItem.get_item('Image') + "'></Image>");
cell.appendChild(cellText);
row.appendChild(cell);
}
if (Linkurl != oListItem.get_item('Linkurl')) {
var cell = document.createElement("td");
var cellText = document.createElement("<a target='_blank' href ='" + oListItem.get_item('Linkurl') + "'>" + oListItem.get_item('Title') + "</a>");
cell.appendChild(cellText);
row.appendChild(cell);
}
if (Title != oListItem.get_item('Title')) {
var cell = document.createElement("td");
var cellText = document.createElement("<p>" + Title + "</p>");
cell.appendChild(cellText);
row.appendChild(cell);
}
$table.append('</tr>');
$table.append('</thead>');
tblBody.appendChild(row);
tbl.appendChild(tblBody);
body.appendchild(tbl);
}
}
// sHtml += '<table><tr><td><img src="' + Image + '" height="55px" width="55px"></td><td><table><tr><td valign="top"><div class="fieldsTitle">' + Linkurl + '</div></td></tr><tr><td valign="top">' + Title + 'Read More >></td></tr><tr><td></td></tr></table></td></tr></table>';
// document.getElementById('MainDiv').innerHTML = sHtml;
// }
function failed(sender, args) {
alert("failed Message" + args.gte_message());
}
</script>
Instead of creating elements through JavaScript, simply create a variable to store theHTML tags and finally add on page using Jquery. Use below script, hope this will help you.
If "Image" and "Linkurl" are HyperLink or Picture Column then use currentItem.get_item('Image').get_url() . I think this was the issue in your case :)
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js "></script>
<script type="text/javascript" language="javascript">
var _clientContext;
var _web;
ExecuteOrDelayUntilScriptLoaded(RetrieveListItems, "sp.js");
function RetrieveListItems() {
_clientContext = new SP.ClientContext.get_current();
_web = _clientContext.get_web();
var list = _web.get_lists().getByTitle('Planning Partners');
var myquery = new SP.CamlQuery.createAllItemsQuery();
allItems = list.getItems(myquery);
_clientContext.load(allItems);
_clientContext.executeQueryAsync(Function.createDelegate(this, this.success), Function.createDelegate(this, this.failed));
}
function success() {
var Image = null;
var Linkurl = null;
var Title = null;
var txtHTML = "";
var ListEnumerator = this.allItems.getEnumerator();
while (ListEnumerator.moveNext()) {
var currentItem = ListEnumerator.get_current();
Image = currentItem.get_item('Image');
Linkurl = currentItem.get_item('Linkurl');
Title = currentItem.get_item('Title');
var row = document.createElement("tr");
txtHTML = txtHTML + "<tr>";
txtHTML = txtHTML + "<td>";
if (Image != null) {
txtHTML = txtHTML + "<image src='" + Image.get_url() + "'></Image>";
}
txtHTML = txtHTML + "</td>";
txtHTML = txtHTML + "<td>";
if (Linkurl != null) {
txtHTML = txtHTML + "<a target='_blank' href ='" + Linkurl.get_url() + "'>" + Title + "</a>";
}
txtHTML = txtHTML + "</td>";
txtHTML = txtHTML + "<td>";
if (Title != null) {
txtHTML = txtHTML + "<p>" + Title + "</p>";
}
txtHTML = txtHTML + "</td>";
txtHTML = txtHTML + "</tr>";
}
$("#tblCustomListData").append(txtHTML);
}
function failed(sender, args) {
alert("failed Message" + args.gte_message());
}
</script>
<table id="tblCustomListData" border="1">
<thead>
<tr>
<th>Image
</th>
<th>Linkurl
</th>
<th>Title
</th>
</tr>
</thead>
</table>

Resources