Sharepoint Client Object Model setting ModifiedBy field - c#

I am trying to update the "ModifiedBy" field in a Sharepoint discussion board using the Client Object Model. By changing the "Editor" and "Author" fields, I can change the "ModifiedBy" that appears on the list view. However, once you click on a discussion post, the "ModifiedBy" field that appears there (the one with the picture above it) does not reflect the changes. After experimenting, I discovered that the field I need to change to correct this is called "MyEditor". Unfortunately, this field is read-only.
In the code below, I try to change the read-only settings of the field to false. When I look at the MyEditor field in Visual Studio's debugger after the ExecuteQuery() line at the bottom of the first block, it shows that the ReadOnlyField value has in fact been set to false.
sharepointContext.Load(discussionList);
sharepointContext.ExecuteQuery();
var fields = discussionList.Fields;
sharepointContext.Load(fields);
sharepointContext.ExecuteQuery();
var field = fields.GetByInternalNameOrTitle("MyEditor");
field.ReadOnlyField = false;
field.Update();
sharepointContext.Load(field);
sharepointContext.ExecuteQuery();
The code above executes with no problems. The problem comes with this next block:
//...Code to initialize discussionItem...
discussionItem["MyEditor"] = 0;
discussionItem["Editor"] = 0;
discussionItem["Author"] = 0;
discussionItem["Body"] = "Testing";
discussionItem["Title"] = "Hello Worlds";
discussionItem.Update();
sharepointContext.Load(discussionItem);
sharepointContext.ExecuteQuery();
When the code reaches the ExecuteQuery() at the bottom of the second block, it throws a ServerException with the following message:
Invalid data has been used to update the list item.
The field you are trying to update may be read only.
To make sure that the MyEditor field was the one causing the exception to be thrown, I commented out the line where I set it and ran the code again. Everything worked fine. I don't understand what is wrong, can someone help me?

In case someone needs to find the user by name, it goes like this:
private static FieldUserValue GetUser(ClientContext clientContext, string userName)
{
var userValue = new FieldUserValue();
var newUser = clientContext.Web.EnsureUser(userName);
clientContext.Load(newUser);
clientContext.ExecuteQuery();
userValue.LookupId = newUser.Id;
return userValue;
}
The returned value can be set via item["Author"]

