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;
}
Related
I found a small detail on the sales order screen, which when adding two custom fields generates a new price as shown in the image.
but at the moment of generating the new value at the unit price I am surprised that the ext price will not be updated and the other fields which are marked with green.
I am attaching my code and I would like them to tell me what I am failing or what I need to do, so that when updating the unit price the other fields are automatically updated since I am only modifying the unitprice.
besides that I have also used the commit change = true, but it is not working for me.
I thank you for your support,
namespace PX.Objects.SO
{
public class PESKSOOrderEntry6_Extension : PXGraphExtension<SOOrderEntry>
{
#region Event Handlers
public const string PMBudgetType = "I";
//STATE
public const string eNY = "NY";
public const string ePA = "PA";
//UOM
public const string uTN = "TN";
public const string uGL = "GL";
protected virtual void SOLine_CuryUnitPrice_FieldUpdated(PXCache sender, PXFieldUpdatedEventArgs e)
{
sender.SetValuePending<SOLine.curyDiscPrice>(e.Row, PXCache.NotSetValue);
}
protected void _(Events.RowUpdated<SOLine> e)
{
var row = (SOLine)e.Row;
var row1 = (SOLine)e.OldRow;
SOOrder soOrder = Base.Document.Current;
if (row == null) return;
var rowExt = row.GetExtension<SOLineExt>();
var rowExt1 = row1.GetExtension<SOLineExt>();
PMRevenueBudget pmBudget = GetPMRevenueBudget(row.ProjectID, row.TaskID, row.InventoryID, PMBudgetType, row.UOM);
var pmBudgetExt = pmBudget.GetExtension<PMBudgetExt>();
if (row.InventoryID != null && row.OrderQty != 0 && row.TaskID != null && pmBudget != null && (rowExt.UsrSPriceIndex == false || rowExt.UsrSPriceIndex == null))
{
rowExt.UsrSPriceIndex = pmBudgetExt.UsrSPriceIndex;
rowExt.UsrQuoteUnitPrice = pmBudget.Rate;
row.CuryUnitPrice = pmBudget.Rate;
//row.CuryExtPrice = row.OrderQty * row.CuryUnitPrice;
//row.CuryDiscPrice = row.CuryExtPrice;
//row.CuryLineAmt = row.CuryExtPrice;
//row.CuryUnbilledAmt = row.CuryExtPrice;
}
else
{
rowExt.UsrSPriceIndex = false;
}
if (row.InventoryID != null && row.OrderQty != 0 && row.TaskID != null && pmBudget != null && rowExt.UsrSPriceIndex == true)
{
rowExt.UsrQuoteUnitPrice = pmBudget.Rate;
PESKPriceIndexCat pricecat = GetPESKPriceIndexCat(row.InventoryID);
decimal? nempriceIndex = 0, baseIndex = 0, aPercent = 0;
nempriceIndex = NewEfecctiveMPriceIndex(soOrder, pricecat, nempriceIndex);
baseIndex = BaseIndex(pmBudgetExt, baseIndex);
aPercent = AsphaltPercent(row, pricecat, aPercent);
if (pricecat != null && pricecat.State == eNY)
{
if (row.UOM == uTN)
{
//((New Effective Monthly Price Index) – (Base Index)) x Asphalt Percent
rowExt.UsrIndexAdj = (((nempriceIndex) - (baseIndex)) * (aPercent / 100));
row.CuryUnitPrice = rowExt.UsrQuoteUnitPrice + rowExt.UsrIndexAdj;
//row.CuryExtPrice = row.OrderQty * row.CuryUnitPrice;
//row.CuryDiscPrice = row.CuryExtPrice;
//row.CuryLineAmt = row.CuryExtPrice;
//row.CuryUnbilledAmt = row.CuryExtPrice;
}
if (row.UOM == uGL)
{
//(((New Effective Monthly Index Price) – (Base Index))/ 235) x Asphalt Percent
decimal? num = 235;
rowExt.UsrIndexAdj = ((((nempriceIndex) - (baseIndex)) / num) * (aPercent / 100));
row.CuryUnitPrice = rowExt.UsrQuoteUnitPrice + rowExt.UsrIndexAdj;
//row.CuryExtPrice = row.OrderQty * row.CuryUnitPrice;
//row.CuryDiscPrice = row.CuryExtPrice;
//row.CuryLineAmt = row.CuryExtPrice;
//row.CuryUnbilledAmt = row.CuryExtPrice;
}
}
if (pricecat != null && pricecat.State == ePA)
{
if (row.UOM == uTN)
{
var resul = (((nempriceIndex) - (baseIndex)) * (aPercent / 100));
var diff = resul - baseIndex;
decimal? diff1 = baseIndex * Convert.ToDecimal(0.1);
if (diff == diff1)
{
//((New Effective Monthly Price Index) – (Base Index)) x Asphalt Percent
rowExt.UsrIndexAdj = resul;
row.CuryUnitPrice = rowExt.UsrQuoteUnitPrice + rowExt.UsrIndexAdj;
//row.CuryExtPrice = row.OrderQty * row.CuryUnitPrice;
//row.CuryDiscPrice = row.CuryExtPrice;
//row.CuryLineAmt = row.CuryExtPrice;
//row.CuryUnbilledAmt = row.CuryExtPrice;
}
}
if (row.UOM == uGL)
{
decimal? num = 235;
var resul = ((((nempriceIndex) - (baseIndex)) / num) * (aPercent / 100));
var diff = resul - baseIndex;
decimal? diff1 = baseIndex * Convert.ToDecimal(0.1);
if (diff == diff1)
{
//(((New Effective Monthly Index Price) – (Base Index))/ 235) x Asphalt Percent
rowExt.UsrIndexAdj = resul;
row.CuryUnitPrice = rowExt.UsrQuoteUnitPrice + rowExt.UsrIndexAdj;
//row.CuryExtPrice = row.OrderQty * row.CuryUnitPrice;
//row.CuryDiscPrice = row.CuryExtPrice;
//row.CuryLineAmt = row.CuryExtPrice;
//row.CuryUnbilledAmt = row.CuryExtPrice;
}
}
}
}
}
//how to calculate field Index Adj
protected void _(Events.RowSelected<SOLine> e)
{
var row = (SOLine)e.Row;
SOOrder soOrder = Base.Document.Current;
if (row == null) return;
var rowExt = row.GetExtension<SOLineExt>();
#region Enabled and Disable
PMRevenueBudget pmBudget = GetPMRevenueBudget(row.ProjectID, row.TaskID, row.InventoryID, PMBudgetType, row.UOM);
if (row.InventoryID != null && row.OrderQty != 0 && row.TaskID != null && pmBudget != null)
{
PXUIFieldAttribute.SetEnabled<SOLineExt.usrQuoteUnitPrice>(e.Cache, e.Row, true);
PXUIFieldAttribute.SetEnabled<SOLineExt.usrIndexAdj>(e.Cache, e.Row, true);
rowExt.UsrQuoteUnitPrice = 0;
rowExt.UsrIndexAdj = 0;
}
else
{
PXUIFieldAttribute.SetEnabled<SOLineExt.usrQuoteUnitPrice>(e.Cache, e.Row, false);
PXUIFieldAttribute.SetEnabled<SOLineExt.usrIndexAdj>(e.Cache, e.Row, false);
}
if (rowExt.UsrSPriceIndex == true)
{
PXUIFieldAttribute.SetEnabled<SOLineExt.usrIndexAdj>(e.Cache, e.Row, true);
}
else
{
PXUIFieldAttribute.SetEnabled<SOLineExt.usrIndexAdj>(e.Cache, e.Row, false);
rowExt.UsrQuoteUnitPrice = 0;
rowExt.UsrIndexAdj = 0;
}
#endregion
}
#region Method
private decimal? AsphaltPercent(SOLine row, PESKPriceIndexCat pricecat, decimal? aPercent)
{
foreach (PESKStockItem res3 in PXSelect<PESKStockItem,
Where<PESKStockItem.inventoryID, Equal<Required<PESKStockItem.inventoryID>>,
And<PESKStockItem.categoryID, Equal<Required<PESKStockItem.categoryID>>>
>>.Select(Base, row.InventoryID, pricecat.CategoryCD))
{
if (res3 != null)
{
//Asphalt Percent
aPercent = res3.AsphaltPct;
}
}
return aPercent;
}
private decimal? BaseIndex(PMBudgetExt contraExt, decimal? baseIndex)
{
PESKPriceIndexDetail res2 = PXSelectJoin<PESKPriceIndexDetail,
InnerJoin<PESKPRC,
On<PESKPRC.priceIndexID, Equal<PESKPriceIndexDetail.priceIndexID>>>,
Where<PESKPRC.recordID, Equal<Required<PESKPRC.recordID>>>>
.Select(Base, contraExt.UsrPRCNumber);
if (res2 != null)
{
//Base Index
baseIndex = res2.BaseIndex;
}
return baseIndex;
}
private decimal? NewEfecctiveMPriceIndex(SOOrder soOrder, PESKPriceIndexCat pricecat, decimal? nempriceIndex)
{
Dictionary<int?, object> Mydict1 = new Dictionary<int?, object>();
Dictionary<int?, object> Mydict2 = new Dictionary<int?, object>();
foreach (PESKPriceIndexDetail res in PXSelect<PESKPriceIndexDetail,
Where<PESKPriceIndexDetail.categoryID, Equal<Required<PESKPriceIndexDetail.categoryID>>>>
.Select(Base, pricecat.CategoryID))
{
if (res != null)
{
if (res.EffDate <= soOrder.OrderDate)
{
if (!Mydict1.ContainsKey(res.PriceIndexID))
{
Mydict1.Add(res.PriceIndexID, res.EffDate);
}
}
}
}
var maxfecha = (from mydic in Mydict1 select mydic.Value).Max();
nempriceIndex = 0;
PESKPriceIndexDetail res1 = PXSelect<PESKPriceIndexDetail,
Where<PESKPriceIndexDetail.categoryID, Equal<Required<PESKPriceIndexDetail.categoryID>>,
And<PESKPriceIndexDetail.effDate, Equal<Required<PESKPriceIndexDetail.effDate>>>>>
.Select(Base, pricecat.CategoryID, maxfecha);
if (res1 != null)
{
//New Effective Monthly Price Index
nempriceIndex = res1.BaseIndex;
}
return nempriceIndex;
}
#endregion
#endregion
#region Metodos Realizados
public static PXGraph GetGraph(PXGraph graph = null)
{
if (graph == null)
{
graph = new PXGraph();
}
return graph;
}
public static List<TDac> PXResultSetToList<TDac>(PXResultset<TDac> resultSet) where TDac : class, IBqlTable, new()
{
List<TDac> list = new List<TDac>();
foreach (PXResult<TDac> item2 in resultSet)
{
TDac item = item2;
list.Add(item);
}
return list;
}
public static PMRevenueBudget GetPMRevenueBudget(int? ProjectID, int? TaskID, int? InventoryID, string PMBudgetType, string UOM, PXGraph graph = null)
{
graph = GetGraph(graph);
PXResultset<PMRevenueBudget> l = PXSelectBase<
PMRevenueBudget, PXSelect<
PMRevenueBudget,
Where<PMRevenueBudget.projectID, Equal<Required<PMRevenueBudget.projectID>>,
And<PMRevenueBudget.projectTaskID, Equal<Required<PMRevenueBudget.projectTaskID>>,
And<PMRevenueBudget.inventoryID, Equal<Required<PMRevenueBudget.inventoryID>>,
And<PMRevenueBudget.type, Equal<Required<PMRevenueBudget.type>>,
And<PMRevenueBudget.uOM, Equal<Required<PMRevenueBudget.uOM>>>>
>>>>.Config>
.Select(graph, ProjectID, TaskID, InventoryID, PMBudgetType, UOM);
return l;
}
public static PESKPriceIndexCat GetPESKPriceIndexCat(int? InventoryID, PXGraph graph = null)
{
graph = GetGraph(graph);
return PXSelectBase<
PESKPriceIndexCat, PXSelectJoin<
PESKPriceIndexCat,
InnerJoin<PESKStockItem,
On<PESKStockItem.categoryID,
Equal<PESKPriceIndexCat.categoryCD>>>,
Where<PESKStockItem.inventoryID,
Equal<Required<PESKStockItem.inventoryID>>>>.Config>
.Select(graph, InventoryID);
}
#endregion
}
}
By using graph.View.SetValueExt<>(), you can take advantage of field events, which is what updates those fields automatically.
It will take a bit of re-coding, but it would look something like this: (notice the first line and last two lines)
protected void _(Events.RowUpdated<SOLine> e)
{
var orderGraph = (SOOrderEntry)e.Cache.Graph; // ***NEW***
var row = (SOLine)e.Row;
var row1 = (SOLine)e.OldRow;
SOOrder soOrder = Base.Document.Current;
if (row == null) return;
var rowExt = row.GetExtension<SOLineExt>();
var rowExt1 = row1.GetExtension<SOLineExt>();
PMRevenueBudget pmBudget = GetPMRevenueBudget(row.ProjectID, row.TaskID, row.InventoryID, PMBudgetType, row.UOM);
var pmBudgetExt = pmBudget.GetExtension<PMBudgetExt>();
if (row.InventoryID != null && row.OrderQty != 0 && row.TaskID != null && pmBudget != null && (rowExt.UsrSPriceIndex == false || rowExt.UsrSPriceIndex == null))
{
rowExt.UsrSPriceIndex = pmBudgetExt.UsrSPriceIndex;
rowExt.UsrQuoteUnitPrice = pmBudget.Rate;
orderGraph.Transactions.SetValueExt<SOLine.curyUnitPrice>(row, pmBudget.Rate); // ***NEW***
//row.CuryUnitPrice = pmBudget.Rate; ***OLD***
//.... other code
}
}
I think this may resolve your issue.
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
`protected void GridFill(IList ListePointAcces)
{
grdRows.Rows.Clear();
UltraGridRow row = null;
// Row row = null;
UltraGridRow ssrow = null;
foreach (Salle salle in meSalle.Selectionner("LIBELLE"))
{
row = new UltraGridRow(new object[] { salle.Site().LIBELLE, salle.LIBELLE });
row.Key = salle.IDSALLE.ToString();
foreach (PointAcces pta in ListePointAcces)
{
if (pta.Salle.IDSALLE != salle.IDSALLE)
continue;
ssrow = new UltraGridRow(new object[] { pta.CODE, pta.LIBELLE, pta.LOGNAME, pta.COMMENTAIRE });
ssrow.Key = pta.IDPOINTACCES.ToString();
row.Rows.Add(ssrow);
}
if (row.Rows.Count > 0)
{
grdRows.Rows.Add(row);
}
}
}
`
I use the fallowing method to update a contact in Exchange over EWS:
private void UpdateContact(Microsoft.Exchange.WebServices.Data.Contact exContact, ContactInfo contact) {
var pathList = new List<string>();
try {
log.DebugFormat("Process ExchangeContact '{0}' with Contact '{1}'", (exContact.IsNew ? "<new>" : exContact.DisplayName), contact.Id);
exContact.GivenName = contact.AdditionalName;
exContact.Surname = contact.Name;
exContact.FileAsMapping = FileAsMapping.SurnameCommaGivenName;
exContact.CompanyName = "";
if (contact is PersonInfo) {
var person = (PersonInfo) contact;
if (person.PersonCompany != null && person.PersonCompany.Company != null) {
exContact.CompanyName = person.PersonCompany.Company.DisplayName;
}
exContact.ImAddresses[ImAddressKey.ImAddress1] = person.MessengerName;
exContact.ImAddresses[ImAddressKey.ImAddress2] = person.SkypeName;
}
// Specify the business, home, and car phone numbers.
var comm = contact.GetCommunication(Constants.CommunicationType.PhoneBusiness);
exContact.PhoneNumbers[PhoneNumberKey.BusinessPhone] = (comm != null ? comm.Value : null);
comm = contact.GetCommunication(Constants.CommunicationType.PhonePrivate);
exContact.PhoneNumbers[PhoneNumberKey.HomePhone] = (comm != null ? comm.Value : null);
comm = contact.GetCommunication(Constants.CommunicationType.PhoneMobile);
exContact.PhoneNumbers[PhoneNumberKey.MobilePhone] = (comm != null ? comm.Value : null);
comm = contact.GetCommunication(Constants.CommunicationType.MailBusiness);
exContact.EmailAddresses[EmailAddressKey.EmailAddress1] = (comm != null ? new EmailAddress(comm.Value) : null);
comm = contact.GetCommunication(Constants.CommunicationType.MailPrivate);
exContact.EmailAddresses[EmailAddressKey.EmailAddress2] = (comm != null ? new EmailAddress(comm.Value) : null);
// Specify two IM addresses.
// Specify the home address.
var address = contact.AddressList.FirstOrDefault(x => x.AddressType != null && x.AddressType.Id == Constants.AddressType.Private);
if (address != null) {
var paEntry = new PhysicalAddressEntry
{
Street = address.Street,
City = address.City,
State = address.Region,
PostalCode = address.PostalCode,
CountryOrRegion = address.CountryName
};
exContact.PhysicalAddresses[PhysicalAddressKey.Home] = paEntry;
if (contact.PostalAddress == address) {
exContact.PostalAddressIndex = PhysicalAddressIndex.Home;
}
} else {
exContact.PhysicalAddresses[PhysicalAddressKey.Home] = null;
}
address = contact.AddressList.FirstOrDefault(x => x.AddressType != null && x.AddressType.Id == Constants.AddressType.Business);
if (address != null) {
var paEntry = new PhysicalAddressEntry
{
Street = address.Street,
City = address.City,
State = address.Region,
PostalCode = address.PostalCode,
CountryOrRegion = address.CountryName
};
exContact.PhysicalAddresses[PhysicalAddressKey.Business] = paEntry;
if(contact.PostalAddress == address) {
exContact.PostalAddressIndex = PhysicalAddressIndex.Business;
}
} else {
exContact.PhysicalAddresses[PhysicalAddressKey.Business] = null;
}
// Save the contact.
if (exContact.IsNew) {
exContact.Save();
} else {
exContact.Update(ConflictResolutionMode.AlwaysOverwrite);
}
pathList.AddRange(this.AddFileAttachments(this.Access.IndependService.GetContact(exContact.Id.UniqueId), contact.GetDocuments()));
} catch(Exception e) {
log.Error("Error updating/inserting Contact in Exchange.", e);
} finally {
foreach (var path in pathList) {
this.Access.Context.Container.Resolve<IDocumentService>().UndoCheckOut(path);
}
}
}
When I do this for update, I get an Exception with Errorcode ErrorIncorrectUpdatePropertyCount on the line exContact.Update(ConflictResolutionMode.AlwaysOverwrite);
Can someone help me, what is the problem? - Thanks.
The solution is that I have to check, if the string-values are empty strings and in this case to set null. On this way, all is working.
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.