Fill RadGridView dynamically - telerik

I am using RadControls for WinForms 2011 Q3
The datasource for a RadGridView is dynamically generated based on users' input/selection
Everytime when a datasource is generated, I will call SetDatasource2KeyValuesGrid()
What I expect to see is columns generated and values filled in gridview.
However what I see is columns generated but no value filled even though the number of rows in gridview match the number of items in its datasource(keyValuesList)
I must have missed something simple. Please help. thanks
Edit:
I create a DataTable from the list keyValueList, and then assign it to DataSource, then it works
Just wonder if there's a better way. thanks
private void CreateTableSetDatasource(List<FeedKeyValueOneSet>) keyValueList)
{
if(keyValueList==null) return;
var table = new DataTable();
table.Columns.Add("Check");
foreach (var feedKeyValueOneSet in keyValueList)
{
var oneset = feedKeyValueOneSet.KeyValueOneSet;
foreach (var oneKey in oneset)
{
table.Columns.Add(oneKey.key);
}
break;
}
foreach (var feedKeyValueOneSet in keyValueList)
{
var oneset = feedKeyValueOneSet.KeyValueOneSet;
var numOfCol = oneset.Length + 1;
var obj = new object[numOfCol];
obj[0] = "false";
int idx = 1;
foreach (var oneKey in oneset)
{
obj[idx] = oneKey.value;
idx++;
}
table.Rows.Add(obj);
}
radGridKeyValues.DataSource = table;
}
private void SetDatasource2KeyValuesGrid()
{
if (radGridKeyValues.Columns != null) radGridKeyValues.Columns.Clear();
radGridKeyValues.AutoGenerateColumns = false;
radGridKeyValues.EnableFiltering = false;
radGridKeyValues.ShowFilteringRow = false;
radGridKeyValues.ShowHeaderCellButtons = false;
radGridKeyValues.AllowDragToGroup = false;
radGridKeyValues.AllowAddNewRow = false;
radGridKeyValues.EnableGrouping = false;
var keyValueList = (List<FeedKeyValueOneSet>)TimeSeries.FeedValuesCache[m_strFeedName + "_KEYVALUES"];
if(keyValueList==null) return;
GridViewDataColumn checkBoxColumn = new GridViewCheckBoxColumn("columnState", "columnState");
checkBoxColumn.HeaderText = string.Empty;
if (radGridKeyValues.Columns != null) radGridKeyValues.Columns.Add(checkBoxColumn);
foreach (var feedKeyValueOneSet in keyValueList)
{
var oneset = feedKeyValueOneSet.KeyValueOneSet;
foreach (var oneKey in oneset)
{
var textboxCol = new GridViewTextBoxColumn(oneKey.key, oneKey.key);
textboxCol.Width = 150;
textboxCol.ReadOnly = true;
if (radGridKeyValues.Columns != null) radGridKeyValues.Columns.Add(textboxCol);
}
break;
}
radGridKeyValues.DataSource = keyValueList;
}
public class FeedKeyValueOneSet
{
public FeedFieldValues[] KeyValueOneSet;
}
public class FeedFieldValues
{
public string key { get; set; }
public string value { get; set; }
}

I create a DataTable from the list keyValueList, and then assign it to DataSource, then it works
see code in edit to the question

Related

Dynamics crm + how to get attribute value based on the type dynamically in plugin code

