Cannot change project owner - csom

I can change project's name , start date etc in my code but my change to project's owner doesn't apply to project server.
here is my code:
ProjectContext projectContext = new ProjectContext("http://servername:12247/PWA/");
var projectContextVar = projectContext.LoadQuery(
projectContext.Projects.Include(
p => p.Id,
p => p.Name,
p => p.StartDate,
p => p.FinishDate,
p => p.IncludeCustomFields,
p => p.IncludeCustomFields.CustomFields,
p => p.Owner.LoginName
));
projectContext.ExecuteQuery();
PublishedProject pubPro = null;
foreach (var p in projectContextVar)
{
if (new Guid("86C21C48-71BE-E811-80C4-00155D011303") == p.Id)
{
pubPro = p;
}
}
DraftProject draft;
draft = pubPro.Draft;
JobState job1 = projectContext.WaitForQueue(draft.CheckIn(true), 20);
draft = pubPro.CheckOut();
projectContext.Load(draft);
projectContext.ExecuteQuery();
var resources = projectContext.EnterpriseResources;
projectContext.Load(resources);
projectContext.ExecuteQuery();
foreach (EnterpriseResource er in resources)
{
if (er.Name.Equals("some name"))
{
var o = er.User;
projectContext.Load(o);
projectContext.ExecuteQuery();
projectContext.Load(draft.Owner);
projectContext.ExecuteQuery();
draft.Owner = o;
Console.WriteLine("changed...");
}
}
draft.Update();
JobState jobState = projectContext.WaitForQueue(draft.Publish(true), 10);
the draft project's owner at last is successfully changed to the user that is expected, but after publishing the draft project, the change doesn't apply to the project. can any body say what is the problem with my code, or god forbid by project-server?!

Your code is very close, but I don't believe it is possible to set a project owner based on an EnterpriseResource user object.
Instead, try using an SharePoint users object.
var newOwner = projectContext.Web.SiteUsers.GetByLoginName("some name");
draft.Owner = newOwner;
newOwner here will be an object of type Microsoft.SharePoint.Client.User, which is what the "Owner" field in the ProjectDraft class is expecting.

Related

SharePoint 2019 CSOM not saving FieldUserValue

I'm facing a strange Issue when I'm inserting or updating an item in SharePoint2019 list which contains a user column the save completes with no errors but the user column always have empty value,
below is my code
context.Load(context.Web, web => web.Lists);
await context.ExecuteQueryAsync();
List RiskList = context.Web.Lists.GetByTitle("Risks");
context.Load(RiskList);
context.Load(RiskList, r => r.Fields);
await context.ExecuteQueryAsync();
ListItem listItem = RiskList.GetItemById(projectRisks.Id);
List<ListItemFormUpdateValue> listItemFormUpdateValue = new List<ListItemFormUpdateValue>();
if (projectRisks.AssignedTo.HasValue)
{
listItem["AssignedTo"] = new FieldUserValue() { LookupId = projectRisks.AssignedTo.Value };
}
if (projectRisks.Owner.HasValue)
{
User OwnerUser = context.Web.SiteUsers.GetById(projectRisks.Owner.Value);
context.Load(OwnerUser);
await context.ExecuteQueryAsync();
listItem["Owner"] = new FieldUserValue() { LookupId = OwnerUser.Id };
}
listItemFormUpdateValue.Add(new ListItemFormUpdateValue() { FieldName = "Category", FieldValue = GetSPSelectedChoiceValue(context, RiskList, "Category", projectRisks.CategoryName).Result });
listItemFormUpdateValue.Add(new ListItemFormUpdateValue() { FieldName = "Status", FieldValue = GetSPSelectedChoiceValue(context, RiskList, "Status", projectRisks.StatusName).Result });
listItem["Contingency_x0020_plan"] = projectRisks.ContingencyPlan;
listItem["Cost"] = projectRisks.Cost;
listItem["Cost_x0020_Exposure"] = string.Empty;
listItem["Description"] = projectRisks.Description;
listItem["DueDate"] = projectRisks.DueDate;
listItem["Exposure"] = projectRisks.Exposure;
listItem["Impact"] = projectRisks.Impact;
listItem["Mitigation_x0020_plan"] = projectRisks.MitigationPlan;
listItem["Probability"] = projectRisks.Probability;
listItem["Title"] = projectRisks.Name;
listItem.ValidateUpdateListItem(listItemFormUpdateValue, false, string.Empty);
listItem.Update();
await context.ExecuteQueryAsync();
as you can see in the AssignTo and in Owner Columns no mater how I try to save the users values the list will take the default value which is null.
I have made sure that there is values in the assigned to and Owner properties and I have tried using the ListItemFormUpdateValue but with no luck.
Thanks in advance

Returning recursive result

