Create sales order via code 2017 R2 - acumatica

I am trying to create sales orders with data retrieved from my edi system. I have the code working to retrieve the orders, but I am having trouble creating the SO. I can create them with an external program using the SOAP interface, but I am trying to use the graph and insert them directly. I get an exception stating "{"Error: An error occurred during processing of the field CustomerLocationID : Object reference not set to an instance of an object.."}" but I successfully looked up the customer id and location id. Here is the code for my routine. I use similar code to create records for a new master/detail set of tables that I created.
Please advise if anyone has insight on creating sales orders in this manner. The error is thrown at the line:
soOrder.CurrentDocument.Insert(order);
I also am getting an error trying to access the extended fields for SOOrder and SOLine. I currently commented those fields out to see if I could create an order, but I will need to load data in them as well.
foreach (LingoOrderSearch ediOrder in doc850)
{
res850 = lingo.Retrieve850(ediOrder.documentId, "850");
SOOrderEntry soOrder = PXGraph.CreateInstance<SOOrderEntry>();
soOrder.Clear();
var order = new SOOrder();
//SOOrderExt orderExt = order.GetExtension<SOOrderExt>();
order.OrderType = "SO";
order.Status = "Open";
if (res850.Data850.partner == "BEDBATH" || res850.Data850.partner == "BEDBATH_CAN")
customerLookup = "BBB";
else
customerLookup = res850.Data850.partner;
CustomerMaint customerGraph = PXGraph.CreateInstance<CustomerMaint>();
Customer arCustomer = PXSelect<Customer, Where<Customer.status, Equal<Required<Customer.status>>,
And<Customer.acctCD, Equal<Required<Customer.acctCD>>>>>.Select(this, "Active", customerLookup);
if (arCustomer == null)
throw new PXException("Unable to find customer " + customerLookup + " (partner:" + res850.Data850.partner + ")");
order.CustomerID = arCustomer.BAccountID;
CustomerLocationMaint customerLocationGraph = PXGraph.CreateInstance<CustomerLocationMaint>();
Location arCustomerLocation = PXSelect<Location, Where<Location.isActive, Equal<Required<Location.isActive>>,
And<Location.bAccountID, Equal<Required<Location.bAccountID>>,
And<Location.locationCD, Equal<Required<Location.locationCD>>>>>>
.Select(this, true, arCustomer.BAccountID, res850.Data850.location);
if (arCustomerLocation == null)
throw new PXException("Unable to find customer location" + customerLookup + " / " +
res850.Data850.location + " (partner:" + res850.Data850.partner + ")");
order.CustomerLocationID = arCustomerLocation.LocationID;
order.CustomerOrderNbr = res850.Data850.poNumber;
order.ExtRefNbr = res850.Data850.documentId.ToString();
//orderExt.UsrEDICustomerVendorId = res850.Data850.vendor;
//orderExt.UsrEDICustomerId = res850.Data850.partner;
if (!DateTime.TryParse(res850.Data850.poDate, out tempDate))
{
tempDate = DateTime.Today;
}
order.DocDate = tempDate;
DateTime.TryParse(res850.Data850.requestedDeliveryDate, out tempDate);
if (!DateTime.TryParse(res850.Data850.requestedDeliveryDate, out tempDate))
{
tempDate = DateTime.Today;
}
order.RequestDate = tempDate;
soOrder.CurrentDocument.Insert(order);
soOrder.Persist();
newOrderId = soOrder.CurrentDocument.Current.OrderNbr;
itemList = res850.Data850.items;
foreach (EdiDoc850Lingoitems item in itemList)
{
InventoryItemMaint invItemGraph = PXGraph.CreateInstance<InventoryItemMaint>();
InventoryItem invItem = PXSelect<InventoryItem,
Where<InventoryItem.itemStatus, Equal<Required<InventoryItem.itemStatus>>,
And<InventoryItem.inventoryCD, Equal<Required<InventoryItem.inventoryCD>>>>>
.Select(this, "Active", item.vendorItem);
if (invItem == null)
throw new PXException("Unable to locate item " + item.vendorItem);
var line = new SOLine();
//SOLineExt lineExt = line.GetExtension<SOLineExt>();
line.OrderNbr = newOrderId;
line.InventoryID = invItem.InventoryID;
line.Qty = item.qtyOrder;
line.ShipComplete = "Ship Complete";
Int32 tempLine = 0;
if (Int32.TryParse(item.lineNo, out tempLine)) { };
//lineExt.UsrEDILineNbr = tempLine;
soOrder.Transactions.Insert(line);
}
}
}

