Sharepoint: Binding GridView with SharePoint List (Client Object Model) - asp.net

I want to show a list on an .aspx site. Therefore I have to use the SP client object model.
I found the following tutorial, but this doesn't use the client libraries:
http://social.technet.microsoft.com/wiki/contents/articles/30287.binding-gridview-with-sharepoint-list.aspx
My code so far looks the following:
ClientContext clientContext = GetContext(accessToken);
Web web = clientContext.Web;
clientContext.Load(web);
clientContext.ExecuteQuery();
// Get the email input list.
List inboxList = web.Lists.GetByTitle("InboxList");
Microsoft.SharePoint.Client.ListItemCollection items = inboxList.GetItems(new CamlQuery());
clientContext.Load(inboxList);
clientContext.Load(items, ic => ic.Include(i => i["DisplayName"], i => i["Client_Title"], i => i["HasUniqueRoleAssignments"]));
clientContext.ExecuteQuery();
foreach (Microsoft.SharePoint.Client.ListItem i in items)
{
clientContext.Load(i);
}
clientContext.ExecuteQuery();
oGrid.DataSource = items;
oGrid.DataBind();
But this shows only some "meta data" of the list item collection, see screenshot:
If I use oGrid.DataSource = inboxList; I get an InvalidOperationException because the data source isn't type of IListSource, IEnumerable nor IDataSource.
If I use oGrid.DataSource = inboxList.DataSource; I get an PropertyOrFieldNotInitializedException, but I don't know how to load this attribute (via clientContext.Load it didn't work)?!

I got it - works with following code:
protected void Page_Load(object sender, EventArgs e)
{
...
ClientContext clientContext = GetContext(accessToken);
Web web = clientContext.Web;
clientContext.Load(web);
clientContext.ExecuteQuery();
// Get the email input list.
List inboxList = web.Lists.GetByTitle("InboxList");
Microsoft.SharePoint.Client.ListItemCollection items = inboxList.GetItems(new CamlQuery());
clientContext.Load(inboxList);
clientContext.Load(items);
clientContext.ExecuteQuery();
foreach (Microsoft.SharePoint.Client.ListItem i in items)
{
clientContext.Load(i);
}
clientContext.ExecuteQuery();
oGrid.DataSource = GetInboxListData(inboxList, items);
oGrid.DataBind();
}
else if (!IsPostBack)
{
Response.Write("Could not find a context token.");
return;
}
}
private DataTable GetInboxListData(List inboxList, Microsoft.SharePoint.Client.ListItemCollection items)
{
DataTable dt = new DataTable();
dt.Columns.Add("From");
dt.Columns.Add("To");
dt.Columns.Add("Subject");
dt.Columns.Add("Body");
dt.Columns.Add("Attachments");
dt.Columns.Add("Sent");
DataRow row;
foreach(Microsoft.SharePoint.Client.ListItem item in items)
{
row = dt.Rows.Add();
row["From"] = item["From1"].ToString();
row["To"] = item["To"].ToString();
row["Subject"] = item["Subject1"].ToString();
row["Body"] = item["Body1"].ToString();
row["Attachments"] = item["Attachments"].ToString();
row["Sent"] = item["Sent"].ToString();
}
return dt;
}
This is similar to Retrieve the values from a list to Gridview in SharePoint Webpart? but with client object model methods & objects.

Related

how to get json data from api in listview paging

i want to get data from web api in listview with paging. What i have done so far i dont see any problem in my code but i am getting null values in Handle_OnDemandLoading
private FeaturedItemList products = new FeaturedItemList();
protected async void FeaturedList()
{
var httpClient = new HttpClient();
var json = await httpClient.GetStringAsync("http://orangepotato.rjcpacking.com/index.php?route=api/login/getFeaturedProducts");
products = JsonConvert.DeserializeObject<FeaturedItemList>(json);
dataPager.Source = products.products;
}
void Handle_OnDemandLoading(object sender, Syncfusion.SfDataGrid.XForms.DataPager.OnDemandLoadingEventArgs e)
{
var source= products.products.Skip(e.StartIndex).Take(e.PageSize);
FeaturedlistView.ItemsSource = source.AsEnumerable();// here is i am getting null values but i am getting values in datapager.source
}

Report localization in Telerik self hosted service (.trdx)

