Related
Can anyone help me find where in the code Acumatica writes to the CRRelation table when createing a Sales Order from an Opportunity? I've done a search for all instances of "CRRelation" but none of them seem to be doing the actual writing to the table.
It is done in the DoCreateSalesOrder(CreateSalesOrderFilter param) method which is called in the CreateSalesOrder action:
public PXAction<CROpportunity> createSalesOrder;
[PXUIField(DisplayName = Messages.CreateSalesOrder, MapEnableRights = PXCacheRights.Update, MapViewRights = PXCacheRights.Select)]
[PXButton(ImageKey = PX.Web.UI.Sprite.Main.DataEntry)]
public virtual IEnumerable CreateSalesOrder(PXAdapter adapter)
{
foreach (CROpportunity opportunity in adapter.Get())
{
Customer customer = (Customer)PXSelect<Customer, Where<Customer.bAccountID, Equal<Current<CROpportunity.bAccountID>>>>
.SelectSingleBound(this, new object[] { opportunity });
if (customer == null)
{
throw new PXException(Messages.ProspectNotCustomer);
}
var products = Products.View.SelectMultiBound(new object[] { opportunity }).RowCast<CROpportunityProducts>();
if (products.Any(_ => _.InventoryID == null) && !products.Any(_ => _.InventoryID != null))
{
throw new PXException(Messages.SalesOrderHasOnlyNonInventoryLines);
}
if (CreateOrderParams.AskExtFullyValid((graph, viewName) => { }, DialogAnswerType.Positive))
{
Save.Press();
PXLongOperation.StartOperation(this, delegate()
{
var grapph = PXGraph.CreateInstance<OpportunityMaint>();
grapph.Opportunity.Current = opportunity;
grapph.CreateOrderParams.Current = CreateOrderParams.Current;
grapph.DoCreateSalesOrder(CreateOrderParams.Current);
});
}
yield return opportunity;
}
}
if we look in that method we can find the following lines which are creating the relation:
var campaignRelation = docgraph.RelationsLink.Insert();
campaignRelation.RefNoteID = doc.NoteID;
campaignRelation.Role = CRRoleTypeList.Source;
campaignRelation.TargetType = CRTargetEntityType.CROpportunity;
campaignRelation.TargetNoteID = opportunity.NoteID;
campaignRelation.DocNoteID = opportunity.NoteID;
campaignRelation.EntityID = opportunity.BAccountID;
campaignRelation.ContactID = opportunity.ContactID;
docgraph.RelationsLink.Update(campaignRelation);
You can find the full code of that method below:
protected virtual void DoCreateSalesOrder(CreateSalesOrderFilter param)
{
bool recalcAny = param.RecalculatePrices == true ||
param.RecalculateDiscounts == true ||
param.OverrideManualDiscounts == true ||
param.OverrideManualDocGroupDiscounts == true ||
param.OverrideManualPrices == true;
var opportunity = this.Opportunity.Current;
Customer customer = (Customer)PXSelect<Customer, Where<Customer.bAccountID, Equal<Current<CROpportunity.bAccountID>>>>.Select(this);
SOOrderEntry docgraph = PXGraph.CreateInstance<SOOrderEntry>();
CurrencyInfo info = PXSelect<CurrencyInfo, Where<CurrencyInfo.curyInfoID, Equal<Current<CROpportunity.curyInfoID>>>>.Select(this);
info.CuryInfoID = null;
info = CurrencyInfo.GetEX(docgraph.currencyinfo.Insert(info.GetCM()));
SOOrder doc = new SOOrder();
doc.OrderType = CreateOrderParams.Current.OrderType ?? SOOrderTypeConstants.SalesOrder;
doc = docgraph.Document.Insert(doc);
doc = PXCache<SOOrder>.CreateCopy(docgraph.Document.Search<SOOrder.orderNbr>(doc.OrderNbr));
doc.CuryInfoID = info.CuryInfoID;
doc = PXCache<SOOrder>.CreateCopy(docgraph.Document.Update(doc));
doc.CuryID = info.CuryID;
doc.OrderDate = Accessinfo.BusinessDate;
doc.OrderDesc = opportunity.Subject;
doc.TermsID = customer.TermsID;
doc.CustomerID = opportunity.BAccountID;
doc.CustomerLocationID = opportunity.LocationID ?? customer.DefLocationID;
if (opportunity.TaxZoneID != null)
{
doc.TaxZoneID = opportunity.TaxZoneID;
if (!recalcAny)
{
SOTaxAttribute.SetTaxCalc<SOLine.taxCategoryID>(docgraph.Transactions.Cache, null, TaxCalc.ManualCalc);
SOTaxAttribute.SetTaxCalc<SOOrder.freightTaxCategoryID>(docgraph.Document.Cache, null,
TaxCalc.ManualCalc);
}
}
doc.ProjectID = opportunity.ProjectID;
doc.BranchID = opportunity.BranchID;
doc = docgraph.Document.Update(doc);
var campaignRelation = docgraph.RelationsLink.Insert();
campaignRelation.RefNoteID = doc.NoteID;
campaignRelation.Role = CRRoleTypeList.Source;
campaignRelation.TargetType = CRTargetEntityType.CROpportunity;
campaignRelation.TargetNoteID = opportunity.NoteID;
campaignRelation.DocNoteID = opportunity.NoteID;
campaignRelation.EntityID = opportunity.BAccountID;
campaignRelation.ContactID = opportunity.ContactID;
docgraph.RelationsLink.Update(campaignRelation);
bool failed = false;
foreach (CROpportunityProducts product in SelectProducts(opportunity.QuoteNoteID))
{
if (product.SiteID == null)
{
InventoryItem item = (InventoryItem)PXSelectorAttribute.Select<CROpportunityProducts.inventoryID>(Products.Cache, product);
if (item != null && item.NonStockShip == true)
{
Products.Cache.RaiseExceptionHandling<CROpportunityProducts.siteID>(product, null,
new PXSetPropertyException(ErrorMessages.FieldIsEmpty, typeof(CROpportunityProducts.siteID).Name));
failed = true;
}
}
SOLine tran = new SOLine();
tran = docgraph.Transactions.Insert(tran);
if (tran != null)
{
tran.InventoryID = product.InventoryID;
tran.SubItemID = product.SubItemID;
tran.TranDesc = product.Descr;
tran.OrderQty = product.Quantity;
tran.UOM = product.UOM;
tran.CuryUnitPrice = product.CuryUnitPrice;
tran.TaxCategoryID = product.TaxCategoryID;
tran.SiteID = product.SiteID;
tran.IsFree = product.IsFree;
tran.ProjectID = product.ProjectID;
tran.TaskID = product.TaskID;
tran.CostCodeID = product.CostCodeID;
tran.ManualPrice = true;
tran.ManualDisc = true;
tran.CuryDiscAmt = product.CuryDiscAmt;
tran.DiscAmt = product.DiscAmt;
tran.DiscPct = product.DiscPct;
tran.POCreate = product.POCreate;
tran.VendorID = product.VendorID;
if (param.RecalculatePrices != true)
{
tran.ManualPrice = true;
}
else
{
if (param.OverrideManualPrices != true)
tran.ManualPrice = product.ManualPrice;
else
tran.ManualPrice = false;
}
if (param.RecalculateDiscounts != true)
{
tran.ManualDisc = true;
}
else
{
if (param.OverrideManualDiscounts != true)
tran.ManualDisc = product.ManualDisc;
else
tran.ManualDisc = false;
}
tran.CuryDiscAmt = product.CuryDiscAmt;
tran.DiscAmt = product.DiscAmt;
tran.DiscPct = product.DiscPct;
}
tran = docgraph.Transactions.Update(tran);
PXNoteAttribute.CopyNoteAndFiles(Products.Cache, product, docgraph.Transactions.Cache, tran,
Setup.Current);
}
PXNoteAttribute.CopyNoteAndFiles(Opportunity.Cache, opportunity, docgraph.Document.Cache, doc, Setup.Current);
if (failed)
throw new PXException(Messages.SiteNotDefined);
//Skip all customer dicounts
if (param.RecalculateDiscounts != true && param.OverrideManualDiscounts != true)
{
var discounts = new Dictionary<string, SOOrderDiscountDetail>();
foreach (SOOrderDiscountDetail discountDetail in docgraph.DiscountDetails.Select())
{
docgraph.DiscountDetails.SetValueExt<SOOrderDiscountDetail.skipDiscount>(discountDetail, true);
string key = discountDetail.Type + ':' + discountDetail.DiscountID + ':' + discountDetail.DiscountSequenceID;
discounts.Add(key, discountDetail);
}
Discount ext = this.GetExtension<Discount>();
foreach (CROpportunityDiscountDetail discountDetail in ext.DiscountDetails.Select())
{
SOOrderDiscountDetail detail;
string key = discountDetail.Type + ':' + discountDetail.DiscountID + ':' + discountDetail.DiscountSequenceID;
if (discounts.TryGetValue(key, out detail))
{
docgraph.DiscountDetails.SetValueExt<SOOrderDiscountDetail.skipDiscount>(detail, false);
if (discountDetail.IsManual == true && discountDetail.Type == DiscountType.Document)
{
docgraph.DiscountDetails.SetValueExt<SOOrderDiscountDetail.extDiscCode>(detail, discountDetail.ExtDiscCode);
docgraph.DiscountDetails.SetValueExt<SOOrderDiscountDetail.description>(detail, discountDetail.Description);
docgraph.DiscountDetails.SetValueExt<SOOrderDiscountDetail.isManual>(detail, discountDetail.IsManual);
docgraph.DiscountDetails.SetValueExt<SOOrderDiscountDetail.curyDiscountAmt>(detail, discountDetail.CuryDiscountAmt);
}
}
else
{
detail = (SOOrderDiscountDetail)docgraph.DiscountDetails.Cache.CreateInstance();
detail.Type = discountDetail.Type;
detail.DiscountID = discountDetail.DiscountID;
detail.DiscountSequenceID = discountDetail.DiscountSequenceID;
detail.ExtDiscCode = discountDetail.ExtDiscCode;
detail.Description = discountDetail.Description;
detail = (SOOrderDiscountDetail)docgraph.DiscountDetails.Cache.Insert(detail);
if (discountDetail.IsManual == true && (discountDetail.Type == DiscountType.Document || discountDetail.Type == DiscountType.ExternalDocument))
{
detail.CuryDiscountAmt = discountDetail.CuryDiscountAmt;
detail.IsManual = discountDetail.IsManual;
docgraph.DiscountDetails.Cache.Update(detail);
}
}
}
SOOrder old_row = PXCache<SOOrder>.CreateCopy(docgraph.Document.Current);
docgraph.Document.Cache.SetValueExt<SOOrder.curyDiscTot>(docgraph.Document.Current, DiscountEngineProvider.GetEngineFor<SOLine, SOOrderDiscountDetail>().GetTotalGroupAndDocumentDiscount(docgraph.DiscountDetails));
docgraph.Document.Cache.RaiseRowUpdated(docgraph.Document.Current, old_row);
}
doc = docgraph.Document.Update(doc);
if (opportunity.TaxZoneID != null && !recalcAny)
{
foreach (CRTaxTran tax in PXSelect<CRTaxTran, Where<CRTaxTran.quoteID, Equal<Current<CROpportunity.quoteNoteID>>>>.Select(this))
{
SOTaxTran newtax = new SOTaxTran();
newtax.LineNbr = int.MaxValue;
newtax.TaxID = tax.TaxID;
newtax = docgraph.Taxes.Insert(newtax);
if (newtax != null)
{
newtax = PXCache<SOTaxTran>.CreateCopy(newtax);
newtax.TaxRate = tax.TaxRate;
newtax.CuryTaxableAmt = tax.CuryTaxableAmt;
newtax.CuryTaxAmt = tax.CuryTaxAmt;
newtax.CuryUnshippedTaxableAmt = tax.CuryTaxableAmt;
newtax.CuryUnshippedTaxAmt = tax.CuryTaxAmt;
newtax.CuryUnbilledTaxableAmt = tax.CuryTaxableAmt;
newtax.CuryUnbilledTaxAmt = tax.CuryTaxAmt;
newtax = docgraph.Taxes.Update(newtax);
}
}
}
if (opportunity.AllowOverrideContactAddress == true)
{
CRContact _CRContact = Opportunity_Contact.SelectSingle();
CRAddress _CRAddress = Opportunity_Address.SelectSingle();
// Insert
if (_CRContact != null)
{
SOBillingContact _billingContact = docgraph.Billing_Contact.Select();
if (_billingContact != null)
{
_billingContact.FullName = _CRContact.FullName;
_billingContact.Salutation = _CRContact.Salutation;
_billingContact.Phone1 = _CRContact.Phone1;
_billingContact.Email = _CRContact.Email;
_billingContact = docgraph.Billing_Contact.Update(_billingContact);
_billingContact.IsDefaultContact = false;
_billingContact = docgraph.Billing_Contact.Update(_billingContact);
}
}
if (_CRAddress != null)
{
SOBillingAddress _billingAddress = docgraph.Billing_Address.Select();
if (_billingAddress != null)
{
_billingAddress.AddressLine1 = _CRAddress.AddressLine1;
_billingAddress.AddressLine2 = _CRAddress.AddressLine2;
_billingAddress.City = _CRAddress.City;
_billingAddress.CountryID = _CRAddress.CountryID;
_billingAddress.State = _CRAddress.State;
_billingAddress.PostalCode = _CRAddress.PostalCode;
_billingAddress = docgraph.Billing_Address.Update(_billingAddress);
_billingAddress.IsDefaultAddress = false;
_billingAddress = docgraph.Billing_Address.Update(_billingAddress);
}
}
}
if (recalcAny)
{
docgraph.recalcdiscountsfilter.Current.OverrideManualPrices = param.OverrideManualPrices == true;
docgraph.recalcdiscountsfilter.Current.RecalcDiscounts = param.RecalculateDiscounts == true;
docgraph.recalcdiscountsfilter.Current.RecalcUnitPrices = param.RecalculatePrices == true;
docgraph.recalcdiscountsfilter.Current.OverrideManualDiscounts = param.OverrideManualDiscounts == true;
docgraph.recalcdiscountsfilter.Current.OverrideManualDocGroupDiscounts = param.OverrideManualDocGroupDiscounts == true;
docgraph.Actions[nameof(Discount.RecalculateDiscountsAction)].Press();
}
if (!this.IsContractBasedAPI)
throw new PXRedirectRequiredException(docgraph, "");
docgraph.Save.Press();
}
NOTE: you can find most part of the sources by the following path in the Acumatica's server folder App_Data\CodeRepository\PX.Objects,App_Data\CodeRepository\PX.Data,App_Data\CodeRepository\PX.Objects.FS
i have done code to fill up grid view with data set.
just look at :
public void FillGrid(string StartAlpha, string CommandName, string ColumnName, string SearchText)
{
using (DataClassesDataContext db = new DataClassesDataContext())
{
int userid = db.Users.Where(u => u.EmailAddress.Equals((String)Session["EmailID"])).Select(u => u.Id).SingleOrDefault();
var sms = Enumerable.Repeat(new
{
Id = default(int),
Title = string.Empty,
Body = string.Empty,
FromUser = string.Empty,
ToUser = string.Empty,
SentDateTime = default(DateTime?),
IsMedia = default(bool),
CreatedDate = default(DateTime),
}, 1).ToList();
DataSet myDataSet = new DataSet();
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("Id", typeof(string)));
dt.Columns.Add(new DataColumn("Title", typeof(string)));
dt.Columns.Add(new DataColumn("Body", typeof(string)));
dt.Columns.Add(new DataColumn("FromUser", typeof(string)));
dt.Columns.Add(new DataColumn("ToUser", typeof(string)));
dt.Columns.Add(new DataColumn("SentDateTime", typeof(DateTime)));
dt.Columns.Add(new DataColumn("IsMedia", typeof(bool)));
dt.Columns.Add(new DataColumn("CreatedDate", typeof(DateTime)));
if (StartAlpha.Equals("All"))
{
switch (CommandName)
{
case "Inbox":
break;
case "Outbox":
lbl_countall.Text = db.SMS.Where(s => s.SentDateTime != null).Count().ToString();
lbut_showinbox.Font.Bold = false;
lbut_showoutbox.Font.Bold = true;
lbut_showdraffs.Font.Bold = false;
sms = db.SMS.OrderByDescending(s => s.SentDateTime).Where(s => (s.SentDateTime != null || s.IsDraft.Equals(false)) & s.user_id.Equals(userid)).Select(s => new
{
Id = s.Id,
Title = s.Title,
Body = s.Body,
FromUser = db.SMSAccounts.Where(a=>a.user_id.Equals(userid)).Select(a=>a.FromMobileNo).FirstOrDefault(),
ToUser = s.To_MobileNo,
SentDateTime = s.SentDateTime,
IsMedia = false,
CreatedDate = s.CreatedDate
}).FilterForColumn(ColumnName, SearchText).ToList();
foreach (var item in sms)
{
if (item != null)
{
DataRow dr = dt.NewRow();
dr["Id"] = item.Id.ToString();
dr["Title"] = item.Title.ToString();
dr["Body"] = Regex.Replace(item.Body.ToString().Trim(), #"<(.|\n)*?>", string.Empty);
dr["FromUser"] = item.FromUser.ToString();
if (item.ToUser != null)
{
dr["ToUser"] = item.ToUser.ToString();
}
else
{
dr["ToUser"] = "NoN";
}
if (item.SentDateTime != null)
{
dr["SentDatetTime"] = item.SentDateTime;
}
else
{
dr["SentDatetTime"] = DBNull.Value;
}
dr["IsMedia"] = item.IsMedia;
dr["CreatedDate"] = item.CreatedDate;
dt.Rows.Add(dr);
}
}
break;
case "Drafts":
lbl_countall.Text = db.SMS.Where(s => s.SentDateTime != null || s.IsDraft.Equals(true)).Count().ToString();
lbut_showinbox.Font.Bold = false;
lbut_showoutbox.Font.Bold = false;
lbut_showdraffs.Font.Bold = true;
sms = db.SMS.OrderByDescending(s => s.SentDateTime).Where(s => (s.SentDateTime == null || s.IsDraft.Equals(true)) & s.user_id.Equals(userid)).Select(s => new
{
Id = s.Id,
Title = s.Title,
Body = s.Body,
FromUser = db.SMSAccounts.Where(a => a.user_id.Equals(userid)).Select(a => a.FromMobileNo).FirstOrDefault(),
ToUser = s.To_MobileNo,
SentDateTime = s.SentDateTime,
IsMedia = false,
CreatedDate = s.CreatedDate
}).FilterForColumn(ColumnName, SearchText).ToList();
foreach (var item in sms)
{
if (item != null)
{
DataRow dr = dt.NewRow();
dr["Id"] = item.Id.ToString();
dr["Title"] = item.Title.ToString();
dr["Body"] = Regex.Replace(item.Body.ToString().Trim(), #"<(.|\n)*?>", string.Empty);
dr["FromUser"] = item.FromUser.ToString();
if (item.ToUser != null)
{
dr["ToUser"] = item.ToUser.ToString();
}
else
{
dr["ToUser"] = "NoN";
}
if (item.SentDateTime != null)
{
dr["SentDatetTime"] = item.SentDateTime;
}
else
{
dr["SentDatetTime"] = DBNull.Value;
}
dr["IsMedia"] = item.IsMedia;
dr["CreatedDate"] = item.CreatedDate;
dt.Rows.Add(dr);
}
}
break;
}
}
else
{
switch (CommandName)
{
//case "Inbox":
.............
// break;
case "Outbox":
lbl_countall.Text = db.SMS.Where(s => s.SentDateTime != null).Count().ToString();
lbut_showinbox.Font.Bold = false;
lbut_showoutbox.Font.Bold = true;
lbut_showdraffs.Font.Bold = false;
sms = db.SMS.OrderByDescending(s => s.SentDateTime).Where(s => (s.SentDateTime != null || s.IsDraft.Equals(false)) & s.user_id.Equals(userid)).Select(s => new
{
Id = s.Id,
Title = s.Title,
Body = s.Body,
FromUser = db.SMSAccounts.Where(a => a.user_id.Equals(userid)).Select(a => a.FromMobileNo).FirstOrDefault(),
ToUser = s.To_MobileNo,
SentDateTime = s.SentDateTime,
IsMedia = false,
CreatedDate = s.CreatedDate
}).FilterForColumn(ColumnName, SearchText).ToList().Where(x => x.Title.StartsWith(StartAlpha, StringComparison.CurrentCultureIgnoreCase)).ToList();
foreach (var item in sms)
{
if (item != null)
{
DataRow dr = dt.NewRow();
dr["Id"] = item.Id.ToString();
dr["Title"] = item.Title.ToString();
dr["Body"] = Regex.Replace(item.Body.ToString().Trim(), #"<(.|\n)*?>", string.Empty);
dr["FromUser"] = item.FromUser.ToString();
if (item.ToUser != null)
{
dr["ToUser"] = item.ToUser.ToString();
}
else
{
dr["ToUser"] = "NoN";
}
if (item.SentDateTime != null)
{
dr["SentDatetTime"] = item.SentDateTime;
}
else
{
dr["SentDatetTime"] = DBNull.Value;
}
dr["IsMedia"] = item.IsMedia;
dr["CreatedDate"] = item.CreatedDate;
dt.Rows.Add(dr);
}
}
break;
case "Drafts":
lbl_countall.Text = db.SMS.Where(s => s.SentDateTime != null).Count().ToString();
lbut_showinbox.Font.Bold = false;
lbut_showoutbox.Font.Bold = false;
lbut_showdraffs.Font.Bold = true;
sms = db.SMS.OrderByDescending(s => s.SentDateTime).Where(s => (s.SentDateTime == null || s.IsDraft.Equals(true)) & s.user_id.Equals(userid)).Select(s => new
{
Id = s.Id,
Title = s.Title,
Body = s.Body,
FromUser = db.SMSAccounts.Where(a => a.user_id.Equals(userid)).Select(a => a.FromMobileNo).FirstOrDefault(),
ToUser = s.To_MobileNo,
SentDateTime = s.SentDateTime,
IsMedia = false,
CreatedDate = s.CreatedDate
}).FilterForColumn(ColumnName, SearchText).ToList().Where(x => x.Title.StartsWith(StartAlpha, StringComparison.CurrentCultureIgnoreCase)).ToList();
foreach (var item in sms)
{
if (item != null)
{
DataRow dr = dt.NewRow();
dr["Id"] = item.Id.ToString();
dr["Title"] = item.Title.ToString();
dr["Body"] = Regex.Replace(item.Body.ToString().Trim(), #"<(.|\n)*?>", string.Empty);
dr["FromUser"] = item.FromUser.ToString();
if (item.ToUser != null)
{
dr["ToUser"] = item.ToUser.ToString();
}
else
{
dr["ToUser"] = "NoN";
}
if (item.SentDateTime != null)
{
dr["SentDatetTime"] = item.SentDateTime;
}
else
{
dr["SentDatetTime"] = DBNull.Value;
}
dr["IsMedia"] = item.IsMedia;
dr["CreatedDate"] = item.CreatedDate;
dt.Rows.Add(dr);
}
}
break;
}
}
myDataSet.Tables.Add(dt);
if (myDataSet.Tables[0].Rows.Count > 0)
{
DataView myDataView = new DataView();
myDataView = myDataSet.Tables[0].DefaultView;
if (this.ViewState["SortExp"] != null)
{
myDataView.Sort = this.ViewState["SortExp"].ToString()
+ " " + this.ViewState["SortOrder"].ToString();
}
GV_ViewSMS.DataSource = myDataView;
}
if (GV_ViewSMS.Rows.Count != 0)
{
SetPageNumbers();
}
GV_ViewSMS.DataBind();
}
}
and this error occurs :
Server Error in '/' Application.
Column 'SentDatetTime' does not belong to table .
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentException: Column 'SentDatetTime' does not belong to table .
Source Error:
Line 439: else
Line 440: {
Line 441: dr["SentDatetTime"] = DBNull.Value;
Line 442: }
Line 443: dr["IsMedia"] = item.IsMedia;
Source File: e:\EASYMAIL_off\EASYMAIL\BulkSMS.aspx.cs Line: 441
Stack Trace:
[ArgumentException: Column 'SentDatetTime' does not belong to table .]
System.Data.DataRow.GetDataColumn(String columnName) +5731291
System.Data.DataRow.set_Item(String columnName, Object value) +13
BulkSMS.FillGrid(String StartAlpha, String CommandName, String ColumnName, String SearchText) in e:\EASYMAIL_off\EASYMAIL\BulkSMS.aspx.cs:441
BulkSMS.Page_Load(Object sender, EventArgs e) in e:\EASYMAIL_off\EASYMAIL\BulkSMS.aspx.cs:40
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +51
System.Web.UI.Control.OnLoad(EventArgs e) +95
System.Web.UI.Control.LoadRecursive() +59
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +678
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.6.1055.0
What wrong with my Code?????
please help me to throughout this problem.....
Looks like you have a spelling error SentDatetTime -> SentDateTime:
if (item.SentDateTime != null)
{
dr["SentDateTime"] = item.SentDateTime;
}
else
{
dr["SentDateTime"] = DBNull.Value;
}
i have uploaded a csv file and also make a data-table from csv file.now i want to find distinct values from each columns of data-table.what will be the code for this.
i have tried by this code but there is error show that object is not ADODB.what is ADODB and how can i remove this error
public static DataTable GetDataTabletFromCSVFile(string csv_file_path)
{
DataTable csvData = new DataTable();
try
{
using (TextFieldParser csvReader = new TextFieldParser(csv_file_path))
{
csvReader.SetDelimiters(new string[] { "," });
csvReader.HasFieldsEnclosedInQuotes = true;
//read column names
string[] colFields = csvReader.ReadFields();
foreach (string column in colFields)
{
DataColumn datecolumn = new DataColumn(column);
datecolumn.AllowDBNull = true;
csvData.Columns.Add(datecolumn);
}
while (!csvReader.EndOfData)
{
string[] fieldData = csvReader.ReadFields();
//Making empty value as null
for (int i = 0; i < fieldData.Length; i++)
{
if (fieldData[i] == "")
{
fieldData[i] = null;
}
}
csvData.Rows.Add(fieldData);
}
foreach (DataColumn col in csvdata.Columns)
{
foreach (DataRow ro in csvdata.Rows)
{
textBox1.Text = "" + ro[col];
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I am very new to Sharepoint development. I have the following code that I need to have display the list items by targeted audience. I know I am suppose to add something like this
AudienceLoader audienceLoader = AudienceLoader.GetAudienceLoader();
foreach (SPListItem listItem in list.Items)
{
// get roles the list item is targeted to
string audienceFieldValue = (string)listItem[k_AudienceColumn];
// quickly check if the user belongs to any of those roles
if (AudienceManager.IsCurrentUserInAudienceOf(audienceLoader,
audienceFieldValue,
false))
But I have no idea where to place it in my code below. Please I would appreciate any of your advise.
using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
using System.Web.UI.HtmlControls;
namespace PersonalAnnouncements.PersonalAnnouncements
{
[ToolboxItem(false)]
public class PersonalAnnouncements : Microsoft.SharePoint.WebPartPages.WebPart
{
// Fields
private string _exceptions = "";
private AddInsEnum DE = AddInsEnum.HyperLink;
private const AddInsEnum DefaultAddInsEnum = AddInsEnum.HyperLink;
private const TheDateFormat DefaultDateFormat = TheDateFormat.MonthDayYear;
private const PeriodEnum DefaultPeriod = PeriodEnum.Five;
private const string defaultText = "Your text here";
private const string DefaultURL = "DispForm.aspx";
private TheDateFormat DF = TheDateFormat.MonthDayYear;
private string endField = "Image URL";
private const string imgTURL = "/_layouts/NewsViewer/banner1_thumb.jpg";
private const string imgURL = "/_layouts/NewsViewer/banner1.jpg";
protected Label lblError;
private const string listText = "";
private string listViewFields = "";
private PeriodEnum Period = PeriodEnum.Five;
private string sImageURL = "/_layouts/NewsViewer/banner1.jpg";
private string siteURLtext = "Your Site here";
private string startField = "Body";
private string sTImageURL = "/_layouts/NewsViewer/banner1_thumb.jpg";
private string sTimeField = "/_layouts/NewsViewer/style_smaller.css";
private string sYAxisTitle = "15";
private string text = "Your text here";
private string ThumbImageField = "";
private const string timer = "/_layouts/NewsViewer/style_smaller.css";
private string titleField = "";
private string urltocalendar = "DispForm.aspx";
private const string yaxistit = "15";
// Methods
protected override void CreateChildControls()
{
HtmlTable table;
HtmlTableRow row;
HtmlTableCell cell;
bool controlsAdded = false;
try
{
base.CreateChildControls();
SPWeb theWeb = new SPSite(this.SiteURL).OpenWeb();
SPSecurity.RunWithElevatedPrivileges(delegate
{
using (SPSite site = new SPSite(theWeb.Url))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists[this.Text];
if (list.BaseTemplate == SPListTemplateType.GenericList)
{
this.lblError = new Label();
this.lblError.Text = "Error:";
this.lblError.Visible = true;
HtmlTable child = new HtmlTable();
row = new HtmlTableRow();
cell = new HtmlTableCell();
string str = "<link rel=\"stylesheet\" type=\"text/css\" href=\"" + this.CSSField + "\" /><script type=\"text/javascript\" src=\"/_layouts/NewsViewer/jquery-1.3.2.min.js\"></script><script type=\"text/javascript\">var X = jQuery.noConflict();X(document).ready(function() {\t X(\".main_image .desc\").show(); X(\".main_image .block\").animate({ opacity: 0.85 }, 1 ); X(\".image_thumb ul li:first\").addClass('active'); X(\".image_thumb ul li\").click(function(){ var imgAlt = X(this).find('img').attr(\"alt\"); var imgTitle = X(this).find('a').attr(\"href\"); var imgDesc = X(this).find('.block').html(); \t var imgDescHeight = X(\".main_image\").find('.block').height();\t\t if (X(this).is(\".active\")) { return false; } else { X(\".main_image .block\").animate({ opacity: 0, marginBottom: -imgDescHeight }, 250 , function() { X(\".main_image .block\").html(imgDesc).animate({ opacity: 0.85,\tmarginBottom: \"0\" }, 250 ); X(\".main_image img\").attr({ src: imgTitle , alt: imgAlt}); }); } X(\".image_thumb ul li\").removeClass('active'); X(this).addClass('active'); return false;}) .hover(function(){ X(this).addClass('hover'); }, function() { X(this).removeClass('hover');}); X(\"a.collapse\").click(function(){ X(\".main_image .block\").slideToggle(); X(\"a.collapse\").toggleClass(\"show\"); });}); </script><div id=\"main\" class=\"container\">";
string sideNav = this.GetSideNav();
string mainContent = this.GetMainContent();
cell.InnerHtml = str + mainContent + sideNav + "</div></div>";
row.Cells.Add(cell);
child.Rows.Add(row);
this.Controls.Add(child);
controlsAdded = true;
}
}
}
});
}
catch (Exception exception)
{
if (controlsAdded)
{
this._exceptions = this._exceptions + "CreateChildControls_Exception: " + exception.Message;
}
table = new HtmlTable();
row = new HtmlTableRow();
cell = new HtmlTableCell();
if (!this.Text.Contains("Your text here"))
{
cell.InnerHtml = "Error: " + exception.Message;
row.Cells.Add(cell);
table.Rows.Add(row);
this.Controls.Add(table);
this.Controls.Add(this.lblError);
}
}
if (!controlsAdded)
{
table = new HtmlTable();
row = new HtmlTableRow();
cell = new HtmlTableCell();
if (!this.Text.Contains("Your text here"))
{
cell.InnerHtml = "Please choose the Personal Announcement list: " + this.Text + " - Site:" + this.SiteURL;
row.Cells.Add(cell);
table.Rows.Add(row);
this.Controls.Add(table);
this.Controls.Add(this.lblError);
}
else
{
cell.InnerHtml = "Please setup Personal Announcement by clicking Modify Shared WebPart";
row.Cells.Add(cell);
table.Rows.Add(row);
this.Controls.Add(table);
}
}
}
private string FirstWords(string input, int numberWords)
{
try
{
int num = numberWords;
for (int i = 0; i < input.Length; i++)
{
if (input[i] == ' ')
{
num--;
}
if (num == 0)
{
return input.Substring(0, i);
}
}
}
catch (Exception)
{
}
return string.Empty;
}
private string GetMainContent()
{
string str = "";
this.lblError.Text = this.lblError.Text + " -> GetMainContent()";
SPSite site = new SPSite(this.SiteURL);
SPWeb web = site.OpenWeb();
SPUserToken userToken = site.SystemAccount.UserToken;
using (SPSite site2 = new SPSite(web.Url, userToken))
{
using (SPWeb web2 = site2.OpenWeb())
{
SPView view = web2.Lists[this.Text].Views[this.ListViewFields];
view.RowLimit = 1;
SPListItemCollection items = web2.Lists[this.Text].GetItems(view);
int num = 0;
int num2 = this.getNumber(this.NumEvents.ToString());
string str2 = "";
if (items.Count > 0)
{
foreach (SPListItem item in items)
{
if (num == 0)
{
object obj2;
string imageURL = "";
string format = "";
if (this.DateFormat.ToString() == "DayMonthYear")
{
format = "d/M/yyyy HH:mm tt";
}
else
{
format = "M/d/yyyy HH:mm tt";
}
if (item[this.ImageURLField] != null)
{
if (this.TheColumnType.ToString() != "HyperLink")
{
if (item[this.ImageURLField].ToString().Trim() != string.Empty)
{
imageURL = item[this.ImageURLField].ToString();
}
else
{
imageURL = this.ImageURL;
}
}
else if (item[this.ImageURLField].ToString().Trim() != string.Empty)
{
imageURL = item[this.ImageURLField].ToString().Split(new char[] { ',' })[0];
}
else
{
imageURL = this.ImageURL;
}
}
else
{
imageURL = this.ImageURL;
}
str2 = str2 + "<div class=\"main_image\">";
str2 = str2 + "<img src=\"" + imageURL + "\" alt=\"BNNewsbanner\" />";
str2 = str2 + "<div class=\"desc\" >Close Me!";
if (item[this.TitleField] != null)
{
obj2 = str2;
str2 = string.Concat(new object[] { obj2, "<div class=\"block\"><h2><a href=\"", web.Url, "/Lists/", this.Text, "/DispForm.aspx?ID=", item.ID, "\" >", item[this.TitleField].ToString(), "</a></h2>" });
}
else
{
obj2 = str2;
str2 = string.Concat(new object[] { obj2, "<div class=\"block\"><h2><a href=\"", web.Url, "/Lists/", this.Text, "/DispForm.aspx?ID=", item.ID, "\" >No Title Text Found</a></h2>" });
}
str2 = str2 + "<small>" + Convert.ToDateTime(item["Created"].ToString()).ToString(format) + "</small>";
if (item[this.BodyField] != null)
{
obj2 = str2;
// str2 = string.Concat(new object[] { obj2, "<p>", this.FirstWords(this.StripTagsCharArray(item[this.BodyField].ToString()), Convert.ToInt32(this.NumWords)), "... <br/><a href=\"", web.Url, "/Lists/", this.Text, "/DispForm.aspx?ID=", item.ID, "\" >read more</a></p></div></div></div>" });
str2 = string.Concat(new object[] { obj2, "<p>", this.FirstWords(this.StripTagsCharArray(item[this.BodyField].ToString()), Convert.ToInt32(this.NumWords)), "... <br/><a href=\"", web.Url, "/Lists/", this.Text, "/DispForm.aspx?ID=", item.ID, "\" >read more</a></p></div></div></div>" });
}
else
{
obj2 = str2;
str2 = string.Concat(new object[] { obj2, "<p>", this.FirstWords(this.StripTagsCharArray("No Body Text Found"), Convert.ToInt32(this.NumWords)), "... <br/><a href=\"", web.Url, "/Lists/", this.Text, "/DispForm.aspx?ID=", item.ID, "\" >read more</a></p></div></div></div>" });
}
}
num++;
}
}
str = str + str2;
}
}
return str;
}
public int getNumber(string number)
{
switch (number)
{
case "One":
return 1;
case "Two":
return 2;
case "Three":
return 3;
case "Four":
return 4;
case "Five":
return 5;
case "Six":
return 6;
case "Seven":
return 7;
case "Eight":
return 8;
case "Nine":
return 9;
case "Ten":
return 10;
}
return 0;
}
private string GetSideNav()
{
this.lblError.Text = this.lblError.Text + " -> GetSideNav()";
string str = "<div class=\"image_thumb\"><ul>";
SPSite site = new SPSite(this.SiteURL);
SPWeb web = site.OpenWeb();
SPUserToken userToken = site.SystemAccount.UserToken;
using (SPSite site2 = new SPSite(web.Url, userToken))
{
using (SPWeb web2 = site2.OpenWeb())
{
SPView view = web2.Lists[this.Text].Views[this.ListViewFields];
SPListItemCollection items = web2.Lists[this.Text].GetItems(view);
int num = 0;
int num2 = this.getNumber(this.NumEvents.ToString());
string str2 = "";
if (items.Count > 0)
{
foreach (SPListItem item in items)
{
if (num < num2)
{
object obj2;
string imageThumbURL = "";
string imageURL = "";
string format = "";
if (this.DateFormat.ToString() == "DayMonthYear")
{
format = "d/M/yyyy HH:mm tt";
}
else
{
format = "M/d/yyyy HH:mm tt";
}
if (item[this.ImageURLField] != null)
{
if (this.TheColumnType.ToString() != "HyperLink")
{
if (item[this.ImageURLField].ToString().Trim() != string.Empty)
{
imageURL = item[this.ImageURLField].ToString();
}
else
{
imageURL = this.ImageURL;
}
}
else if (item[this.ImageURLField].ToString().Trim() != string.Empty)
{
imageURL = item[this.ImageURLField].ToString().Split(new char[] { ',' })[0];
}
else
{
imageURL = this.ImageURL;
}
}
else
{
imageURL = this.ImageURL;
}
if (item[this.ThumbImageURLField] != null)
{
if (this.TheColumnType.ToString() != "HyperLink")
{
if (item[this.ThumbImageURLField].ToString().Trim() != string.Empty)
{
imageThumbURL = item[this.ThumbImageURLField].ToString();
}
else
{
imageThumbURL = this.ImageThumbURL;
}
}
else if (item[this.ThumbImageURLField].ToString().Trim() != string.Empty)
{
imageThumbURL = item[this.ThumbImageURLField].ToString().Split(new char[] { ',' })[0];
}
else
{
imageThumbURL = this.ImageThumbURL;
}
}
else
{
imageThumbURL = this.ImageThumbURL;
}
str2 = str2 + "<li><a href=\"" + imageURL + "\">";
str2 = str2 + "<img src=\"" + imageThumbURL + "\" alt=\"\" /></a>";
if (item[this.TitleField] != null)
{
obj2 = str2;
str2 = string.Concat(new object[] { obj2, "<div class=\"block\"><h2><a href=\"", web.Url, "/Lists/", this.Text, "/DispForm.aspx?ID=", item.ID, "\" >", item[this.TitleField].ToString(), "</a></h2>" });
}
else
{
obj2 = str2;
str2 = string.Concat(new object[] { obj2, "<div class=\"block\"><h2><a href=\"", web.Url, "/Lists/", this.Text, "/DispForm.aspx?ID=", item.ID, "\" >No List Title Found</a></h2>" });
}
str2 = str2 + "<small>" + Convert.ToDateTime(item["Created"].ToString()).ToString(format) + "</small>";
if (item[this.BodyField] != null)
{
obj2 = str2;
str2 = string.Concat(new object[] { obj2, "<p>", this.FirstWords(this.StripTagsCharArray(item[this.BodyField].ToString()), Convert.ToInt32(this.NumWords)), "... <br/><a href=\"", web.Url, "/Lists/", this.Text, "/DispForm.aspx?ID=", item.ID, "\" >read more</a></p></div></li>" });
}
else
{
obj2 = str2;
str2 = string.Concat(new object[] { obj2, "<p>", this.FirstWords(this.StripTagsCharArray("No Body Text Found"), Convert.ToInt32(this.NumWords)), "... <br/><a href=\"", web.Url, "/Lists/", this.Text, "/DispForm.aspx?ID=", item.ID, "\" >read more</a></p></div></li>" });
}
}
num++;
}
}
str = str + str2;
}
}
return (str + "</ul>");
}
public override ToolPart[] GetToolParts()
{
ToolPart[] partArray = new ToolPart[3];
WebPartToolPart part = new WebPartToolPart();
CustomPropertyToolPart part2 = new CustomPropertyToolPart();
partArray[0] = part2;
partArray[1] = part;
partArray[2] = new CustomToolPart();
return partArray;
}
protected override void RenderContents(HtmlTextWriter writer)
{
try
{
base.RenderContents(writer);
}
catch (Exception exception)
{
this._exceptions = this._exceptions + "RenderContents_Exception: " + exception.Message;
}
finally
{
if (this._exceptions.Length > 0)
{
writer.WriteLine(this._exceptions);
}
}
}
private string StripTagsCharArray(string source)
{
char[] chArray = new char[source.Length];
int index = 0;
bool flag = false;
for (int i = 0; i < source.Length; i++)
{
char ch = source[i];
if (ch == '<')
{
flag = true;
}
else if (ch == '>')
{
flag = false;
}
else if (!flag)
{
chArray[index] = ch;
index++;
}
}
return new string(chArray, 0, index);
}
// Properties
public string BodyField
{
get
{
return this.startField;
}
set
{
this.startField = value;
}
}
[WebDisplayName("Style Sheet URL"), WebDescription("Specifies the path to the css file"), SPWebCategoryName("General Settings"), Personalizable(true), WebBrowsable(true)]
public string CSSField
{
get
{
return this.sTimeField;
}
set
{
this.sTimeField = value;
}
}
[WebBrowsable(true), Personalizable(true), WebDisplayName("Date Format"), WebDescription("Date Format of your News Items"), SPWebCategoryName("General Settings")]
public TheDateFormat DateFormat
{
get
{
return this.DF;
}
set
{
this.DF = value;
}
}
[WebBrowsable(true), WebDescription("Thumb Image URL to use when no image is found"), SPWebCategoryName("General Settings"), Personalizable(true), WebDisplayName("No Thumb Image URL")]
public string ImageThumbURL
{
get
{
return this.sTImageURL;
}
set
{
this.sTImageURL = value;
}
}
[Personalizable(true), SPWebCategoryName("General Settings"), WebBrowsable(true), WebDisplayName("No Image URL"), WebDescription("Image URL to use when no image is found")]
public string ImageURL
{
get
{
return this.sImageURL;
}
set
{
this.sImageURL = value;
}
}
public string ImageURLField
{
get
{
return this.endField;
}
set
{
this.endField = value;
}
}
public string ListViewFields
{
get
{
return this.listViewFields;
}
set
{
this.listViewFields = value;
}
}
[WebDescription("Number of news items to show"), WebDisplayName("Number of news items to show"), WebBrowsable(true), SPWebCategoryName("General Settings"), Personalizable(true)]
public PeriodEnum NumEvents
{
get
{
return this.Period;
}
set
{
this.Period = value;
}
}
[WebDisplayName("Number of words to show from the Body"), Personalizable(true), SPWebCategoryName("General Settings"), WebDescription("Specifies the number of words to show from the body in the main webpart, under the Title"), WebBrowsable(true)]
public string NumWords
{
get
{
return this.sYAxisTitle;
}
set
{
this.sYAxisTitle = value;
}
}
public string SiteURL
{
get
{
return this.siteURLtext;
}
set
{
this.siteURLtext = value;
}
}
public string Text
{
get
{
return this.text;
}
set
{
this.text = value;
}
}
[Personalizable(true), SPWebCategoryName("General Settings"), WebDisplayName("Image Column Type")
You can put the code in CreateChildControls() method.
I am getting the error
Missing operand before '=' operator.
when I try and export and the code is running fine in the grid.
Here is the code for the web part. The error only occurs on the rebind. It works fine in the grid itself. Is there any way to narrow down the exact thing it is erroring on?
I am willing to pay for a support / solution to this problem, I just need it to work.
[Guid("5fbe4ccf-4d90-476b-af77-347de4e1176c")]
public class ParentChildGrid : Microsoft.SharePoint.WebPartPages.WebPart
{
#region
Variables
private bool _error = false;
private string _PageSize = null;
private string _ParentList = null;
private string _ParentView = null;
private string _ParentIDField = null;
private string _FirstChildList = null;
private string _FirstChildView = null;
private string _FirstChildIDField = null;
private string _FirstChildParentIDField = null;
private string _SecondChildList = null;
private string _SecondChildView = null;
private string _SecondChildIDField = null;
private string _SecondChildParentIDField = null;
protected ScriptManager scriptManager;
protected RadAjaxManager ajaxManager;
protected Panel panel;
protected SPView oView;
protected RadGrid oGrid = new RadGrid();
protected Label label;
protected DataTable ParentDataTable;
protected DataTable Child1DataTable;
protected DataTable Child2DataTable;
protected Button cmdExport = new Button();
#endregion
#region
Properties
[Personalizable(PersonalizationScope.Shared)]
[WebBrowsable(true)]
[System.ComponentModel.
Category("Parent Child Properties")]
[WebDisplayName("Items Per Page")]
[WebDescription("# of items to include in each page.")]
public string PageSize
{
get
{
if (_PageSize == null)
{
_PageSize = "100";
}
return _PageSize.Trim();
}
set { _ParentList = value.Trim(); }
}
[Personalizable(PersonalizationScope.Shared)]
[WebBrowsable(true)]
[System.ComponentModel.
Category("Parent Child Properties")]
[WebDisplayName("ParentList")]
[WebDescription("Parent List in Grid View")]
public string ParentList
{
get
{
if (_ParentList == null)
{
_ParentList = "";
}
return _ParentList.Trim();
}
set { _ParentList = value.Trim(); }
}
[Personalizable(PersonalizationScope.Shared)]
[WebBrowsable(true)]
[System.ComponentModel.Category("Parent Child Properties")]
[WebDisplayName("ParentView")]
[WebDescription("View for Parent List")]
public string ParentView
{
get
{
if (_ParentView == null)
{
_ParentView = "";
}
return _ParentView.Trim();
}
set { _ParentView = value.Trim(); }
}
[
Personalizable(PersonalizationScope.Shared)]
[
WebBrowsable(true)]
[System.ComponentModel.
Category("Parent Child Properties")]
[
WebDisplayName("ParentIDField")]
[
WebDescription("ID Field in Parent List")]
public string ParentIDField
{
get
{
if (_ParentIDField == null)
{
_ParentIDField = "";
}
return _ParentIDField.Trim();
}
set { _ParentIDField = value.Trim(); }
}
[Personalizable(PersonalizationScope.Shared)]
[WebBrowsable(true)]
[System.ComponentModel.
Category("Parent Child Properties")]
[WebDisplayName("FirstChildList")]
[WebDescription("FirstChildList Name")]
public string FirstChildList
{
get
{
if (_FirstChildList == null)
{
_FirstChildList = "";
}
return _FirstChildList.Trim();
}
set { _FirstChildList = value.Trim(); }
}
[Personalizable(PersonalizationScope.Shared)]
[WebBrowsable(true)]
[System.ComponentModel.Category("Parent Child Properties")]
[WebDisplayName("FirstChildView")]
[WebDescription("First Child View Name")]
public string FirstChildView
{
get
{
if (_FirstChildView == null)
{
_FirstChildView = "";
}
return _FirstChildView.Trim();
}
set { _FirstChildView = value.Trim(); }
}
[Personalizable(PersonalizationScope.Shared)]
[WebBrowsable(true)]
[System.ComponentModel.Category("Parent Child Properties")]
[WebDisplayName("FirstChildIDField")]
[WebDescription("First Child ID Field (Tyically ID)")]
public string FirstChildIDField
{
get
{
if (_FirstChildIDField == null)
{
_FirstChildIDField = "";
}
return _FirstChildIDField.Trim();
}
set { _FirstChildIDField = value.Trim(); }
}
[Personalizable(PersonalizationScope.Shared)]
[WebBrowsable(true)]
[System.ComponentModel.Category("Parent Child Properties")]
[WebDisplayName("FirstChildParentIDField")]
[WebDescription("First Child Parent ID Field")]
public string FirstChildParentIDField
{
get
{
if (_FirstChildParentIDField == null)
{
_FirstChildParentIDField = "";
}
return _FirstChildParentIDField.Trim();
}
set { _FirstChildParentIDField = value.Trim(); }
}
[Personalizable(PersonalizationScope.Shared)]
[WebBrowsable(true)]
[System.ComponentModel.
Category("Parent Child Properties")]
[WebDisplayName("SecondChildList")]
[WebDescription("Second Child List")]
public string SecondChildList
{
get
{
if (_SecondChildList == null)
{
_SecondChildList = "";
}
return _SecondChildList.Trim();
}
set { _SecondChildList = value.Trim(); }
}
[Personalizable(PersonalizationScope.Shared)]
[WebBrowsable(true)]
[System.ComponentModel.
Category("Parent Child Properties")]
[WebDisplayName("SecondChildView")]
[
WebDescription("Second Child View")]
public string SecondChildView
{
get
{
if (_SecondChildView == null)
{
_SecondChildView = "";
}
return _SecondChildView.Trim();
}
set { _SecondChildView = value.Trim(); }
}
[Personalizable(PersonalizationScope.Shared)]
[WebBrowsable(true)]
[System.ComponentModel.
Category("Parent Child Properties")]
[WebDisplayName("SecondChildIDField")]
[WebDescription("Second Child ID Field (Typically ID)")]
public string SecondChildIDField
{
get
{
if (_SecondChildIDField == null)
{
_SecondChildIDField = "";
}
return _SecondChildIDField.Trim();
}
set { _SecondChildIDField = value.Trim(); }
}
[Personalizable(PersonalizationScope.Shared)]
[WebBrowsable(true)]
[System.ComponentModel.Category("Parent Child Properties")]
[WebDisplayName("SecondChildParentIDField")]
[WebDescription("Second Child ID Field")]
public string SecondChildParentIDField
{
get
{
if (_SecondChildParentIDField == null)
{
_SecondChildParentIDField = "";
}
return _SecondChildParentIDField.Trim();
}
set { _SecondChildParentIDField = value.Trim(); }
}
#endregion
private const string ByeByeIncludeScriptKey = "myByeByeIncludeScript";
private const string EmbeddedScriptFormat = "<script language=javascript>function ByeBye(){ alert('Test Code'); }</script> ";
private const string DisableAjaxScriptKey = "myDisableAjaxIncludeScript";
private const string DisableAjaxForExport = "<script language=javascript>function onRequestStart(sender, args) { if (args.get_eventTarget().indexOf(\"cmdExport\") >= 0);args.set_enableAjax(false);alert('Ajax Disabled'); }</script>";
private void WebPart_ClientScript_PreRender(object sender , System.EventArgs e )
{
if (!Page.IsClientScriptBlockRegistered(ByeByeIncludeScriptKey))
Page.RegisterClientScriptBlock(ByeByeIncludeScriptKey,
EmbeddedScriptFormat);
if (!Page.IsClientScriptBlockRegistered(DisableAjaxScriptKey))
Page.RegisterClientScriptBlock(DisableAjaxScriptKey,
DisableAjaxForExport);
//ajaxManager.ClientEvents.OnRequestStart = "onRequestStart";
}
public ParentChildGrid()
{
this.ExportMode = WebPartExportMode.All;
this.PreRender += new EventHandler(WebPart_ClientScript_PreRender);
}
private void onRequestStart()
{
ajaxManager.EnableAJAX =
false;
}
protected override void OnInit(EventArgs e)
{
try
{
base.OnInit(e);
Page.ClientScript.RegisterStartupScript(
typeof(ParentChildGrid), this.ID, "_spOriginalFormAction = document.forms[0].action;_spSuppressFormOnSubmitWrapper=true;", true);
if (this.Page.Form != null)
{
string formOnSubmitAtt = this.Page.Form.Attributes["onsubmit"];
if (!string.IsNullOrEmpty(formOnSubmitAtt) && formOnSubmitAtt == "return _spFormOnSubmitWrapper();")
{
this.Page.Form.Attributes["onsubmit"] = "_spFormOnSubmitWrapper();";
}
}
scriptManager =
ScriptManager.GetCurrent(this.Page);
if (scriptManager == null)
{
scriptManager =
new RadScriptManager();
this.Page.Form.Controls.AddAt(0, scriptManager);
}
scriptManager.RegisterPostBackControl(cmdExport);
}
catch (Exception ex)
{
HandleException(ex);
}
}
protected override void OnLoad(EventArgs e)
{
ScriptManager.GetCurrent(Page).RegisterPostBackControl(cmdExport);
if (!_error)
{
try
{
base.OnLoad(e);
this.EnsureChildControls();
base.OnLoad(e);
if (_ParentList != null)
{
if (_ParentList != "")
{
panel =
new Panel();
panel.ID =
"Panel1";
this.Controls.Add(panel);
oGrid =
new RadGrid();
DefineComplexGrid();
oGrid.GridExporting +=
new OnGridExportingEventHandler(oGrid_GridExporting);
panel.Controls.Add(oGrid);
//DefineSimpleMasterDetail();
cmdExport.Click +=
new EventHandler(cmdExport_Click);
cmdExport.Text =
"Export";
Button cmdExpandAll = new Button();
cmdExpandAll.Text =
"Expand All";
cmdExpandAll.Click +=
new EventHandler(cmdExpandAll_Click);
panel.Controls.Add(cmdExpandAll);
ajaxManager =
RadAjaxManager.GetCurrent(this.Page);
if (ajaxManager == null)
{
ajaxManager =
new RadAjaxManager();
ajaxManager.ID =
"RadAjaxManager1";
Controls.Add(ajaxManager);
this.Page.Items.Add(typeof(RadAjaxManager), ajaxManager);
}
ajaxManager.AjaxSettings.AddAjaxSetting(oGrid, panel);
panel.Controls.Add(cmdExport);
ajaxManager.AjaxRequest +=
new RadAjaxControl.AjaxRequestDelegate(ajaxManager_AjaxRequest);
this.Controls.Add(new LiteralControl("<br><br><input class='ms-SPButton' value=\'Test Code\' type=button onclick=\"ByeBye();\" >"));
ajaxManager.ClientEvents.OnRequestStart =
"onRequestStart";
}
}
}
catch (Exception ex)
{
HandleException(ex);
}
}
}
void oGrid_GridExporting(object source, GridExportingArgs e)
{
//throw new NotImplementedException();
}
void ajaxManager_AjaxRequest(object sender, AjaxRequestEventArgs e)
{
ajaxManager.EnableAJAX =
false;
}
void cmdExpandAll_Click(object sender, EventArgs e)
{
try
{
foreach (GridItem item in oGrid.MasterTableView.Items)
{
item.Expanded =
true;
}
}
catch (Exception ex)
{
HandleException(ex);
}
}
void cmdExport_Click(object sender, EventArgs e)
{
try
{
ajaxManager.ClientEvents.OnRequestStart =
"onRequestStart";
oGrid.ExportSettings.ExportOnlyData =
true;
oGrid.ExportSettings.IgnorePaging =
true;
oGrid.ExportSettings.OpenInNewWindow =
true;
oGrid.MasterTableView.HierarchyDefaultExpanded =
true;
if (FirstChildList.Trim() != "")
oGrid.MasterTableView.DetailTables[0].HierarchyDefaultExpanded =
true;
if (SecondChildList.Trim() != "")
oGrid.MasterTableView.DetailTables[1].HierarchyDefaultExpanded =
true;
oGrid.Rebind();
oGrid.MasterTableView.ExportToExcel();
}
catch (Exception ex)
{
HandleException(ex);
}
}
//private void DefineSimpleGrid()
//{
// try
// {
// oGrid.ID = "Master";
// oGrid.PageSize = 10;
// oGrid.AllowPaging = true;
// oGrid.AllowSorting = true;
// oGrid.Skin = "WebBlue";
// oGrid.GroupingEnabled = true;
// oGrid.NeedDataSource += new GridNeedDataSourceEventHandler(oGrid_NeedDataSource);
// oGrid.ShowStatusBar = true;
// oGrid.ShowGroupPanel = true;
// oGrid.GroupingEnabled = true;
// oGrid.ClientSettings.AllowDragToGroup = true;
// oGrid.ClientSettings.AllowColumnsReorder = true;
// }
// catch (Exception ex)
// {
// HandleException(ex);
// }
//}
private DataTable GetDataTable(String cListName, String ViewName)
{
try
{
SPList list = SPContext.Current.Web.Lists[cListName];
SPView view = list.Views[ViewName];
SPListItemCollection items = list.GetItems(view);
if (items != null)
{
if (items.Count > 0)
return items.GetDataTable();
}
}
catch (Exception ex)
{
HandleException(ex);
}
return null;
}
//private void DefineSimpleMasterDetail()
//{
// try
// {
// oGrid.MasterTableView.DataKeyNames = new string[] { "ID" };
// oGrid.Skin = "Default";
// oGrid.Width = Unit.Percentage(100);
// oGrid.PageSize = 5;
// oGrid.AllowPaging = true;
// oGrid.MasterTableView.PageSize = 15;
// oGrid.MasterTableView.DataSource = GetDataTable(_ParentList, _ParentView);
// GridTableView tableViewOrders = new GridTableView(oGrid);
// tableViewOrders.DataSource = GetDataTable(_FirstChildList, _FirstChildView);
// tableViewOrders.DataKeyNames = new string[] { _ParentIDField };
// GridRelationFields relationFields = new GridRelationFields();
// relationFields.MasterKeyField = _FirstChildIDField;
// relationFields.DetailKeyField = _FirstChildParentIDField;
// tableViewOrders.ParentTableRelation.Add(relationFields);
// oGrid.MasterTableView.DetailTables.Add(tableViewOrders);
// }
// catch (Exception ex)
// {
// HandleException(ex);
// }
//}
private void DefineComplexGrid()
{
try
{
oGrid.ID =
"RadGrid1";
//oGrid.Width = Unit.Percentage(98);
oGrid.PageSize =
Convert.ToInt32(PageSize);
oGrid.AllowPaging =
true;
oGrid.AllowSorting =
true;
oGrid.PagerStyle.Mode =
GridPagerMode.NextPrevAndNumeric;
oGrid.ShowStatusBar =
true;
oGrid.ClientSettings.Resizing.AllowColumnResize =
true;
oGrid.DetailTableDataBind +=
new GridDetailTableDataBindEventHandler(oGrid_DetailTableDataBind);
oGrid.NeedDataSource +=
new GridNeedDataSourceEventHandler(oGrid_NeedDataSource);
oGrid.ColumnCreated +=
new GridColumnCreatedEventHandler(oGrid_ColumnCreated);
oGrid.MasterTableView.Name = _ParentList;
if (_FirstChildList != "" || _SecondChildList != "")
{
oGrid.MasterTableView.PageSize =
Convert.ToInt32(PageSize);
oGrid.MasterTableView.DataKeyNames =
new string[] { _ParentIDField };
oGrid.MasterTableView.HierarchyLoadMode =
GridChildLoadMode.ServerOnDemand;
}
if (_FirstChildList != "")
{
GridTableView tableViewFirstChild = new GridTableView(oGrid);
tableViewFirstChild.Width =
Unit.Percentage(100);
tableViewFirstChild.HierarchyLoadMode =
GridChildLoadMode.ServerOnDemand;
tableViewFirstChild.DataKeyNames =
new string[] { _FirstChildIDField };
tableViewFirstChild.Name = _FirstChildList;
GridRelationFields FirstChildrelationFields = new GridRelationFields();
FirstChildrelationFields.MasterKeyField = _ParentIDField;
FirstChildrelationFields.DetailKeyField = _FirstChildParentIDField;
tableViewFirstChild.ParentTableRelation.Add(FirstChildrelationFields);
tableViewFirstChild.Caption = _FirstChildList;
oGrid.MasterTableView.DetailTables.Add(tableViewFirstChild);
}
if (_SecondChildList != "")
{
GridTableView tableViewSecondChild = new GridTableView(oGrid);
tableViewSecondChild.Width =
Unit.Percentage(100);
tableViewSecondChild.HierarchyLoadMode =
GridChildLoadMode.ServerOnDemand;
tableViewSecondChild.DataKeyNames =
new string[] { _SecondChildIDField };
tableViewSecondChild.Name = _SecondChildList;
GridRelationFields SecondChildrelationFields = new GridRelationFields();
SecondChildrelationFields.MasterKeyField = _ParentIDField;
SecondChildrelationFields.DetailKeyField = _SecondChildParentIDField;
tableViewSecondChild.Caption = _SecondChildList;
tableViewSecondChild.ParentTableRelation.Add(SecondChildrelationFields);
oGrid.MasterTableView.DetailTables.Add(tableViewSecondChild);
}
oGrid.ShowStatusBar =
true;
oGrid.ShowGroupPanel =
true;
oGrid.GroupingEnabled =
true;
oGrid.ClientSettings.AllowDragToGroup =
true;
oGrid.ClientSettings.AllowColumnsReorder =
true;
oGrid.Skin =
"Web20";
}
catch (Exception ex)
{
HandleException(ex);
}
}
void oGrid_ColumnCreated(object sender, GridColumnCreatedEventArgs e)
{
try
{
//if (e.Column.HeaderText == "ID" || e.Column.HeaderText == "Created")
//{
// e.Column.Display = false;
// return;
//}
String cOwnerTable = "";
cOwnerTable = e.OwnerTableView.Name;
if (cOwnerTable.Trim() != "" && e.Column.HeaderText != "" && e.Column.HeaderText != _FirstChildParentIDField && e.Column.HeaderText != _SecondChildParentIDField)
{
SPList CurrentList = SPContext.Current.Web.Lists[e.OwnerTableView.Name];
e.Column.HeaderText = GetFieldDisplayName(e.Column.HeaderText, CurrentList);
SPField oField = CurrentList.Fields[e.Column.HeaderText];
GridBoundColumn col = (GridBoundColumn)e.Column;
switch (oField.Type)
{
case SPFieldType.Currency:
col.DataFormatString =
"{0:C}";
break;
case SPFieldType.DateTime:
SPFieldDateTime oDateTime = (SPFieldDateTime)oField;
if (oDateTime.DisplayFormat == SPDateTimeFieldFormatType.DateOnly)
col.DataFormatString =
"{0:d}";
break;
default:
break;
}
}
}
catch (Exception ex)
{
HandleException(ex);
}
}
private DataTable GetChildDataTable(GridDetailTableDataBindEventArgs e, String cChildListName, String cChildView,String cParentIDField)
{
try
{
GridDataItem parentItem = e.DetailTableView.ParentItem as GridDataItem;
SPList FirstChildList = SPContext.Current.Web.Lists[cChildListName];
SPView oView = FirstChildList.Views[cChildView];
String cContractID = parentItem[_ParentIDField].Text;
SPQuery oChildQuery = new SPQuery();
if (Occurs(cParentIDField, oView.Query) == 2)
{
String cNewQuery = oView.Query;
Int32 iPos = cNewQuery.IndexOf(cParentIDField) + cParentIDField.Length;
String cPartOne = cNewQuery.Substring(0,cNewQuery.IndexOf(cParentIDField, iPos));
String cPartTwo = cNewQuery.Substring(cNewQuery.IndexOf(cParentIDField, iPos) + cParentIDField.Length);
cNewQuery = cPartOne + cContractID + cPartTwo;
oChildQuery.Query = cNewQuery;
oChildQuery.Query =
"<Where><Eq><FieldRef Name='" + cParentIDField + "' /><Value Type='Text'>" + cContractID + "</Value></Eq></Where>";
}
else
{
oChildQuery.Query =
"<Where><Eq><FieldRef Name='" + cParentIDField + "' /><Value Type='Text'>" + cContractID + "</Value></Eq></Where>";
}
SPViewFieldCollection oViewFields = oView.ViewFields;
oViewFields.Add(cParentIDField);
String cViewFields = oViewFields.SchemaXml;
oChildQuery.ViewFields = cViewFields;
SPListItemCollection items = FirstChildList.GetItems(oChildQuery);
if (items != null)
{
if (items.Count > 0)
{
return items.GetDataTable();
}
}
}
catch (Exception ex)
{
//HandleException(ex);
}
return null;
}
void oGrid_DetailTableDataBind(object source, GridDetailTableDataBindEventArgs e)
{
try
{
GridDataItem parentItem = e.DetailTableView.ParentItem as GridDataItem;
if (parentItem.Edit)
{
return;
}
if (e.DetailTableView.Name == _FirstChildList)
{
Child1DataTable = GetChildDataTable(e, _FirstChildList, _FirstChildView, _FirstChildParentIDField);
e.DetailTableView.DataSource = Child1DataTable;
}
if (e.DetailTableView.Name == _SecondChildList)
{
Child2DataTable = GetChildDataTable(e, _SecondChildList, _SecondChildView, _SecondChildParentIDField);
e.DetailTableView.DataSource = Child2DataTable;
}
}
catch (Exception ex)
{
HandleException(ex);
}
}
void oGrid_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
{
try
{
if (!e.IsFromDetailTable)
{
SPList ParentList = SPContext.Current.Web.Lists[_ParentList];
oView = ParentList.Views[_ParentView];
SPQuery ParentQuery = new SPQuery();
ParentQuery.Query = oView.Query;
ParentQuery.RowLimit = 100000;
ParentQuery.ViewFields = oView.ViewFields.SchemaXml;
SPListItemCollection oItems = SPContext.Current.Web.Lists[_ParentList].GetItems(ParentQuery);
ParentDataTable = oItems.GetDataTable();
oGrid.DataSource = ParentDataTable;
}
}
catch (Exception ex)
{
HandleException(ex);
}
}
private string GetFieldDisplayName(String cInternalName, SPList oList)
{
try
{
foreach (SPField field in oList.Fields)
{
if (field.InternalName == cInternalName)
return field.Title;
}
}
catch (Exception ex)
{
HandleException(ex);
}
return cInternalName;
}
private Int32 Occurs(String SearchFor, String SearchIn)
{
Int32 Count = 0;
Int32 iPos = 0;
try
{
while (SearchIn.IndexOf(SearchFor, iPos) != -1)
{
Count++;
iPos = SearchIn.IndexOf(SearchFor, iPos) + 1;
}
}
catch (Exception ex)
{
HandleException(ex);
}
return Count;
}
private void HandleException(Exception ex)
{
this._error = true;
try
{
this.Controls.Clear();
this.Controls.Add(new LiteralControl(ex.Message));
}
catch
{
}
}
} //End Class
As a follow-up, it appears the problem was that there were NULL values in John's original data. These nulls were causing problems during the data export. Fixing the null values also fixed the Excel export. Original solution on Telerik.com forums:
http://www.telerik.com/community/forums/aspnet-ajax/grid/extremely-frustrated-please-help-with-radgrid-export-of-multi-tabe-view.aspx