Hopefully, the sample below will help move forward with your task:
SOOrderEntry soOrder = PXGraph.CreateInstance<SOOrderEntry>();
var order = new SOOrder();
order.OrderType = SOOrderTypeConstants.SalesOrder;
order = soOrder.CurrentDocument.Insert(order);
Customer arCustomer = PXSelect<Customer, Where<Customer.status, Equal<Required<Customer.status>>,
And<Customer.acctCD, Equal<Required<Customer.acctCD>>>>>.Select(this, "Active", "ABARTENDE");
if (arCustomer == null)
throw new PXException("Unable to find customer");
order.CustomerID = arCustomer.BAccountID;
order = soOrder.CurrentDocument.Update(order);
Location arCustomerLocation = PXSelect<Location, Where<Location.isActive, Equal<Required<Location.isActive>>,
And<Location.bAccountID, Equal<Required<Location.bAccountID>>,
And<Location.locationCD, Equal<Required<Location.locationCD>>>>>>
.Select(this, true, arCustomer.BAccountID, "CHICAGO");
if (arCustomerLocation == null)
throw new PXException("Unable to find customer location");
order.CustomerLocationID = arCustomerLocation.LocationID;
order.CustomerOrderNbr = "res850.Data850.poNumber";
order.ExtRefNbr = "res850.Data850.documentId";
order.RequestDate = DateTime.Today;
soOrder.CurrentDocument.Update(order);
for(int i = 0; i < 3; i++)
{
InventoryItem invItem = PXSelect<InventoryItem,
Where<InventoryItem.itemStatus, Equal<Required<InventoryItem.itemStatus>>,
And<InventoryItem.inventoryCD, Equal<Required<InventoryItem.inventoryCD>>>>>
.Select(this, "Active", "AALEGO500");
if (invItem == null)
throw new PXException("Unable to locate item");
var line = soOrder.Transactions.Insert();
line.InventoryID = invItem.InventoryID;
line.Qty = 1;
line.ShipComplete = SOShipComplete.ShipComplete;
soOrder.Transactions.Update(line);
}
soOrder.Actions.PressSave();

Related

Add an additional line on the grid