I have the below requirement.
I need to perform the sum of each field across multiple records of the same entity However while performing the sum, I also need to check the type and cast them accrodingly. For eg, For whole number cast to Int, For Decimal cast to decimal. Also some of the values are aliased value too. I am looking for a generic function which I can call for both alias fields and direct fields and it will return me the value based on the type
Background on the code written below -
Attribute List is the list of all attributes that belong to the
entity.
Format in which the field values are stored in AttributeList-
AttributeList = { "price ", "quantity", "contact.revenue", "opportunity.sales"}
price, quantity - fields of main entity on which we are querying
contact.revenue, opportunity.sales - fields of the aliased entities,
entity name is appended to understand which entity's field it is
Below is the code which i have tried so far -
I only have decimal and whole number fields in my attributeList.
private void calculate(List<string> attributeList,List<Entity> mainEntityList,Guid targetId,Guid oppId,Guid contactId)
{
var mainentity = new mainEntity();
mainentity.Id = targetId;
var opportunity = new Opportunity();
opportunity.Id = oppId;
var contact = new Contact();
contact.Id = contactId;
foreach (var attribute in attributeList)
{
var fieldSum = new decimal(0);
int intFieldSum = 0;
bool attributeFound = false;
foreach (var entity in mainEntityList)
{
if (entity.Contains(attribute))
{
var type = entity[attribute].GetType().Name;
attributeFound = true;
switch (type)
{
case "AliasedValue":
var aliasedFieldValue = entity.GetAttributeValue<AliasedValue>(attribute);
if (aliasedFieldValue.Value.GetType().Name == "Decimal")
{
decimalFieldSum += (decimal)aliasedFieldValue.Value;
}
else
{
intFieldSum += (int)aliasedFieldValue.Value;
}
break;
case "Decimal":
decimalFieldSum += entity.GetAttributeValue<decimal>(attribute);
break;
case "Int32":
intFieldSum += entity.GetAttributeValue<int>(attribute);
break;
default:
break;
}
}
}
if (attributeFound)
{
if (attribute.Contains("opportunity"))
{
opportunity[attribute] = decimalFieldSum != 0 ? decimalFieldSum : intFieldSum;
}
else if (attribute.Contains("contact"))
{
contact[attribute] = decimalFieldSum != 0 ? decimalFieldSum : intFieldSum;
}
else
{
mainentity[attribute] = decimalFieldSum != 0 ? decimalFieldSum : intFieldSum;
}
}
}
service.update(opportunity);
service.update(contact);
service.update(mainentity);
}
Any help would be appreciated.
Just a little bit edited your code.
...
var fieldSum = new decimal(0);
foreach (var entity in mainEntityList)
{
fieldSum += GetAttrValue(entity, attribute);
}
...
You can use this function to calculate fieldSum variable which is of decimal type.
private decimal GetAttrValue(Entity entity, string attribute)
{
var attrValue = new decimal(0);
if (!entity.Contains(attribute) || entity.Attributes[attribute] == null)
{
return attrValue;
}
var type = entity.Attributes[attribute].GetType().Name;
switch (type)
{
case "AliasedValue":
var aliasedFieldValue = entity.GetAttributeValue<AliasedValue>(attribute);
attrValue = type == "Decimal" ? (decimal)aliasedFieldValue.Value : (int)aliasedFieldValue.Value;
break;
case "Decimal":
attrValue = entity.GetAttributeValue<decimal>(attribute);
break;
case "Int32":
attrValue = entity.GetAttributeValue<int>(attribute);
break;
default:
break;
}
return attrValue;
}
On the other hand if you just need a generic function which will return decimal or int value for an attribute you can use this
private T GetAttrValue<T>(Entity entity, string attribute)
{
if (!entity.Contains(attribute) || entity.Attributes[attribute] == null)
{
return default(T);
}
T result;
var type = entity.Attributes[attribute].GetType().Name;
if (type == "AliasedValue")
{
var aliasedFieldValue = entity.GetAttributeValue<AliasedValue>(attribute);
result = (T)aliasedFieldValue.Value;
}
else
{
result = entity.GetAttributeValue<T>(attribute);
}
return result;
}
--Update--
So, here is the whole code if I understand you requirements right.
First of all add this class.
public class AttributeInfo
{
public string Name { get; set; }
public Type Type { get; set; }
public decimal DecimalSum { get; set; } = new decimal(0);
public int IntSum { get; set; } = 0;
}
And add this function
private void SetValue(Entity entity, AttributeInfo attributeInfo)
{
if (entity.Contains(attributeInfo.Name))
{
switch (attributeInfo.Type.Name)
{
case "Decimal":
entity[attributeInfo.Name] = attributeInfo.DecimalSum;
break;
case "Int32":
entity[attributeInfo.Name] = attributeInfo.IntSum;
break;
default:
break;
}
}
}
Then this is you Calculate function
private void Calculate(List<string> attributeList, List<Entity> mainEntityList, Guid targetId, Guid oppId, Guid contactId)
{
var mainentity = new mainEntity();
mainentity.Id = targetId;
var opportunity = new Opportunity();
opportunity.Id = oppId;
var contact = new Contact();
contact.Id = contactId;
var attributesInfo = new List<AttributeInfo>();
foreach (var attribute in attributeList)
{
var attributeInfo = new AttributeInfo
{
Name = attribute
};
foreach (var entity in mainEntityList)
{
if (entity.Contains(attribute))
{
attributeInfo.Type = entity[attribute].GetType();
switch (attributeInfo.Type.Name)
{
case "AliasedValue":
var aliasedFieldValue = entity.GetAttributeValue<AliasedValue>(attribute);
if (aliasedFieldValue.Value.GetType().Name == "Decimal")
{
attributeInfo.DecimalSum += (decimal)aliasedFieldValue.Value;
}
else
{
attributeInfo.IntSum += (int)aliasedFieldValue.Value;
}
break;
case "Decimal":
attributeInfo.DecimalSum += entity.GetAttributeValue<decimal>(attribute);
break;
case "Int32":
attributeInfo.IntSum += entity.GetAttributeValue<int>(attribute);
break;
default:
break;
}
}
}
attributesInfo.Add(attributeInfo);
}
foreach (var attributeInfo in attributesInfo)
{
if (attributeInfo.Type != null)
{
SetValue(mainentity, attributeInfo);
SetValue(opportunity, attributeInfo);
SetValue(contact, attributeInfo);
}
}
service.update(mainentity);
service.update(opportunity);
service.update(contact);
}
I should say that the structure of the calculate function still seems weird for me. However, here I tried to keep the main structure.