ModifiedBy and CreadtedBy calculated automatically from Author and Editor you need to change only Author and Editor fields like this:
using (var clientContext = new ClientContext(#"http://server"))
{
var web = clientContext.Web;
var lst = web.Lists.GetByTitle("Discus");
var item = lst.GetItemById(2);
item["Author"] = 3;
item["Editor"] = 2;
item.Update();
clientContext.ExecuteQuery();
Console.WriteLine("done");
}

Related

Why do I get the "reference not set to an instance of an object?

I am working with the new CosmosDB SDK v3 https://learn.microsoft.com/en-us/azure/cosmos-db/sql-api-sdk-dotnet-standard and a very simple insert, I have verified all the objects are indeed not null and have reasonable values but I still get the error message:
[1/12/2019 10:35:04] System.Private.CoreLib: Exception while executing function: HAPI_HM_Seasons. Microsoft.Azure.Cosmos.Direct: Object reference not set to an instance of an object.
I dont see why this is I must be missing something really basic here but I cant put my finger on it.
The code is as below:
List<SeasonInformation> seasonInformationList = new List<SeasonInformation>();
foreach(JObject document in listOfSeasons)
{
SeasonInformation seasonInformation = new SeasonInformation
{
id = Guid.NewGuid().ToString(),
Brand = brand,
IntegrationSource = source,
DocumentType = Enums.DocumentType.Season,
UpdatedBy = "HAPI_HM_Seasons",
UpdatedDate = DateTime.Now.ToString(),
UpdatedDateUtc = string.Format("{0:yyyy-MM-ddTHH:mm:ss.FFFZ}", DateTime.UtcNow),
OriginalData = document
};
seasonInformationList.Add(seasonInformation);
}
database = cosmosClient.GetDatabase(cosmosDBName);
container = database.GetContainer(cosmosDBCollectionNameRawData);
log.LogInformation(string.Format("HAPI_HM_Seasons BASIC setup done at {0:yyyy-MM-ddTHH:mm:ss.FFFZ}", DateTime.UtcNow));
log.LogInformation(string.Format("HAPI_HM_Seasons import {1} items BEGIN at {0:yyyy-MM-ddTHH:mm:ss.FFFZ}", DateTime.UtcNow, seasonInformationList.Count));
foreach(var season in seasonInformationList)
{
ItemResponse<SeasonInformation> response = await container.CreateItemAsync(season);
}
I have verified that the List is populated and that the season variable in the loop contains the correct data so I am a bit stuck here.
The exception happens in the last foreach loop where I try CreateItemAsync into CosmosDB
As a best practice, you need to use Async method with await in all the Cosmosdb methods just to make sure that they are getting executed and you get the response,
and modify your CreateItemAsync as follows,
ItemResponse<SeasonInformation> response = await container.CreateItemAsync(season, new PartitionKey(season.whatever));
Here is the Sample Repository

Property read only error when setting the label location for the axes - Infragistics

I am building the xamdatachart axes in the code behind as below:
NumericYAxis yAxis = new NumericYAxis() { IsInverted=true, MajorStrokeThickness= 0 };
NumericYAxis yAxis_right = new NumericYAxis() { IsInverted = false, MajorStrokeThickness = 0 };
To set yAxis's location to OutsideLeft and yAxis_right's location to OutsideRight, I added following part:
yAxis.MinimumValue = 0;
yAxis.Title = "Depth";
yAxis.LabelSettings.Location = AxisLabelsLocation.OutsideLeft;
yAxis_right.MinimumValue = 0;
yAxis_right.Title = "Net Production";
yAxis_right.LabelSettings.Location = AxisLabelsLocation.OutsideRight;
But get error as
"Cannot set a property on object 'Infragistics.Controls.Charts.AxisLabelSettings' because it is in a read-only state."
Any insights on why it happens?
I found this link useful from their website and I did follow the same but I get above error.
The error is being thrown because some property in LabelSettings is read-only aka get-only property. From your code, only Location property is being assigned so i would believe that property doesn't have a public set, causing an error when you try.
I searched for NumericYAxis class and found this:
http://help.infragistics.com/Help/Doc/wpf/2012.1/clr4.0/html/InfragisticsWPF4.Controls.Charts.XamDataChart.v12.1~Infragistics.Controls.Charts.AxisLabelSettings~LocationProperty.html
So Location is both a Dependency property (and this is static read-only) and a also the name of a member property (with get and set). When you type yAxis_right.LabelSettings.Location only one suggestion appears in Visual Studio?
Apparently this is a known issue in Xamdatachart.
here is the Infragistics's response and workaround to it.
This is essentially due to the AxisLabelSettings object being frozen, and so it gets placed in a read-only state. The workaround to this issue is to create a new AxisLabelSettings object and assign it to your axes' LabelSettings property. You can use the following code for this:
AxisLabelSettings settings = new AxisLabelSettings() { Location = AxisLabelsLocation.OutsideRight };
yAxis.LabelSettings = settings;

MaxDrillthroughRecords on IOLEDBConnection resets after changing Connection

I'm working with an IOLEDBConnection object, and changing the MaxDrillthoughRecords field works as expected. However, I also need to change the Connection field of the IOLEDBConnection and when I do this then the MaxDrillthroughRecords field gets set to 1000. I don't want this to happen.
IOLEDBConnection oleConnection = connection.OLEDBConnection;
try
{
this.SetMaxDrillthroughRecords();
var a = oleConnection.MaxDrillthroughRecords; // MaxDrillthroughRecords is 5 here.
oleConnection.Connection = new object[] { connection.ConnectionString };
a = oleConnection.MaxDrillthroughRecords; // MaxDrillthroughRecords is 1000 here.
}
finally { Marshal.ReleaseComObject(oleConnection); }
I tried to use Reflector to view the code in the Microsoft.Office.Interop.Excel assembly but was strangely unable to locate the interface. Is there some subtle behavior I'm missing here? Thanks for any help.

TFS WorkItem Validation error

So here's the case: I am trying to create a Task WorkItem. I have to get the data from a dataGridView, which I think I managed to. But the fun part comes when I try to save, or validate the WorkItem. No matter what value State has, the validator always comes with InvalidListValue on execution of wiTask.Validate();. I have tried even hard-coding the State's value, but nothing happens. There is one thing that bothers me a bit - in the Validation array the error comes within the Status property, where the actual control has only State available. Here are some code and a snippet of the error bit:
WorkItem wiTask = new WorkItem(workItemType)
{
Title = form1.dg_taskView.Rows[rows].Cells["titleDataGridViewTextBoxColumn"].Value.ToString() + " " + form1.tb_details.Text,
Description = form1.dg_taskView.Rows[rows].Cells["descriptionDataGridViewTextBoxColumn"].Value.ToString(),
AreaId = int.Parse(form1.dg_taskView.Rows[rows].Cells["areaIDDataGridViewTextBoxColumn"].Value.ToString()),
AreaPath = form1.dg_taskView.Rows[rows].Cells["areaPathDataGridViewTextBoxColumn"].Value.ToString(),
IterationId = int.Parse(form1.dg_taskView.Rows[rows].Cells["iterationIDDataGridViewTextBoxColumn"].Value.ToString()),
IterationPath = form1.dg_taskView.Rows[rows].Cells["iterationPathDataGridViewTextBoxColumn"].Value.ToString(),
State = form1.dg_taskView.Rows[rows].Cells["stateDataGridViewTextBoxColumn"].Value.ToString()
};
ArrayList result = wiTask.Validate();
wiTask.Save();
var hierarchicalLink = _workItemStore.WorkItemLinkTypes["System.LinkTypes.Hierarchy"];
userStory.WorkItemLinks.Add(new WorkItemLink(hierarchicalLink.ForwardEnd, wiTask.Id));
userStory.Save();
As it turns - the validation returns to the array the column that has issues. After further examination the issue is resolved by specifying to Assigned to name, which is part of the project contributors' list.

How do I programatically change the status of a test in VersionOne?

I am posting this because it might help someone using the VersionOne API SDK Client. I wanted to change the status of a test programmatically, to one of the following categories: Ready, InTesting, Passed, or Failed. I originally tried to change the attribute 'Status.Name' however I would get an error that the attribute is a Read-Only attribute. Another suggestion was to create a new attribute with the same name and that the new attribute would override the previous read-only attribute with the same name. However, it appears that I was looking at it backwards.
internal void TestStatusPassed(string str_TestID)
{
var testId = Oid.FromToken(str_TestID, _context.MetaModel);
var query = new Query(testId);
var testType = _context.MetaModel.GetAssetType("Test");
var sourceAttribute = testType.GetAttributeDefinition("Status.Name");
query.Selection.Add(sourceAttribute);
var result = _context.Services.Retrieve(query);
var test = result.Assets[0];
var oldSource = GetValue(test.GetAttribute(sourceAttribute).Value);
test.SetAttributeValue(sourceAttribute, "Passed");
_context.Services.Save(test);
}
This code will throw an exception "Cannot change a read-only attribute"...
I pulled the XML data for one test from the VersionOne Rest API and noticed a relation named "TestStatus" and then it had a number '9123' assigned to it. So I moved that test manually to 'In Testing' and the "TestStatus" changed to '9121'. Then I moved it to failed and the "TestStatus" changed to '155'. I repeated this with several tests from different testsets and noticed that the numbers for each status were consistent and then changed the code slightly and then I was able to programmatically change the status of each test. I changed "Status.Name" to "Status" and "Passed" to "TestStatus:9123" and now it moves the test into the passed category programmatically.
internal void TestStatusPassed(string str_TestID)
{
var testId = Oid.FromToken(str_TestID, _context.MetaModel);
var query = new Query(testId);
var testType = _context.MetaModel.GetAssetType("Test");
var sourceAttribute = testType.GetAttributeDefinition("Status");
query.Selection.Add(sourceAttribute);
var result = _context.Services.Retrieve(query);
var test = result.Assets[0];
var oldSource = GetValue(test.GetAttribute(sourceAttribute).Value);
test.SetAttributeValue(sourceAttribute, "TestStatus:9123");
_context.Services.Save(test);
}

Categories