I am looking for help, I hope I can solve this problem.
I've created a new screen and I'm filtering all the Revalue Accounts information.
With this screen, what I want to do is insert and at the same time add an additional new line within the grid.
Here is my new created screen and the button that inserts GLTran
I am attaching an image where I want the line to be added at insert time
Here I share code that I have and it does not work for the additional line.
private void CreateDNGL(Batch batch)
{
var graph = PXGraph.CreateInstance<JournalEntry>();
if (graph.BatchModule.Current == null)
{
Batch cmbatch = new Batch();
cmbatch.BranchID = batch.BranchID;
cmbatch.Module = batch.Module;
cmbatch.Status = "U";
cmbatch.AutoReverse = true;
cmbatch.Released = true;
cmbatch.Hold = false;
cmbatch.CuryDebitTotal = batch.CuryDebitTotal;
cmbatch.CuryCreditTotal = batch.CuryCreditTotal;
cmbatch.FinPeriodID = batch.FinPeriodID;
cmbatch.CuryID = batch.CuryID;
cmbatch.CuryInfoID = batch.CuryInfoID;
cmbatch.DebitTotal = batch.DebitTotal;
cmbatch.CreditTotal = batch.CreditTotal;
cmbatch.Description = "Head new insert";
cmbatch = graph.BatchModule.Insert(cmbatch);
}
foreach (GLTran item in PXSelect<GLTran,
Where<GLTran.module, Equal<Required<GLTran.module>>,
And<GLTran.batchNbr, Equal<Required<GLTran.batchNbr>>>>>.Select(this, batch.Module, batch.BatchNbr))
{
GLTran tran = new GLTran();
tran.SummPost = item.SummPost;
tran.ZeroPost = false;
tran.DebitAmt = item.DebitAmt;
tran.CreditAmt = item.CreditAmt;
tran.CuryDebitAmt = item.CuryDebitAmt;
tran.CuryCreditAmt = item.CuryCreditAmt;
tran.AccountID = item.AccountID;
tran.SubID = item.SubID;
tran.LineNbr = item.LineNbr;
tran.LedgerID = item.LedgerID;
tran.TranType = item.TranType;
tran.TranClass = item.TranClass;
tran.RefNbr = string.Empty;
tran.FinPeriodID = item.FinPeriodID;
tran.TranDesc = "Test detail";
tran.Released = true;
tran.ReferenceID = item.ReferenceID;
tran = graph.GLTranModuleBatNbr.Insert(tran);
Account account = PXSelect<Account, Where<Account.accountID,
Equal<Required<Account.accountID>>>>.Select(graph, item.AccountID);
xLocEquivalAcct equivalAcct = PXSelect<xLocEquivalAcct, Where<xLocEquivalAcct.acctCD,
Equal<Required<xLocEquivalAcct.acctCD>>>>.Select(graph, account.AccountCD);
if (equivalAcct != null)
{
/*here is added for an additional line*/
var glTran = graph.GLTranModuleBatNbr.Insert();
graph.GLTranModuleBatNbr.SetValueExt<GLTran.accountID>(glTran, 343567);
graph.GLTranModuleBatNbr.SetValueExt<GLTran.subID>(glTran, 281);
glTran.TranDesc = "add extra line";
if (item.DebitAmt != 0m && item.CreditAmt == 0m)
{
if (batch.Module == BatchModule.CM)
{
graph.GLTranModuleBatNbr.SetValueExt<GLTran.curyDebitAmt>(glTran, item.CuryDebitAmt);
graph.GLTranModuleBatNbr.SetValueExt<GLTran.debitAmt>(glTran, item.DebitAmt);
}
}
if (item.CreditAmt != 0m && item.DebitAmt == 0m)
{
if (batch.Module == BatchModule.CM)
{
graph.GLTranModuleBatNbr.SetValueExt<GLTran.curyCreditAmt>(glTran, item.CuryCreditAmt);
graph.GLTranModuleBatNbr.SetValueExt<GLTran.creditAmt>(glTran, item.CreditAmt);
}
}
glTran = graph.GLTranModuleBatNbr.Update(glTran);
}
}
graph.Save.Press();
}
I hope I was clear with my question.
This code will create a copy of the originating batch and insert additional lines.
#Warning Your original code was attempting to create a batch that was already released but unposted. I can update my answer to match your requirement but this will break Acumatica work-flow.
Please find code example below :
public class JournalEntryExtension : PXGraphExtension<JournalEntry>
{
public PXAction<Batch> CopyCreate;
//CommitChanges being set to false allows the graph to not be considered dirty when there are errors that we manually show on screen. Case #207998
[PXButton(CommitChanges = false)]
[PXUIField(DisplayName = "Copy Create", MapEnableRights = PXCacheRights.Update, MapViewRights = PXCacheRights.Update, Enabled = true)]
protected virtual IEnumerable copyCreate(PXAdapter pxAdapter)
{
if (Base.BatchModule.Current != null)
{
if (Base.IsDirty)
{
Base.BatchModule.Ask("You must discard your unsaved changes to be able to press this button.", MessageButtons.OK);
}
else
{
Batch batch = Base.BatchModule.Current;
PXLongOperation.StartOperation(this, () => CreateDNGL(batch));
}
}
return pxAdapter.Get();
}
private static void CreateDNGL(Batch batch)
{
JournalEntry graph = PXGraph.CreateInstance<JournalEntry>();
Batch newBatch = PXCache<Batch>.CreateCopy(batch);
newBatch.NoteID = null;
newBatch.Description = "Test header";
newBatch = graph.BatchModule.Insert(newBatch);
GLTran newTran;
foreach (GLTran tran in PXSelectReadonly<GLTran,
Where<GLTran.module, Equal<Required<GLTran.module>>,
And<GLTran.batchNbr, Equal<Required<GLTran.batchNbr>>>>>.Select(graph, batch.Module, batch.BatchNbr))
{
newTran = PXCache<GLTran>.CreateCopy(tran);
newTran.Module = null;
newTran.BatchNbr = null;
newTran.NoteID = null;
newTran.TranDesc = "Test detail";
newTran = graph.GLTranModuleBatNbr.Insert(newTran);
}
if (true)
{
newTran = graph.GLTranModuleBatNbr.Insert();
newTran.AccountID = 1190;
newTran.SubID = 467;
newTran.CuryDebitAmt = 1000;
newTran.TranDesc = "Additional Line 1";
newTran = graph.GLTranModuleBatNbr.Update(newTran);
newTran = graph.GLTranModuleBatNbr.Insert();
newTran.AccountID = 1190;
newTran.SubID = 467;
newTran.CuryCreditAmt = 1000;
newTran.TranDesc = "Additional Line 2";
newTran = graph.GLTranModuleBatNbr.Update(newTran);
}
graph.Save.Press();
}
}
Original Batch :
New Batch :