I have telerik REST web API(ASP.NET ) which is working fine. Now I need to localize the reports (report are in .trdx extension).
From documentation of telerik I found the code which have place in my BaseTelerikReportsController but this also not working, and even not show any error.
Telerik Localization Documentation
public class BaseTelerikReportsController : ReportsControllerBase
{
static readonly Telerik.Reporting.Services.ReportServiceConfiguration ConfigurationInstance;
static BaseTelerikReportsController()
{
var resolver = new CustomReportResolver();
//Create new CultureInfo
var cultureInfo = new System.Globalization.CultureInfo("aa-iq"); //<-- Line 1
// Set the language for static text (i.e. column headings, titles)
System.Threading.Thread.CurrentThread.CurrentUICulture = cultureInfo; //<-- Line 2
var reportsPath = HttpContext.Current.Server.MapPath("~/Reports");
ConfigurationInstance = new Telerik.Reporting.Services.ReportServiceConfiguration
{
HostAppId = "TBReportApp",
ReportResolver = resolver,
// ReportResolver = new ReportFileResolver(reportsPath),
Storage = new Telerik.Reporting.Cache.File.FileStorage(),
};
}
public BaseTelerikReportsController()
{
ReportServiceConfiguration = ConfigurationInstance;
}
}
Note
There is a similar question but don't guide me to any right direction Here
Update 1
I have added below function in Global.asax.cs.
protected void Application_AcquireRequestState(object sender, EventArgs e)
{
//Create new CultureInfo
var cultureInfo = new System.Globalization.CultureInfo("ar");
// Set the language for static text (i.e. column headings, titles)
System.Threading.Thread.CurrentThread.CurrentUICulture = cultureInfo;
// Set the language for dynamic text (i.e. date, time, money)
System.Threading.Thread.CurrentThread.CurrentCulture = cultureInfo;
}
After above line (see image) data under red mark is localize but i need to localize yellow one(i.e heading)
I figure out how to localize the report header. Following are the some summarized steps.
Add App_GlobalResources folder and .resx accordingly your languages (See the figure 1-1).
Send language attribute from 'HTML5 Viewer'.
var viewer = $("#report-viewer").data("telerik_ReportViewer");
var model = {
//other attributes
Language: this.selectedLanguage //Here value may be ,en Or ar
};
viewer.reportSource({
report: reportSettings,
parameters: model
});
On server side based on that attribute change label accordingly.
private static void Localization(ref Report reportInstance)
{
ResourceManager currentResource = null;
switch (_language)
{
case "en":
currentResource = new ResourceManager("Resources.en", System.Reflection.Assembly.Load("App_GlobalResources"));
break;
case "ar":
currentResource = new ResourceManager("Resources.ar", System.Reflection.Assembly.Load("App_GlobalResources"));
break;
}
// var MyResourceClass = new ResourceManager("Resources.ar", System.Reflection.Assembly.Load("App_GlobalResources"));
ResourceSet resourceSet = currentResource.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
foreach (DictionaryEntry entry in resourceSet)
{
string key = entry.Key.ToString();
string value = entry.Value.ToString();
var items = reportInstance.Items.Find(key,true);
foreach (var singleItem in items)
{
var singleItemType = singleItem.GetType();
//if (singleItem.GetType().FullName == "") ;
if (singleItemType.FullName == "Telerik.Reporting.TextBox")
{
var castItem = (Telerik.Reporting.TextBox) singleItem;
castItem.Value = value;
}
}
}
}
On Telerik Standalone Report Designer
Change your report(.trdx) Textbox value which matches your .resxname value pair.
Resource file values

How to put xml code for a subreport in xtrareport devexpress?

I created a master report file. Then I created subreport file. Is there a way to put xml code of the subreport file as a report source ?
Override OnBeforePrint method and go through XtraReportBase.Controls property tree to find XRSubreport. As described here you can use DataSet and its DataSet.ReadXml method:
protected override void OnBeforePrint(PrintEventArgs e)
{
base.OnBeforePrint(e);
//Get your xml here
var dataSet = new DataSet();
using (var reader = new StringReader(xml))
dataSet.ReadXml(reader);
SetSubReportXML(this, dataSet);
}
private void SetSubReportXML(XRControl xrControl, DataSet dataSet)
{
foreach (XRControl xrControlChild in xrControl.Controls)
{
var subReport = xrControlChild as XRSubreport;
if (subReport != null)
{
//Set your xml here
subReport.ReportSource.DataSource = dataSet;
subReport.ReportSource.DataMember = this.DataMember;
SetSubReportXML(subReport.ReportSource, dataSet);
}
SetSubReportXML(xrControlChild, dataSet);
}
}

Returning Arraylist from recursive function for ASP.Net