I currently have this in a simple MVC Api controller:
var rootFolder = Umbraco.TypedMedia(200);
return rootFolder.Children().Select(s => new MediaItem
{
Name = s.Name,
Children = s.Children.Select(e => new MediaItem
{
Name = e.Name
})
});
It works, but only return level 1 and 2.
I tried using
return rootFolder.Descendants(), which returns all results from all levels - but "flattened out", so I cannot see the structure in the output.
The output is used in a simple app, navigating a tree structure.
Any ideas, as to how I can make it recursive?
Using Descendants, the output is returned like this
[
{
"Name":"dok1"
},
{
"Name":"dok2"
},
{
"Name":"dok21"
}
]
But it should be
[
{
"Name":"dok1"
},
{
"Name":"dok2"
"Children": [
{
"Name":"dok21"
}
]
}
Not sure you really need recursion here -- the solution below (or something similar) should suffice
// Dictionary between level/depth(int) and the files on that level/depth
var fileDictionary = new Dictionary<int, List<MediaItem>>();
var children = rootFolder.Children();
var depth = 1;
while (children.Any())
{
var tempList = new List<MediaItem>();
children.ForEach(child => {
tempList.Add(child);
});
fileDictionary.Add(depth, tempList);
children = children.Children();
depth++;
}
Then, you can do something like:
foreach (var key in fileDictionary.Keys)
{
// Access the key by key.Key (key would be "depth")
// Access the values by fileDictionary[key] (values would be list of MediaItem)
}
Why not just create a recursive function like so?
IEnumerable<MediaItem> ConvertToMediaItems(IEnumerable<IPublishedContent> items)
{
return items?.Select(i => new MediaItem
{
Name = i.Name,
Children = ConvertToMediaItems(i.Children)
}) ?? Enumerable.Empty<MediaItem>();
}
Then the usage would be
var rootFolder = Umbraco.TypedMedia(200);
return ConvertToMediaItems(rootFolder.Children());
You can also make the function a local function if it's only needed in one place.

Datasource order changed while sorting and grouping in server side

We have tried asp sorting and grouping the datasource the order will be changed. But in client side working fine. We have attached code snippet below.
List<accs> acc = new List<accs>();
acc.Add(new accs() { Account = "4320", Content = "Invest" });
acc.Add(new accs() { Account = "4290", Content = "rewrw" });
acc.Add(new accs() { Account = "4290", Content = "test11" });
var list = acc.OrderBy(x => x.Content);
var t = list.GroupBy(p => p.Account, p => p.Content, (key, g) => new { Account = key, Content = g.ToList() });
return View();
serverside output:
0-Account="4320"
1-Account="4290"
ClientSide output:
0-Account="4290"
1-Account="4320"
Please let me know if you have any solution.
Regards,
Gopi G.

TFS API: How to get attachments from shared steps?

This is what I see in the test results in the Test Manager: some attachments (1) are on the test steps (in this case - on a shared step). Some (2) are on a result level. In the report I'm working on, I can extract information about attachments (2), but fail to get information about (1). Any suggestions?
In the debugger I can see, that the steps are iterated, I can see, i.e. "Verify the stuff" string etc, but the step has 0 attachments.
For reference, this is most of the code I am using to extract test case results:
foreach (ITestCaseResult testCaseResult in resutlsToDisplay)
{
project.TestCases.Find(test.Id);
var testRun = testCaseResult.GetTestRun();
var testPlanEntry = project.TestPlans.Find(testRun.TestPlanId);
var artifacts = testCaseResult.QueryAssociatedWorkItemArtifacts();
if (testPlanEntry.Name != testPlan)
continue;
var testResult = new TestResult // CUSTOM CLASS
{
TestConfiguration = testCaseResult.TestConfigurationName,
TestRun = testRun.Id,
DateCreated = testRun.DateCreated,
DateStarted = testRun.DateStarted,
DateCompleted = testRun.DateCompleted,
Result = testCaseResult.Outcome.ToString(),
TestResultComment = testRun.Comment,
RunBy = testCaseResult.RunBy == null ? "" : testCaseResult.RunBy.DisplayName,
Build = testRun.BuildNumber ?? ""
};
foreach (var iteration in testCaseResult.Iterations)
{
var iterationResult = testResult.Clone();
iterationResult.ResultAttachmentHtml = getAttachments(iteration.Attachments, testCase.TestCaseId.ToString(), string.Empty, iteration.IterationId.ToString()); // HERE I GET THE ATTACHMENTS OF TYPE 2
iterationResult.Iteration = iteration.IterationId;
iterationResult.IterationComment = iteration.Comment;
foreach (var step in steps)
{
var stepCopy = step.Clone();
iterationResult.Steps.Add(stepCopy);
var actionResult = iteration.FindActionResult(stepCopy.TestStep);
if (actionResult == null)
continue;
stepCopy.Result.Comment = actionResult.ErrorMessage;
stepCopy.Result.Result = actionResult.Outcome.ToString();
stepCopy.Result.AttachmentHtml = getAttachments(actionResult.Attachments, testCase.TestCaseId.ToString(), step.Number, iteration.IterationId.ToString()); // HERE I DO NOT GET ATTACHMENTS OF TYPE 1 - WHY?
}
config.TestCaseResult.TestResults.Add(iterationResult);
}
} //end foreach testCaseResult in resutlsToDisplay
I think I figured it out eventually.
The ITestCaseResult contains ITestIterationResultCollection Iterations.
The ITestIterationResult contains TestActionResultCollection of ITestActionResult.
ITestActionResult can be either ITestStepResult or ISharedStepResult.
If it is ITestStepResult, then it has Attachments collection right there.
If it is ISharedStepResult, however, then it has its own TestActionResultCollection. So this is the one that I have to iterate to find if each member has Attachments.
The code to iterate over steps, including shared steps, looks like this:
foreach (ITestIterationResult iteration in testCaseResult.Iterations)
{
var iterationResult = testResult.Clone();
iterationResult.ResultAttachmentHtml = getAttachments(iteration.Attachments,
testCase.TestCaseId.ToString(),
string.Empty, iteration.IterationId.ToString());
iterationResult.Iteration = iteration.IterationId;
iterationResult.IterationComment = iteration.Comment;
foreach (ITestActionResult action in iteration.Actions)
{
if (action is ITestStepResult)
{
GetStepResults(steps, action, iterationResult, iteration, getAttachments, testCase, false);
}
else if (action is ISharedStepResult)
{
ISharedStepResult result = action as ISharedStepResult;
foreach (var sharedAction in result.Actions)
{
if (sharedAction is ITestStepResult)
{
GetStepResults(steps, sharedAction, iterationResult, iteration, getAttachments, testCase, true);
}
}
}
}

How do I get an in-memory chart (or image) into an in-memory OpenXML document?

I'm having a nightmare of a time trying to add a Chart to a MemoryStream in-memory.
I'm creating a Word document on the fly using OpenXML and I have a chart that is also being dynamically generated from data in the database.
I get the template from the database as a byte array, passing that into a method that also takes a business object that holds a bunch of data to populate bookmarks held within that template.
Here's the method:
public Stream Parse(byte[] array, AudiometryReport AudReport)
{
using (MemoryStream Stream = new MemoryStream())
{
Stream.Write(array, 0, (int)array.Length);
Stream.Position = 0;
using (document = WordprocessingDocument.Open(Stream, true))
{
XDocument doc = document.MainDocumentPart.GetXDocument();
List<XElement> bookmarks = doc.Descendants()
.Where(n => n.NodeType == XmlNodeType.Element && n.Name.LocalName == "bookmarkStart")
.ToList();
PropertyInfo[] reportInfo = AudReport.GetType().GetProperties();
foreach (XElement bm in bookmarks)
{
try
{
if (bm.LastAttribute.Value == "AudiometryChart")
{
string partId = InsertImage(document.MainDocumentPart);
var element = AddImageToDocument(document.MainDocumentPart, partId);
//var element = InsertImageXElement(partId);
//bm.ReplaceWith(new XElement(w + "r", element));
}
else
{
string val = reportInfo.Single(x => x.Name == bm.LastAttribute.Value).GetValue(AudReport, null).ToString();
bm.ReplaceWith(new XElement(w + "r",
new XElement(w + "t", val)));
}
}
catch
{ }
}
document.MainDocumentPart.PutXDocument();
//foreach (BookmarkStart bm in (IEnumerable<BookmarkStart>)document.MainDocumentPart.Document.Descendants<BookmarkStart>())
//{
// if (bm.Name == "AudiometryChart")
// {
// // Insert the chart object here.
// //AddImage(document);
// }
// populateStaffDetails(AudReport.Report.Employee, bm);
// populateAudiometryDetails(AudReport, bm);
//}
}
MemoryStream s = new MemoryStream();
Stream.WriteTo(s);
s.Position = 0;
return s;
}
}
The InsertImage image takes the MainDocumentPart and attaches a new ImagePart from the image I stream from the database. I pass the ID of that part back to the calling method.
private string InsertImage(MainDocumentPart docPart)
{
//DrawingsPart dp = docPart.AddNewPart<DrawingsPart>();
//ImagePart part = dp.AddImagePart(ImagePartType.Png, docPart.GetIdOfPart(dp));
ImagePart part = docPart.AddImagePart(ImagePartType.Png);
Chart cht = new ChartBuilder().DoChart(Data, new string[] { "Left", "Right", "Normal" });
using (MemoryStream ms = new MemoryStream())
{
cht.SaveImage(ms, ChartImageFormat.Png);
ms.Position = 0;
part.FeedData(ms);
}
//int count = dp.ImageParts.Count<ImagePart>();
int count = docPart.ImageParts.Count<ImagePart>();
return docPart.GetIdOfPart(part);
}
The last part is some serious nastiness that is allegdly required to add one image to one word document, but what the hell - here it is anyway:
private Run AddImageToDocument(MainDocumentPart docPart, string ImageRelId)
{
string ImageFileName = "Audiometry Chart Example";
string GraphicDataUri = "http://schemas.openxmlformats.org/drawingml/2006/picture";
long imageLength = 990000L;
long imageHeight = 792000L;
var run = new Run(
new Drawing(
new wp.Inline(
new wp.Extent() { Cx = imageLength, Cy = imageHeight },
new wp.EffectExtent()
{
LeftEdge = 19050L,
TopEdge = 0L,
RightEdge = 9525L,
BottomEdge = 0L
},
new wp.DocProperties()
{
Id = (UInt32Value)1U,
Name = "Inline Text Wrapping Picture",
Description = ImageFileName
},
new wp.NonVisualGraphicFrameDrawingProperties(
new a.GraphicFrameLocks() { NoChangeAspect = true }),
new a.Graphic(
new a.GraphicData(
new pic.Picture(
new pic.NonVisualPictureProperties(
new pic.NonVisualDrawingProperties() { Id = (UInt32Value)0U, Name = ImageFileName },
new pic.NonVisualPictureDrawingProperties()),
new pic.BlipFill(
new a.Blip() { Embed = ImageRelId },
new a.Stretch(
new a.FillRectangle())),
new pic.ShapeProperties(
new a.Transform2D(
new a.Offset() { X = 0L, Y = 0L },
new a.Extents() { Cx = imageLength, Cy = imageHeight }),
new a.PresetGeometry(
new a.AdjustValueList()) { Preset = a.ShapeTypeValues.Rectangle }))
) { Uri = GraphicDataUri }))
{
DistanceFromTop = (UInt32Value)0U,
DistanceFromBottom = (UInt32Value)0U,
DistanceFromLeft = (UInt32Value)0U,
DistanceFromRight = (UInt32Value)0U
}
));
return run;
}
So I've solved issues where the memory stream was causing problems by closing prematurely and probably a dozen other unnecessary amateur garden path problems but that image will just not show up in my document. Frustrating. Suggestions or divine inspiration very welcome right now.
(this question has been heavily edited so some answers may not relate to the wording of this question).
I've just tested your AddImageToDocument function in a small test
scenario using the following code:
string partId = ...
Run element = AddImageToDocument(newdoc.MainDocumentPart, partId);
Paragraph p = new Paragraph() { RsidParagraphAddition = "00EA6221", RsidRunAdditionDefault = "008D25CC" };
p.AppendChild(element);
newdoc.MainDocumentPart.Document.Body.Append(p);
// Save the word document here...
Everything works as expected and the image shows up in the word document.
Then I've come to the conclusion that the problem in your code must be the replacement of the bookmarkStart tag and the conversion
of the Run (containing the image) to an XElement.
So, I've modified your code in the following way (using XElement.Parse to convert
an OpenXmlElement to a XElement):
foreach (XElement bm in bookmarks)
{
try
{
if (bm.LastAttribute.Value == "AudiometryChart")
{
string partId = InsertImage(document.MainDocumentPart);
Run element = AddImageToDocument(document.MainDocumentPart, partId);
bm.ReplaceWith(XElement.Parse(element.OuterXml)); // Use XElement.Parse to convert an OpenXmlElement to an XElement.
}
else
{
... }
}
}
catch
{
}
}
The image now shows up in the word document.
Then I've analyzed the word document using the
OpenXml SDK productivity tool and found that the bookmarkEnd tags still exist in the document.
To remove those tags use the following code:
List<XElement> bookmarksEnd = doc.Descendants()
.Where(n => n.NodeType == XmlNodeType.Element && n.Name.LocalName == "bookmarkEnd")
.ToList();
foreach (XElement x in bookmarksEnd)
{
x.Remove();
}
Edit 3: :o)
Ok, I found the problem.
If you initialize the document's MemoryStream with the doc content, the buffer will be fixed in size and not editable. Just changed the init to write the doc content after creation and all seemd to work fine.
//using (MemoryStream stream = new MemoryStream (docxFile))
using (MemoryStream stream = new MemoryStream ())
{
stream.Write (docxFile, 0, docxFile.Length);
stream.Position = 0;
using (WordprocessingDocument docx = WordprocessingDocument.Open (stream, true))
{
[....]
Cheers

Resources