Creating Customer Location

My requirement is to create a customer location part of downloading order from 3rd party shopping cart.
I have tried this below code and It is not saving any location and also not raising any error.
private static void CreateCustomerLocation(Customer cust, string locationcode, OrderDTO ord, OrderDownloadActivityEntry grp)
{
try
{
LocationMaint graph = CustomerLocationMaint.CreateInstance<CustomerLocationMaint>();
SelectedLocation loc = new SelectedLocation();
loc.BAccountID = cust.BAccountID;
loc.LocationCD = locationcode;
loc.Descr = ord.CustomerLocationName;
loc.IsContactSameAsMain = false;
loc.IsAddressSameAsMain = false;
graph.Location.Insert(loc);
Contact contact = new Contact();
contact.Attention = ord.OrderCustomerContactName;
contact.Phone1 = ord.OrderCustomerContactPhone;
contact.DisplayName = ord.CustomerLocationName;
contact.LastName = ord.OrderCustomerContactName;
contact = graph.Contact.Update(contact);
Address address = new Address();
address.AddressLine1 = ord.OrderShippingLocationAddress1;
address.AddressLine2 = ord.OrderShippingLocationAddress2;
address.City = ord.OrderShippingLocationCity;
address.State = ord.OrderShippingLocationState;
address.PostalCode = ord.OrderShippingLocationZip;
address.CountryID = "US";
contact = graph.Contact.Update(contact);
address = graph.Address.Update(address);
loc.DefAddressID = address.AddressID;
loc.DefContactID = contact.ContactID;
graph.Location.Update(loc);
graph.Save.Press();
}
catch(Exception e)
{
grp.AddLogData(SessionID, "Create Location", "Create Location falied", null, null, e.StackTrace);
}
}
I am not able to figure out where i am making mistake. any suggestion for this issue?
Update
I have tried the following code and I am getting the following error
CARAccountLocationID' cannot be empty.
private static void CreateCustomerLocation(Customer cust, string locationcode, OrderDTO ord, OrderDownloadActivityEntry grp)
{
try
{
LocationMaint graph = PXGraph.CreateInstance<CustomerLocationMaint>();
graph.BusinessAccount.Current = PXSelect<BAccount, Where<BAccount.bAccountID, Equal<Required<BAccount.bAccountID>>>>.Select(graph, cust.BAccountID);
var newLocation = (Location)graph.Location.Cache.CreateInstance();
var locType = LocTypeList.CustomerLoc;
newLocation.LocType = locType;
graph.Location.Insert(newLocation);
var loc = (Location)graph.Location.Cache.CreateCopy(graph.Location.Current);
Contact contact = graph.Contact.Cache.CreateCopy(graph.Contact.Current) as Contact;
contact.Attention = ord.OrderCustomerContactName;
contact.Phone1 = ord.OrderCustomerContactPhone;
contact.DisplayName = ord.CustomerLocationName;
contact.LastName = ord.OrderCustomerContactName;
contact = graph.Contact.Update(contact);
Address address = graph.Address.Cache.CreateCopy(graph.Address.Current) as Address;
address.AddressLine1 = ord.OrderShippingLocationAddress1;
address.AddressLine2 = ord.OrderShippingLocationAddress2;
address.City = ord.OrderShippingLocationCity;
address.State = ord.OrderShippingLocationState;
address.PostalCode = ord.OrderShippingLocationZip;
address.CountryID = "US";
contact = graph.Contact.Update(contact);
address = graph.Address.Update(address);
contact.DefAddressID = address.AddressID;
loc.IsAddressSameAsMain = false;
loc.IsContactSameAsMain = false;
loc.IsAPAccountSameAsMain = true;
loc.IsAPPaymentInfoSameAsMain = true;
loc.IsARAccountSameAsMain = true;
loc.LocationCD = locationcode;
loc.Descr = ord.CustomerLocationName;
loc = graph.Location.Update(loc);
loc.BAccountID = cust.BAccountID;
graph.Location.Cache.RaiseFieldUpdated<Location.isARAccountSameAsMain>(loc, null);
if (loc.CARAccountLocationID == null)
loc.CARAccountLocationID = cust.DefLocationID;
graph.Location.Update(loc);
graph.Save.Press();
}
catch(Exception e)
{
grp.AddLogData(SessionID, "Create Location", "Create Location falied", null, null, e.StackTrace);
}
}
CARAccountLocationID is the LocationID of the MAIN location for a given BAccount/Customer. It is used by the business logic when setting GLAccounts.SameAsDefaultLocationS on screen AR303020.
I've seen the "'CARAccountLocationID' cannot be empty." error when creating a location without first setting the Customer.
The resolution was to first set the customer, then set SameAsDefaultLocationS, then set the rest of the fields.
In the screen API order of operations matters.
In your case you might need to directly set loc.CARAccountLocationID to the LocationID of the customer's MAIN location.