Please refer the attached screenshot. I have an array of the checkbox and a button for the post back in ASP.Net page. I have written a function as follows to determine what all check boxes have been checked on the button click event: The following code is a part of the business component which is called from ASP.Net. Please let me know how can I return actionArray back to calling functon in ASP.Net page.
public void checkBoxValidation(Control parent, string strKey)
{
XmlDocument getCyleXML = new XmlDocument();
string strChkID="", strActionXPath = "",strAction="";
ArrayList actionArray = new ArrayList();
// Loop through all the controls on the page
foreach (Control c in parent.Controls)
{
// Check and see if it's a checkbox.
if ((c.GetType() == typeof(CheckBox)))
{
// Since its a checkbox, see if this is checked.
if (((CheckBox)(c)).Checked == true)
{
// Find the ID of the checkbox
strChkID = ((CheckBox)(c)).ID.ToString();
getCyleXML = CycleXML(strKey);
strActionXPath = "/Actions/Action[checkbox='" + strChkID + "']/*[self::Name]";
strAction = getCyleXML.SelectSingleNode(strActionXPath).ToString();
actionArray.Add(strAction);
}
}
// Now we need to call itself (recursion) because all items (Panel, GroupBox, etc) is a container so we need to check
// all containers for any checkboxes.
if (c.HasControls())
{
checkBoxValidation(c, strKey);
}
}
}
The code should be like this :
public ArrayList checkBoxValidation(Control parent, string strKey, ArrayList actionArray)
{
XmlDocument getCyleXML = new XmlDocument();
string strChkID="", strActionXPath = "",strAction="";
if(actionArray == null) { actionArray = new ArrayList(); }
// Loop through all the controls on the page
foreach (Control c in parent.Controls)
{
// Check and see if it's a checkbox.
if ((c.GetType() == typeof(CheckBox)))
{
// Since its a checkbox, see if this is checked.
if (((CheckBox)(c)).Checked == true)
{
// Find the ID of the checkbox
strChkID = ((CheckBox)(c)).ID.ToString();
getCyleXML = CycleXML(strKey);
strActionXPath = "/Actions/Action[checkbox='" + strChkID + "']/*self::Name]";
strAction = getCyleXML.SelectSingleNode(strActionXPath).ToString();
actionArray.Add(strAction);
}
}
// Now we need to call itself (recursion) because all items (Panel, GroupBox, etc) is a container so we need to check
// all containers for any checkboxes.
if (c.HasControls())
{
checkBoxValidation(c, strKey, actionArray);
}
}
return actionArray;
}

Functionality of not working user control not working on Sharepoint 2007 List Edit.aspx

I have deployed a user control on sharepoint 2007 list Edit.aspx page. It is working fine on my test server but on production only the UI of the user control is loaded. No textbox or combo box on page load are getting filled. Please see the screen shot of default values of user control instead of the filled up data. Also find the code below which takes the ID from querystring and loads the required data on page load. I have used createdby value to check who is assigning the list item. If the user is accessing the data which is not created by him then its redirected to other page.Please guide me. What shall I do or check to make it work.
public partial class Class1 : System.Web.UI.UserControl
{
static string name, lname, Number;
protected void Page_Load(object sender, EventArgs e)
{
try
{
string c1,c2,c3,c4,c5, Created;
if (!Page.IsPostBack)
{
EditID = Convert.ToInt32(Request.QueryString["ID"]);
name = SPContext.Current.Web.CurrentUser.Name;
lname = SPContext.Current.Web.CurrentUser.LoginName;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite("site name"))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists["list1"];
SPList UserSkill = web.Lists["list2"];
ItemForEdit = UserSkill.GetItemById(EditID);
c1 = ItemForEdit["col1"].ToString();
c2 = ItemForEdit["col2"].ToString();
c3 = ItemForEdit["col3"].ToString();
c4 = ItemForEdit["col4"].ToString();
c5 = ItemForEdit["col5"].ToString();
Created = ItemForEdit["Author"].ToString();
Number = ItemForEdit["col6"].ToString();
string[] extract;
extract = Created.Split('#');
if (name == extract[1])
{
WholeData = web.Lists["list1"].Items.GetDataTable();
Roles = WholeData.DefaultView.ToTable(true, "Title");
txtnumber.Text = Number;
ddlRole.DataSource = Roles;
ddlRole.DataTextField = "Title";
ddlRole.DataValueField = "Title";
ddlRole.DataBind();
ddlRole.SelectedValue = c1;
//more code
}
else
{
Response.Redirect("/IM/pages/Intrusion.aspx", false);
}
}
}
});
}
}
catch (Exception exc)
{
HttpContext.Current.Response.Write("<script>alert('Exception on page load: " + exc.Message + "')</script>");
}
}
}
It looks at first cut to be a data issue.
To debug on your production box you can use a remote debugger, or you could add a call that checks if 0 items are returned and either product an error or log the result.

Resources