Accessing an extension method on a dbset subtype

I have an extension method defined as:
public static class CurrentItemExtensions
{
static GPOPricingEntities ctx = new GPOPricingEntities();
public static List<CurrentItem> Get(this DbSet<CurrentItem> item, int tierId, string contractId)
{
List<CurrentItem> items = ctx.Items.OfType<CurrentItem>().Where(x => x.TierId == tierId).ToList();
if (items == null)
{
GPOPricing.AS400Models.ItemCollection collection = new GPOPricing.AS400Models.ItemCollection().Get(contractId);
foreach (var c in collection)
{
CurrentItem target = new CurrentItem();
target.Price = c.DirectPriceEaches;
target.SKU = c.LongItemNbr;
target.Description = c.Description;
target.ProductLine = c.ProductLine;
items.Add(target);
}
}
else
{
foreach (var i in items)
{
GPOPricing.AS400Models.Item as400Item = new GPOPricing.AS400Models.ItemCollection().GetBySKU(i.SKU);
i.Description = as400Item.Description;
i.ProductLine = as400Item.ProductLine;
}
}
return items;
}
}
The problem I'm having is accessing it - CurrentItem is a subtype of Item. So I've tried:
db.Items.Get (doesn't work)
and I have tried
db.Items.OfType<CurrentItem>().Get (doesn't work)
Any suggestions?
I found that I had to use the base type and create a method for each subtype:
public static class CurrentItemExtensions
{
static GPOPricingEntities ctx = new GPOPricingEntities();
public static List<CurrentItem> GetCurrentItems(this DbSet<Item> item, int tierId, string contractId)
{
List<CurrentItem> items = ctx.Items.OfType<CurrentItem>().Where(x => x.TierId == tierId).ToList();
if (items.Count() == 0)
{
GPOPricing.AS400Models.ItemCollection collection = new GPOPricing.AS400Models.ItemCollection().Get(contractId);
foreach (var c in collection)
{
CurrentItem target = new CurrentItem();
target.Price = c.DirectPriceEaches;
target.SKU = c.LongItemNbr;
items.Add(target);
}
}
else
{
foreach (var i in items)
{
GPOPricing.AS400Models.Item as400Item = new GPOPricing.AS400Models.ItemCollection().GetBySKU(i.SKU);
}
}
return items;
}
}

ActionFilter to read Contents before RedirectToAction

I wish to record deletes and edits, and thought the best way would be to apply An actionFilter
Attribute to my delete and edit [ post ] methods
But because the end results is a redirect to action, my Context.Result is always null
because there is only a Context.RedirectToAction results available.
Now before i go creating some code to plug into my delete and Edit functions, has anyone tried something like this!, and could you possibly advise?
Thanks
Action Code:
[HttpPost, ValidateInput(false)]
[SiteChangeLogger(LogType = "Update", TableName = "Affiliates")]
public ActionResult Edit(Affiliate affiliate, FormCollection form)
{
var existing = db2.Affiliates.SingleOrDefault(x => x.AffiliateId == affiliate.AffiliateId);
ViewBag.before = Common.Strings.Base64Encode(Common.Strings.ToJsonString(existing));
if (ModelState.IsValid)
{
try
{
var curFiles = new NameValueCollection();
curFiles["AffiliateLogo"] = affiliate.AffiliateLogo;
if (!String.IsNullOrWhiteSpace(form["AffiliateLogo"]))
{
UploadFiles(form,curFiles);
TryUpdateModel(affiliate, form);
var oldFileName = affiliate.AffiliateLogo;
var newFileName = Common.Strings.RandomFileName();
new WebImage(Server.MapPath("~/Content/images/" + affiliate.AffiliateLogo))
.Resize(200, 50, true, true)
.Crop(1, 1)
.Save(Server.MapPath("~/Content/images/" + newFileName), "png", true);
affiliate.AffiliateLogo = newFileName + ".png";
Common.Common.TryAndDeleteFile("~/Content/images/" + oldFileName);
}
else
{
affiliate.AffiliateLogo = existing.AffiliateLogo;
}
}
catch (Exception ex)
{
Common.Common.CompileErrorMessage(ex,"ADMIN.Affiliate.Edit");
}
finally
{
db.Entry(affiliate).State = EntityState.Modified;
db.SaveChanges();
}
ViewBag.after = Common.Strings.Base64Encode(Common.Strings.ToJsonString(affiliate));
return RedirectToAction("Index");
}
return View(affiliate);
}
my Filter Code
public override void OnResultExecuted(ResultExecutedContext fc)
{
var viewResult = fc.Result as ViewResult;
if(viewResult == null) return;
var beforeData = viewResult.ViewBag.before;
var afterData = viewResult.ViewBag.after;
if (beforeData == null && afterData == null) return;
var ctx = new SgeGamesContext();
var eventId = 0;
var siteChangeLogEvent = ctx.SiteChangeLogEvents.SingleOrDefault(x => x.SiteChangeLogEventName == LogType);
if (siteChangeLogEvent != null)
{
eventId = siteChangeLogEvent.SiteChangeLogEventId;
}
var model = new Sge.Games.Data.Models.SiteChangeLog
{
SiteChangeLogTable = TableName,
SiteId = 1,
SiteChangeLogAfterContent = afterData,
SiteChangeLogBeforeContent = beforeData,
SiteChangeLogEventId = eventId
};
ctx.SiteChangeLogs.Add(model);
ctx.SaveChanges();
base.OnResultExecuted(fc);
}
You could access the ViewBag directly, you don't need a ViewResult:
public override void OnResultExecuted(ResultExecutedContext fc)
{
var before = fc.Controller.ViewBag.before;
var after = fc.Controller.ViewBag.after;
...
}
Also you probably want to use the OnActionExecuted event instead of OnResultExecuted.

Anonymous types in LINQ

I am using the following code to get a record from my database table tblDatabases. I then populate Controls on a Form based on the value. I have used some functions to get the values needed for displaying in a text box (e.g. the display value is different than the value.
The DetailData is an object in my base form class. Initially I just got the record from the table as is and I was able to cast the DetailData to the tblDatabases and use reflection to get all of the values for the data and populate the controls on my form.
I am no longer able to cast the DetailData to my table because of the anonymous types.
I would like to be able to use reflection on the DetailData to get the values.
Thanks,
Brad
DetailData = (from db in priorityDataContext.tblDatabases
where db.DatabaseID == Id
select new
{
db.DatabaseID,
db.DatabaseName,
db.Purpose,
db.BackEnd,
db.FrontEnd,
db.Version,
db.ProducesReports,
db.MultiUser,
db.UserDescription,
Developer = priorityDataContext.func_get_employee_name(db.Developer),
DeptOwner = priorityDataContext.func_get_dept_name(db.DeptOwner),
db.Source_Code_Path,
db.Notes,
db.Active,
db.row_entry_time_stamp,
row_oper_name = priorityDataContext.func_get_employee_name(db.Developer),
db.row_last_chng_time_stamp,
row_last_chng_oper_name = priorityDataContext.func_get_employee_name(db.Developer)
}).SingleOrDefault();
protected virtual void PopulateDetailControlsA(List<Control> controlContainers, string srcDataTableName)
{
switch (srcDataTableName)
{
case "tblDatabase" :
break;
}
var database = (tblDatabase) DetailData;
var type = typeof(tblDatabase);
var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (var controlContainer in controlContainers)
{
foreach (var propertyInfo in properties)
{
if (!ControlExists(controlContainer, propertyInfo.Name)) continue;
var txtExtControl = controlContainer.Controls[propertyInfo.Name] as ExtendedTextBox;
if (txtExtControl != null)
{
try
{
var value = propertyInfo.GetValue(database, null).ToString();
txtExtControl.Text = value;
}
catch (NullReferenceException)
{
}
continue;
}
var lnklblControl = controlContainer.Controls[propertyInfo.Name] as ExtendedLinkLabel;
if (lnklblControl != null)
{
try
{
var value = propertyInfo.GetValue(database, null).ToString();
lnklblControl.Text = value;
}
catch (NullReferenceException)
{
}
continue;
}
var chkControl = controlContainer.Controls[propertyInfo.Name] as ExtendedCheckBox;
if (chkControl != null)
{
try
{
var value = propertyInfo.GetValue(database, null).ToString();
switch (value)
{
case "True":
chkControl.CheckState = CheckState.Checked;
break;
case "False":
chkControl.CheckState = CheckState.Unchecked;
break;
}
}
catch (NullReferenceException)
{
chkControl.CheckState = CheckState.Indeterminate;
}
continue;
}
var cmbControl = controlContainer.Controls[propertyInfo.Name] as ExtendedComboBox;
if (cmbControl != null)
{
try
{
var value = propertyInfo.GetValue(database, null).ToString();
cmbControl.ValueMember = value;
}
catch (Exception ex)
{
}
continue;
}
}
}
}
What technology are you using for your UI? If you could use binding you would not need to worry about reflection on the anonymous type and then could also use converters if you need to format/calculate values from this.
From your response can't you just use the connection to the linq and then bind this to the combo box?
private void Form1_Load(object sender, System.EventArgs e)
{
var item = new DataClassesDataContext();
var stuff = item.Entity.Where(c => c.Property.Contains("something"));
comboBox1.DataSource = stuff;
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "PIN";
}

Sharepoint 2010 Custom Webpart - Access Denied Error

we've created a custom webpart to display announcements from all lists a user has access to, removing a few. The error we are having is that the webpart works fine on the page for the administrators, but when testing with regular user accounts, they are unable to see the page at all and are given a Access Denied error which is coming from the webpart itself.
Only when a user is added as a Site Collection Administrator they can see the page and have access to the webpart. What I'd like some advice on is how to be able to apply full read permissions to a select group within the code itself.
Below is the backend code
using System;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
namespace Test.TestWebPart
{
public partial class TestWebPartUserControl : UserControl
{
//Global variable call
private SPSite thisSite = SPContext.Current.Site;
private SPWebCollection thisWeb;
private DataTable dt;
private SPListCollection siteLists;
private DataTableWrapper myDataTable;
//Occurs when the page loads
protected void Page_Load(object sender, EventArgs e)
{
//Pulls all the websites in the site into a webcollection
thisWeb = thisSite.AllWebs;
//If the page is not postback call BindToGrid()
if (!Page.IsPostBack)
{
BindToGrid();
}
}
private void BindToGrid()
{
//Create a new DataTable along with the columns and headers
dt = new DataTable();
dt.Columns.Add("Title");
dt.Columns.Add("Created");
dt.Columns.Add("List");
//Call to populate the DataTable
dt = SelectData();
//Populate DataTableWrapper class and get the type
myDataTable = new DataTableWrapper(dt);
Type t = myDataTable.GetType();
//Create a ObjectDataSource to hold data and bind to spgridview
ObjectDataSource ds = new ObjectDataSource();
ds.ID = "myDataSource";
ds.TypeName = t.AssemblyQualifiedName;
ds.SelectMethod = "GetTable";
ds.ObjectCreating += new ObjectDataSourceObjectEventHandler(ds_ObjectCreating);
this.Controls.Add(ds);
grid.ID = "gridID";
BoundField column = new BoundField();
column.DataField = "Title";
column.HtmlEncode = false;
//column.SortExpression = "Title";
column.HeaderText = "Title";
grid.Columns.Add(column);
BoundField column1 = new BoundField();
column1.DataField = "Created";
column1.HtmlEncode = true;
//column1.SortExpression = "Created";
column1.HeaderText = "Created";
grid.Columns.Add(column1);
BoundField column2 = new BoundField();
column2.DataField = "List";
column2.HtmlEncode = false;
//column2.SortExpression = "List";
column2.HeaderText = "List";
grid.Columns.Add(column2);
//Provide the SPGridview with the DataSource
grid.DataSourceID = "myDataSource";
this.Controls.Add(grid);
//grid.PageSize =10;
//grid.AllowPaging = true;
//Default Pagination - commented out due to not working
//grid.PageIndexChanging += new GridViewPageEventHandler(grid_PageIndexChanging);
//grid.PagerTemplate = null;
//Bind the data to the grid
grid.DataBind();
}
//private void GenerateColumns()
//{
//}
//Used to deal with the PageIndexChange event
void grid_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grid.PageIndex = e.NewPageIndex;
grid.DataBind();
}
//Used to deal with the ObjectCreated event
void ds_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
{
myDataTable = new DataTableWrapper(dt);
e.ObjectInstance = myDataTable;
}
//Pulls the data from lists which will be displayed
public DataTable SelectData()
{
try
{
//Create a new instance of type DataRow
DataRow row;
//Loop through each website in the webcollection
foreach (SPWeb web in thisWeb)
{
//Pull the lists from the site into a list collection
siteLists = web.Lists;
//Display only lists the current user has access to
siteLists.ListsForCurrentUser = true;
//Loop through each list within the list collection
foreach (SPList list in siteLists)
{
//If the list is an announcement list continue otherwise skip
if (list.BaseTemplate.ToString() == "Announcements")
{
//Exclude the lists stated from those whose data will be collected
if (list.Title.ToString() == "Bulletins" || list.Title.ToString() == "The Buzz - Curriculum" || list.Title.ToString() == "The Buzz - Personal" || list.Title.ToString() == "The Buzz - Support" || list.Title.ToString() == "Critical Annoucements")
{
}
else
{
//Create a item collection for each item within the current list
SPListItemCollection listItem = list.Items;
//Loop through each item within the item collection
foreach (SPListItem item in listItem)
{
//Get the url of the current website
string weburl = web.Url;
//Gets the URL of the current item
string dispurl = item.ContentType.DisplayFormUrl;
dispurl = list.Forms[PAGETYPE.PAGE_DISPLAYFORM].Url;
//Joins together the full URL for the current item into a single variable
dispurl = string.Format("{0}/{1}?ID={2}", weburl, dispurl, item.ID);
//Create a new in the datatable as an instance of row
row = dt.Rows.Add();
//Put the correct information and links into the correct column
row["Title"] = "<a target=_blank href=\"" + dispurl + "\">" + item["Title"].ToString() + "</a>";
row["Created"] = item["Created"].ToString();
row["List"] = "<a target=_blank href=\"" + list.DefaultViewUrl + "\">" + list.Title + "</a>";
}
}
}
}
}
//Return the completed DataTable
return dt;
}
//Exception to catch any errors
catch (Exception s)
{
return dt;
}
}
}
}
Thanks
thisWeb = thisSite.AllWebs;
This code requires Administrator previliges. Run it under Elevated Previleges:
http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spsecurity.runwithelevatedprivileges.aspx
Based on the above comments and edited changes, here is the full working code, encase anyone was wondering:-
using System;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
namespace Test.TestWebPart
{
public partial class TestWebPartUserControl : UserControl
{
//Global variable call
private SPSite thisSite = SPContext.Current.Site;
//private SPWebCollection thisWeb;//
private SPWeb thisWeb = SPContext.Current.Web;
private DataTable dt;
private SPListCollection siteLists;
private DataTableWrapper myDataTable;
//Occurs when the page loads
protected void Page_Load(object sender, EventArgs e)
{
//Pulls all the websites in the site into a webcollection
//thisWeb = thisSite.AllWebs.;//
//If the page is not postback call BindToGrid()
if (!Page.IsPostBack)
{
BindToGrid();
}
}
private void BindToGrid()
{
//Create a new DataTable along with the columns and headers
dt = new DataTable();
dt.Columns.Add("Title");
dt.Columns.Add("Created");
dt.Columns.Add("List");
//Call to populate the DataTable
dt = SelectData();
//Populate DataTableWrapper class and get the type
myDataTable = new DataTableWrapper(dt);
Type t = myDataTable.GetType();
//Create a ObjectDataSource to hold data and bind to spgridview
ObjectDataSource ds = new ObjectDataSource();
ds.ID = "myDataSource";
ds.TypeName = t.AssemblyQualifiedName;
ds.SelectMethod = "GetTable";
ds.ObjectCreating += new ObjectDataSourceObjectEventHandler(ds_ObjectCreating);
this.Controls.Add(ds);
grid.ID = "gridID";
//Sorting, Filtering & paging does not work so has been commented out for now
//this.grid.AllowSorting = true;
//Bind the three columns to the SPGridView
//HtmlEncode must be false for the links to appear as true html
BoundField column = new BoundField();
column.DataField = "Title";
column.HtmlEncode = false;
//column.SortExpression = "Title";
column.HeaderText = "Title";
grid.Columns.Add(column);
BoundField column1 = new BoundField();
column1.DataField = "Created";
column1.HtmlEncode = true;
//column1.SortExpression = "Created";
column1.HeaderText = "Created";
grid.Columns.Add(column1);
BoundField column2 = new BoundField();
column2.DataField = "List";
column2.HtmlEncode = false;
//column2.SortExpression = "List";
column2.HeaderText = "List";
grid.Columns.Add(column2);
//Has been commented out due to these sections not working
//grid.AllowFiltering = true;
//grid.FilterDataFields = "Title";
//grid.FilteredDataSourcePropertyName = "FilterExpression";
//grid.FilteredDataSourcePropertyFormat = "{1} like '{0}'";
//grid.FilterDataFields = "Created";
//grid.FilteredDataSourcePropertyName = "FilterExpression";
//grid.FilteredDataSourcePropertyFormat = "{1} like '{0}'";
//grid.FilterDataFields = "ListName";
//grid.FilteredDataSourcePropertyName = "FilterExpression";
//grid.FilteredDataSourcePropertyFormat = "{1} like '{0}'";
//Provide the SPGridview with the DataSource
grid.DataSourceID = "myDataSource";
this.Controls.Add(grid);
//grid.PageSize =10;
//grid.AllowPaging = true;
//Default Pagination - commented out due to not working
//grid.PageIndexChanging += new GridViewPageEventHandler(grid_PageIndexChanging);
//grid.PagerTemplate = null;
//Bind the data to the grid
grid.DataBind();
}
//private void GenerateColumns()
//{
//}
//Used to deal with the PageIndexChange event
void grid_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
grid.PageIndex = e.NewPageIndex;
grid.DataBind();
}
//Used to deal with the ObjectCreated event
void ds_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
{
myDataTable = new DataTableWrapper(dt);
e.ObjectInstance = myDataTable;
}
//Pulls the data from lists which will be displayed
public DataTable SelectData()
{
try
{
//Create a new instance of type DataRow
DataRow row;
//Loop through each website in the webcollection
{
//Pull the lists from the site into a list collection
siteLists = thisWeb.Lists;
//Display only lists the current user has access to
siteLists.ListsForCurrentUser = true;
SPBasePermissions perms = SPBasePermissions.ViewListItems;
//Loop through each list within the list collection
foreach (SPList list in siteLists)
{
if (list.DoesUserHavePermissions(perms))
{
//If the list is an announcement list continue otherwise skip
if (list.BaseTemplate.ToString() == "Announcements")
{
//Exclude the lists stated from those whose data will be collected
if (list.Title.ToString() == "The Buzz" || list.Title.ToString() == "Test 2 list")
{
}
else
{
//Create a item collection for each item within the current list
SPListItemCollection listItem = list.Items;
//Loop through each item within the item collection
foreach (SPListItem item in listItem)
{
//Get the url of the current website
string weburl = thisWeb.Url;
//Gets the URL of the current item
string dispurl = item.ContentType.DisplayFormUrl;
dispurl = list.Forms[PAGETYPE.PAGE_DISPLAYFORM].Url;
//Joins together the full URL for the current item into a single variable
dispurl = string.Format("{0}/{1}?ID={2}", weburl, dispurl, item.ID);
//Create a new in the datatable as an instance of row
row = dt.Rows.Add();
//Put the correct information and links into the correct column
row["Title"] = "<a target=_blank href=\"" + dispurl + "\">" + item["Title"].ToString() + "</a>";
row["Created"] = item["Created"].ToString();
row["List"] = "<a target=_blank href=\"" + list.DefaultViewUrl + "\">" + list.Title + "</a>";
}
}
}
}
}
}
//Return the completed DataTable
return dt;
}
//Exception to catch any errors
catch (Exception s)
{
return dt;
}
}
}
}
SPWeb.GetSubwebsForCurrentUser() should be used. It gets SubWebs that current user has access to. Avoid using ElevatedPriveleges until you absolutely need it.

Resources