Add Join in BQLCommand

I would like to join the following statement with EPEmployee table on EPEmployee's BAccountID with FSAppointmentEmployee's EmployeeID column then put where condition on EPEmployee's UserID with currently logged in employee's user id in the current BQLCommand for PXAdapter, so that I can see the list of appointments that are assigned to current employee only.
public static PXAdapter PrepareCustomNavAdapter(PXAction action, PXAdapter adapter, bool prevNextAction = false)
{
var select = adapter.View.BqlSelect;
select = select
.WhereAnd<Where<EPEmployee.userID,Equal<AccessInfo.userID>>>()
.OrderByNew<OrderBy<
Desc<FSAppointment.createdDateTime,
Desc<FSAppointment.srvOrdType,
Desc<FSAppointment.refNbr>>>>>();
var newAdapter = new PXAdapter(new PXView(action.Graph, true, select))
{
MaximumRows = adapter.MaximumRows
};
object current = action.Graph.Views[action.Graph.PrimaryView].Cache.Current;
if (prevNextAction)
{
var sortColumns = new string[adapter.SortColumns.Count() + 1];
adapter.SortColumns.CopyTo(sortColumns, 1);
sortColumns[0] = "CreatedDateTime";
newAdapter.SortColumns = sortColumns;
var descendings = new bool[adapter.Descendings.Count() + 1];
adapter.Descendings.CopyTo(descendings, 1);
descendings[0] = true;
newAdapter.Descendings = descendings;
var searches = new object[adapter.Searches.Count() + 1];
adapter.Searches.CopyTo(searches, 1);
if (current != null && current is FSAppointment)
searches[0] = ((FSAppointment)current).CreatedDateTime;
newAdapter.Searches = searches;
}
else if (current != null)
{
adapter.Currents = new object[] { current };
}
return newAdapter;
}
So that, only these two employees would be able to see that appointment.
Thank you.
AccessInfo is a Singleton, you should decorate it with Current class:
Where<EPEmployee.userID, Equal<Current<AccessInfo.userID>>>

