I’m fairly new to Project Server development and was wondering what modifications need to be made the following code I have to have it update multiple Custom Fields in one pass. I have everything working up until the point I want to start updating multiple Custom Fields. I’ve gone through numerous tutorials and haven’t found a solution that works for this issue. The current program I’ve put together only results in updating the first ForEach cfValueWOD Custom Field. I can get the code to update multiple fields if they already have a value but for my project these custom fields can either have an initial value or no value to start. In both cases I will need to write values to these fields. I need to complete this for a project at work very soon and I’m at a loss. Your help will be much appreciated. My current code is as follows:
{
static void WriteCustomFields()
{
//Guids for custom fields to update - Test
string cfNameWOD = "WO Description"; //Test WO Description custom field
string cfValueWOD = "xxxx5WODes";
Guid cfIdWOD = new Guid("{8071365c-1375-46a1-9424-cd79f3c2b0db}");
string cfNameWG = "Work Group"; //Test Work Group custom field
string cfValueWG = "xxxx5Group";
Guid cfIdWG = new Guid("{f75c6cfb-b7cb-4d35-8b04-60efb12fcd39}");
//projects into a dataset
ProjectDataSet projectList = projectSvc.ReadProjectList();
//read project data
Guid myProjectUid = new Guid("{c96bd7ea-e9d2-47ed-8819-02e4653e92a7}");
ProjectDataSet myProject = projectSvc.ReadProject(myProjectUid, DataStoreEnum.WorkingStore);
//indicate the custom field has been found
bool customFieldFound = false;
//iterate over fields and update them to the table for WO Status
foreach (ProjectDataSet.ProjectCustomFieldsRow cfRow in myProject.ProjectCustomFields)
{
//if field exists update it
if (cfRow.MD_PROP_UID == cfIdWOD)
{
//update the value
cfRow.TEXT_VALUE = cfValueWOD;
customFieldFound = true;
}
}
//check if the custom field has been found
if (!customFieldFound)
{
//create a new row
ProjectDataSet.ProjectCustomFieldsRow cfRowWOD =
myProject.ProjectCustomFields.NewProjectCustomFieldsRow();
//Sets all values to NUll to begin
cfRowWOD.SetDATE_VALUENull();
cfRowWOD.SetTEXT_VALUENull();
//General parameters
cfRowWOD.MD_PROP_UID = cfIdWOD; //custom field ID
cfRowWOD.CUSTOM_FIELD_UID = Guid.NewGuid();
cfRowWOD.PROJ_UID = myProjectUid; //current project ID
//add value
cfRowWOD.FIELD_TYPE_ENUM = 21;
cfRowWOD.TEXT_VALUE = Convert.ToString(cfValueWOD); //test value
//add the row to the data set
myProject.ProjectCustomFields.AddProjectCustomFieldsRow(cfRowWOD);
}
//iterate over fields and update them to the table for WO Status
foreach (ProjectDataSet.ProjectCustomFieldsRow cfRow in myProject.ProjectCustomFields)
{
//if field exists update it
if (cfRow.MD_PROP_UID == cfIdWG)
{
//update the value
cfRow.TEXT_VALUE = cfValueWG;
customFieldFound = true;
}
}
//check if the custom field has been found
if (!customFieldFound)
{
//create a new row
ProjectDataSet.ProjectCustomFieldsRow cfRowWG =
myProject.ProjectCustomFields.NewProjectCustomFieldsRow();
//Sets all values to NUll to begin
cfRowWG.SetDATE_VALUENull();
cfRowWG.SetTEXT_VALUENull();
//General parameters
cfRowWG.MD_PROP_UID = cfIdWG; //custom field ID
cfRowWG.CUSTOM_FIELD_UID = Guid.NewGuid();
cfRowWG.PROJ_UID = myProjectUid; //current project ID
//add value
cfRowWG.FIELD_TYPE_ENUM = 21;
cfRowWG.TEXT_VALUE = Convert.ToString(cfValueWG); //test value
//add the row to the data set
myProject.ProjectCustomFields.AddProjectCustomFieldsRow(cfRowWG);
}
//generate sessionId for tracking
Guid sessionId = Guid.NewGuid(); //sessionId for updating process
Guid jobId = Guid.NewGuid(); //ID for each job
//check out project
projectSvc.CheckOutProject(myProjectUid, sessionId,
"update checkout");
//update project database
bool validateOnly = false;
projectSvc.QueueUpdateProject(jobId, sessionId,
myProject, validateOnly);
//wait to finish
WaitForJob(jobId);
//new jobId to check in the project
jobId = Guid.NewGuid();
//check in the updated project
bool force = false;
string sessionDescription = "update custom fields";
projectSvc.QueueCheckInProject(jobId, myProjectUid,
force, sessionId, sessionDescription);
//wait to finish
WaitForJob(jobId);
//new jobId to publish the project
jobId = Guid.NewGuid();
bool fullPublish = true;
projectSvc.QueuePublish(jobId, myProjectUid, fullPublish, null);
//wait to finish
WaitForJob(jobId);
}
As per my understanding, you are updating a project custom field. Updating a custom field is nothing but up updating a project. In order to do that, first you have to check out a project,Update the custom field, and then call the Queue publish method to save and publish it.
But in your code, You are checking out only one project. So you can update the custom fields that belongs to only that project.
Inorder to update multiple custom fields then your code should be more dynamic.
Example :
read project Guid dynamically.
Loop in thru the project Guid's, then
{
Get Custom field Dataset.
Read custom field dataset.
compare custom fields guids, pick the custom field values based on Project Guid and Custom Field Guid.
Set the value and finally update it.
}
Related
I am making a windows application that sync the source data to Active Directory.
This application works like this.
Choose Source Data(Department, User)
Mapping user or department attributes from source data
When Application service is run, it create groups and users in Active Directory
And also it sets the attributes to users and groups.
When I try to set group or user attributes(properties), it throws exception message like this.
in DirectoryEntry.CommitChanges(); block
The directory
service cannot perform the requested operation on the RDN attribute of an object.
I tried to solve it, but it's really hard to me because I`m not good at Active directory...
Code is below, Please share your knowledge.
//ppk: department key column, pk:user key column, row : Source DataTable's row
void CreateADUser(string ppk,string pk,DataRow row)
{
//password
string pass = GetPass(pk,row,LogSections.AD);
//OU
DirectoryEntry addept = adm.FindOU(ppk);
//principal path
string sOU = adm.GetPrincipalPath(addept);
var aduser = adm.CreateNewUser(sOU, pk, pass, pk, null, null, adm.sDomain);
SetAdUserProperties(pk, pass, row);
MoveUser(ppk,pk);
}
void SetAdUserProperties(string pk,string pass,DataRow row)
{
if (row == null) return;
//list of mapped column(AD User attributes)
List<ADMapping> MappingPatterns = GetAdMappings(Words.User,false);
//Columns name of Source Data table's row
var colnames = Tool.GetColNames(row);
//get user proterties
var aduser = adm.GetUser(pk);
//directory entry of users
var de=aduser.GetUnderlyingObject() as DirectoryEntry;
//looping mapped column of user attributes
foreach (var ADMap in MappingPatterns)
{
string val = ADMap.Mapping;
//mapped columns value
val=Util.ReplaceColPattern(val, row);
SetProperty(de, ADMap.CN, val);
}
if (!string.IsNullOrWhiteSpace(pass))
{
var UserPkColumn = AppConfigHelper.GetAppString(Words.SourceUserPKColumn);
UserPkColumn = Util.GetActualColName(UserPkColumn);
aduser.SetPassword(pass);
QueryHelper.Update(QueryHelper.ConnectionString, Words.ShadowUserTable
,new SqlParameter[] { new SqlParameter("#passwd", pass) }
, new SqlParameter("#"+UserPkColumn,pk));
}
aduser.Save();
}
public void SetProperty(DirectoryEntry oDE, string sPropertyName, object sPropertyValue)
{
if (sPropertyValue != null && !string.IsNullOrWhiteSpace(sPropertyValue.ToString()))
{
if (oDE.Properties.Contains(sPropertyName))
{
oDE.Properties[sPropertyName].Value = sPropertyValue;
}
else
{
oDE.Properties[sPropertyName].Add(sPropertyValue);
}
try
{
oDE.CommitChanges(); //exception here.
oDE.Close();
}
catch (Exception)
{
}
}
}
I also asked this question to other forums, and finally got it.
Before DirectoryEntry.CommitChanges(); set UserPropertyCache property to true
and call the RefreshCache method.
It's hard to see what's the cause of the issue here as we're not seeing what attributes you are trying to set.
That said, you can't just add an attribute if it doesn't exist on your AD object so this part of your code definitely has an issue :
if (oDE.Properties.Contains(sPropertyName))
{
oDE.Properties[sPropertyName].Value = sPropertyValue;
}
else
{
//The following line will never work in this context
oDE.Properties[sPropertyName].Add(sPropertyValue);
}
If I had to make an educated guess, I'd say you're either trying to set an attribute that can't be set, or the User you're adding doesn't have all it's mandatory attributes set.
I have a situation where a user can upload a word document which contains placeholders for certain properties (i.e. in MS Word the user has gone to Insert > Quick Parts > Document Properties and chosen a property). The specific properties I want to support are Title, Author, Company and Publish Date.
Title and Author are set as Package Properties, and Company is set as an Extended File Property. These are set with the below code, which works correctly:
private static void SetDocumentProperties(ReportTemplateModel model, WordprocessingDocument wordDocument)
{
//these properties always exist
wordDocument.PackageProperties.Title = model.Title;
wordDocument.PackageProperties.Creator = model.Author;
wordDocument.PackageProperties.Created = DateTime.Now;
wordDocument.PackageProperties.Modified = DateTime.Now;
//these properties can be null
if (wordDocument.ExtendedFilePropertiesPart == null)
{
wordDocument.AddNewPart<ExtendedFilePropertiesPart>();
}
if (wordDocument.ExtendedFilePropertiesPart.Properties == null)
{
wordDocument.ExtendedFilePropertiesPart.Properties = new Properties(new Company(model.SiteName));
}
else
{
wordDocument.ExtendedFilePropertiesPart.Properties.Company = new Company(model.SiteName);
}
}
My problem is that I can't work out how the set the Publish Date property. I have tried adding it as a Custom File Property using the below code (which is adapted from https://www.snip2code.com/Snippet/292005/WDSetCustomProperty), but this does not work. I've read a few things about setting custom properties, but I'm confused how they're meant to work. I'm also unsure if the Publish Date should actually be set as a custom property, or some other type of property.
var customProps = wordDocument.CustomFilePropertiesPart;
if (customProps == null)
{
customProps = wordDocument.AddCustomFilePropertiesPart();
customProps.Properties = new DocumentFormat.OpenXml.CustomProperties.Properties();
}
var properties1 = new DocumentFormat.OpenXml.CustomProperties.Properties();
//I have tried both of these lines, neither worked.
//properties1.AddNamespaceDeclaration("op", "http://schemas.openxmlformats.org/officeDocument/2006/custom-properties");
properties1.AddNamespaceDeclaration("vt", "http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes");
var customDocumentProperty1 = new DocumentFormat.OpenXml.CustomProperties.CustomDocumentProperty()
{
FormatId = "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}",
PropertyId = 2,
Name = "Publish Date"
};
customDocumentProperty1.Append(new DocumentFormat.OpenXml.VariantTypes.VTLPWSTR { Text = DateTime.Today.ToShortDateString() });
properties1.Append(customDocumentProperty1);
part.Properties = properties1;
What type of property should the Publish Date be set as, and what is the right syntax for setting this?
Update: I have found that Publish Date is a CoverPageProperty which can be created using the below snippet, but I still haven't found how to set it correctly within the document.
var coverPageProps = new DocumentFormat.OpenXml.Office.CoverPageProps.CoverPageProperties
{
PublishDate = new PublishDate(DateTime.Today.ToShortDateString())
};
Adding the below code to my SetDocumentProperties method seems to work. I must admit I don't fully understand the below code, so any explanation would still be welcome. Additionally, if anyone has a solution which doesn't include writing XML as a string inside C# I would much prefer to avoid that.
const string publishDatePartId = "publishDatePart";
var publishDateXmlPart = wordDocument.MainDocumentPart.AddNewPart<CustomXmlPart>("application/xml", publishDatePartId);
var writer = new XmlTextWriter(publishDateXmlPart.GetStream(FileMode.Create), System.Text.Encoding.UTF8);
writer.WriteRaw($"<CoverPageProperties xmlns=\"http://schemas.microsoft.com/office/2006/coverPageProps\">" +
$"<PublishDate>{DateTime.Today.ToShortDateString()}</PublishDate>" +
$"</CoverPageProperties>");
writer.Flush();
writer.Close();
var customXmlPropertiesPart = publishDateXmlPart.AddNewPart<CustomXmlPropertiesPart>(publishDatePartId);
customXmlPropertiesPart.DataStoreItem = new DocumentFormat.OpenXml.CustomXmlDataProperties.DataStoreItem()
{
//I don't know what this ID is, but it seems to somehow relate to the Publish Date
ItemId = "{55AF091B-3C7A-41E3-B477-F2FDAA23CFDA}"
};
I have 2 screen, inquiry and data entry.
and i want to copy Record from Screen1 to screen2, see picture below.
scree1 and Screen2
I use the following code:
public PXAction<FuncLocFilter> CreateFuncLoc;
[PXButton]
[PXUIField(DisplayName = "Create Functional Location")]
protected virtual void createFuncLoc()
{
FuncLocFilter row = Filter.Current;
BSMTFuncLoc FnLc = new BSMTFuncLoc();
FunLocEntry graph = PXGraph.CreateInstance<FunLocEntry>();
graph.FunLocations.Current.FuncLocCD = row.FuncLocCD;
graph.FunLocations.Current.StructureID = row.StructureID;
graph.FunLocations.Current.HierLevels = row.HierLevels;
graph.FunLocations.Current.EditMask = row.EditMask;
if (graph.FunLocations.Current != null)
{
throw new PXRedirectRequiredException(graph, true, "Functional Location");
}
}
but i encountered an error like the following:
Error
can someone please help solve this seemingly stupid question?
im sorry my english is bad.. :)
Thanks!
Below is a common pattern to create data records via code/programming in Acumatica
public PXAction<FuncLocFilter> CreateFuncLoc;
[PXButton]
[PXUIField(DisplayName = "Create Functional Location")]
protected virtual void createFuncLoc()
{
FuncLocFilter row = Filter.Current;
// 1. Create an instance of the BLC (graph)
FunLocEntry graph = PXGraph.CreateInstance<FunLocEntry>();
// 2. Create an instance of the BSMTFuncLoc DAC, set key field values (besides the ones whose values are generated by the system),
// and insert the record into the cache
BSMTFuncLoc FnLc = new BSMTFuncLoc();
FnLc.FuncLocCD = row.FuncLocCD;
FnLc = graph.FunLocations.Insert(FnLc);
// 3. Set non-key field values and update the record in the cache
FnLc.StructureID = row.StructureID;
FnLc.HierLevels = row.HierLevels;
FnLc.EditMask = row.EditMask;
FnLc = graph.FunLocations.Update(FnLc);
// 4. Redirect
if (graph.FunLocations.Current != null)
{
throw new PXRedirectRequiredException(graph, true, "Functional Location");
}
Currently, I'm sending some data to Parse.com. All works well, however, I would like to add a row if it's a new user or update the current table if it's an old user.
So what I need to do is check if the current Facebook ID (the key I'm using) shows up anywhere in the fbid column, then update it if case may be.
How can I check if the key exists in the column?
Also, I'm using C#/Unity.
static void sendToParse()
{
ParseObject currentUser = new ParseObject("Game");
currentUser["name"] = fbname;
currentUser["email"] = fbemail;
currentUser["fbid"] = FB.UserId;
Task saveTask = currentUser.SaveAsync();
Debug.LogError("Sent to Parse");
}
Okay, I figured it out.
First, I check which if there is any Facebook ID in the table that matches the current ID, then get the number of matches.
public static void getObjectID()
{
var query = ParseObject.GetQuery("IdealStunts")
.WhereEqualTo("fbid", FB.UserId);
query.FirstAsync().ContinueWith(t =>
{
ParseObject obj = t.Result;
objectID = obj.ObjectId;
Debug.LogError(objectID);
});
}
If there is any key matching the current Facebook ID, don't do anything. If there aren't, just add a new user.
public static void sendToParse()
{
if (count != 0)
{
Debug.LogError("Already exists");
}
else
{
ParseObject currentUser = new ParseObject("IdealStunts");
currentUser["name"] = fbname;
currentUser["email"] = fbemail;
currentUser["fbid"] = FB.UserId;
Task saveTask = currentUser.SaveAsync();
Debug.LogError("New User");
}
}
You will have to do a StartCoroutine for sendToParse, so getObjectID has time to look through the table.
It may be a crappy implementation, but it works.
What you need to do is create a query for the fbid. If the query returns an object, you update it. If not, you create a new.
I'm not proficient with C#, but here is an example in Objective-C:
PFQuery *query = [PFQuery queryWithClassName:#"Yourclass]; // Name of your class in Parse
query.cachePolicy = kPFCachePolicyNetworkOnly;
[query whereKey:#"fbid" equalTo:theFBid]; // Variable containing the fb id
NSArray *users = [query findObjects];
self.currentFacebookUser = [users lastObject]; // Array should contain only 1 object
if (self.currentFacebookUser) { // Might have to test for NULL, but probably not
// Update the object and save it
} else {
// Create a new object
}
We are having an issue with searching a custom record through SuiteTalk. Below is a sample of what we are calling. The issue we are having is in trying to set up the search using the internalId of the record. The issue here lies in in our initial development account the internal id of this custom record is 482 but when we deployed it through the our bundle the record was assigned with the internal Id of 314. It would stand to reason that this internal id is not static in a site per site install so we wondered what property to set up to reference the custom record. When we made the record we assigned its “scriptId’ to be 'customrecord_myCustomRecord' but through suitetalk we do not have a “scriptId”. What is the best way for us to allow for this code to work in all environments and not a specific one? And if so, could you give an example of how it might be used.
Code (C#) that we are attempting to make the call from. We are using the 2013.2 endpoints at this time.
private SearchResult NetSuite_getPackageContentsCustomRecord(string sParentRef)
{
List<object> PackageSearchResults = new List<object>();
CustomRecord custRec = new CustomRecord();
CustomRecordSearch customRecordSearch = new CustomRecordSearch();
SearchMultiSelectCustomField searchFilter1 = new SearchMultiSelectCustomField();
searchFilter1.internalId = "customrecord_myCustomRecord_sublist";
searchFilter1.#operator = SearchMultiSelectFieldOperator.anyOf;
searchFilter1.operatorSpecified = true;
ListOrRecordRef lRecordRef = new ListOrRecordRef();
lRecordRef.internalId = sParentRef;
searchFilter1.searchValue = new ListOrRecordRef[] { lRecordRef };
CustomRecordSearchBasic customRecordBasic = new CustomRecordSearchBasic();
customRecordBasic.recType = new RecordRef();
customRecordBasic.recType.internalId = "314"; // "482"; //THIS LINE IS GIVING US THE TROUBLE
//customRecordBasic.recType.name = "customrecord_myCustomRecord";
customRecordBasic.customFieldList = new SearchCustomField[] { searchFilter1 };
customRecordSearch.basic = customRecordBasic;
// Search for the customer entity
SearchResult results = _service.search(customRecordSearch);
return results;
}
I searched all over for a solution to avoid hardcoding internalId's. Even NetSuite support failed to give me a solution. Finally I stumbled upon a solution in NetSuite's knowledgebase, getCustomizationId.
This returns the internalId, scriptId and name for all customRecord's (or customRecordType's in NetSuite terms! Which is what made it hard to find.)
public string GetCustomizationId(string scriptId)
{
// Perform getCustomizationId on custom record type
CustomizationType ct = new CustomizationType();
ct.getCustomizationTypeSpecified = true;
ct.getCustomizationType = GetCustomizationType.customRecordType;
// Retrieve active custom record type IDs. The includeInactives param is set to false.
GetCustomizationIdResult getCustIdResult = _service.getCustomizationId(ct, false);
foreach (var customizationRef in getCustIdResult.customizationRefList)
{
if (customizationRef.scriptId == scriptId) return customizationRef.internalId;
}
return null;
}
you can make the internalid as an external property so that you can change it according to environment.
The internalId will be changed only when you install first time into an environment. when you deploy it into that environment, the internalid will not change with the future deployments unless you choose Add/Rename option during deployment.