Hide a product in Kentico 10

I am performing CRUD operations for products of e-commerce site in kentico 10.I can add and update products using below API
SKUInfoProvider.SetSKUInfo(updateProduct);
Also there is an API for deleting product
SKUInfoProvider.DeleteSKUInfo(updateProduct);
But I do not wish to delete the product from database,rather just disable them so that they do not show up to the end users and still stay in the database .
I tried to set SKUEnabled as false but still user can see the product.So, I used below code to hide the products
ProductNode.SetValue("DocumentPublishTo", DateTime.Now.AddDays(-1));
But my code setup adds a new product with above disabled property.Here is my code
foreach (DataRow dr in dt.Rows)
{
manufacturer = GetManufacturer(Convert.ToString(dr["MANUFACTURER_NAME"]));
department = GetDepartment(Convert.ToString(dr["CATEGORY_OF_PRODUCT_1"]));
var sku = new SKUInfo
{
SKUNumber = Convert.ToString(dr["MANUFACTURER_PART_NUMBER"]),
SKUName = Convert.ToString(dr["MANUFACTURER_PART_NUMBER"]),
SKUDescription = Convert.ToString(dr["TECHNICAL_SPECIFICATIONS"]).Trim('"'),
SKUShortDescription = Convert.ToString(dr["SHORT_DESCRIPTION"]).Trim('"'),
SKUPrice = ValidationHelper.GetDouble(dr["RESELLER_BUY_INC"], 0),
SKURetailPrice = ValidationHelper.GetDouble(dr["RRP_INC"], 0),
SKUEnabled = false,
SKUSiteID = siteId,
SKUProductType = SKUProductTypeEnum.Product,
SKUManufacturerID = manufacturer.ManufacturerID,
SKUDepartmentID = department.DepartmentID,
SKUHeight = ValidationHelper.GetDouble(dr["HEIGHT"], 0),
SKUWidth = ValidationHelper.GetDouble(dr["WIDTH"], 0),
SKUWeight = ValidationHelper.GetDouble(dr["WEIGHT"], 0),
SKUDepth = ValidationHelper.GetDouble(dr["LENGTH"], 0),
SKUAvailableItems = 1,
SKUSellOnlyAvailable = true
};
try
{
SKUInfo updateProduct = SKUInfoProvider.GetSKUs()
.WhereEquals("SKUNumber", sku.SKUNumber)
.FirstObject;
sku.SKUPrice += sku.SKUPrice * 0.015;
if (updateProduct != null)
{
updateProduct.SKUNumber = sku.SKUNumber; updateProduct.SKUName = sku.SKUName;
SKUInfoProvider.SetSKUInfo(updateProduct);
}
else
{
SKUInfoProvider.SetSKUInfo(sku);
}
if (!sku.SKUEnabled)
{
SKUTreeNode productDoc = (SKUTreeNode)SKUTreeNode.New(productDocumentType.ClassName, tree);
if (sku.SKUEnabled == false)
{
productDoc.DocumentPublishTo = DateTime.Now.AddDays(-1);
}
productDoc.DocumentSKUName = Convert.ToString(dr["MANUFACTURER_PART_NUMBER"]);
productDoc.DocumentSKUDescription = sku.SKUDescription;
productDoc.NodeSKUID = sku.SKUID;
productDoc.DocumentCulture = cultureCode;
productDoc.DocumentName = Convert.ToString(dr["MANUFACTURER_PART_NUMBER"]);
}
}
catch (Exception ex)
{
error += "error";
}
}
Please provide the possible solution.There ain't no property such as DocumentPublishTo in SKUInfo,hence I used it with SKUTreeNode which you can find in code setup.
SKUTreeNode productDoc = (SKUTreeNode)SKUTreeNode.New(productDocumentType.ClassName, tree);
if (sku.SKUEnabled == false)
{
productDoc.DocumentPublishTo = DateTime.Now.AddDays(-1);
}
You need to get the node for the SKU, not create a new one. from the documentation :
SKUTreeNode productDoc = (SKUTreeNode)tree.SelectNodes()
.Path("/Products/NewProduct")
.OnCurrentSite()
.CombineWithDefaultCulture()
.FirstObject;
productDoc.DocumentPublishTo = DateTime.Now.AddDays(-1)

How do I create a KPI list programmatically in SharePoint?

I want to be able to create a KPI List on my MOSS 2007 installation via the object model. Is this possible?
using (SPWeb web1 = properties.Feature.Parent as SPWeb)
{
using (SPSite objSite = new SPSite(web1.Site.ID))
{
using (SPWeb web = objSite.OpenWeb(web1.ID))
{
SPListTemplate template = null;
foreach (SPListTemplate t in web.ListTemplates)
{
if (t.Type.ToString() == "432")
{
template = t;
break;
}
}
Guid gG = Guid.Empty;
SPList list = null;
string sListTitle = "Status List";
SPSecurity.RunWithElevatedPrivileges(delegate
{
try
{
web.AllowUnsafeUpdates = true;
gG = web.Lists.Add(sListTitle, sListTitle, template);
list = web.Lists[gG];
}
catch
{
// exists
list = web.Lists[sListTitle];
}
SPContentType ct =
list.ContentTypes["SharePoint List based Status Indicator"];
//declare each item which u want to insert in the kpi list
SPListItem item1 = list.Items.Add();
SPFieldUrlValue value1 = new SPFieldUrlValue();
item1["ContentTypeId"] = ct.Id;
item1.SystemUpdate();
item1["Title"] = "Project Specific Doc.Lib.Rating";
value1.Url = web.Url + "/Lists/Project Specific Documents";
item1["DataSource"] = value1;
item1["Indicator Goal Threshold"] = "3";
item1["Indicator Warning Threshold"] = "3";
item1["Value Expression"] =
"Average;Average_x0020_Rating:Number";
item1.SystemUpdate();
}
}
}
average is the calculation value and the column is Average_x0020_Rating.
http://alonsorobles.com/2010/03/17/important-custom-sharepoint-list-template-notes/
I found that the Template ID for a Status Indicator (KPI List) is 432. Google for this to find some info on creating a new list. I'm needing to read up what properties I can set on this list.
this is work for me:
private void CreateKPIDocumentLibrary(List<PageStructure> list)
{
SPListTemplate kpi = null;
foreach (SPListTemplate t in web.ListTemplates)
{
if (t.Type.ToString() == "432")
{
kpi = t;
break;
}
}
foreach (PageStructure st in list)
{
bool find = false;
string[] periodType = st.tag.Split('_');
string name = periodType[0] + "-" + st.effdate + "-" + st.template;
SPListCollection lstCol = site.OpenWeb().GetListsOfType(SPBaseType.GenericList);
foreach (SPList l in lstCol)
{
string title = l.Title;
if (title == name)
{
find = true;
break;
}
}
if (find == false)
{
Guid docLibID = web.Lists.Add(name, "", kpi);
}
SPList itemList = web.Lists[name];
SPListItem item = itemList.Items.Add();
SPFieldUrlValue value = new SPFieldUrlValue();
item["Title"] = st.tag;
value.Url = st.docUrl;
item["DetailLink"] = st.url;
item["DataSource"] = value;
item["Indicator Goal Threshold"] = "2";
item["Indicator Warning Threshold"] = "1";
item["View Name"] = "All Documents";
item.SystemUpdate();
web.Update();
KpiObject kp = new KpiObject(name, SPContext.Current.Site.Url + itemList.DefaultViewUrl);
this.kpiList.Add(kp);
}
}

Resources