Update a DynamicContent item of a dynamic module in Sitefinity - sitefinity

I am trying to update a DynamicContent Property of a module using the following:
DynamicModuleManager dynamicModuleManager = DynamicModuleManager.GetManager();
Type pollanswerType = TypeResolutionService.ResolveType("Telerik.Sitefinity.DynamicTypes.Model.Poll.Pollanswer");
Guid pollanswerID = new Guid(answerID);
// This is how we get the pollanswer item by ID
DynamicContent pollanswerItem = dynamicModuleManager.GetDataItem(pollanswerType, pollanswerID);
pollanswerItem.SetValue("VoteCount", int.Parse(pollanswerItem.GetValue("VoteCount").ToString()) + 1);
dynamicModuleManager.SaveChanges();
Basically getting the current Property value and incrementing it by 1
and calling SaveChanges()
the code runs without errors but it doesn't update the value when I check it from the Back End of Sitefinity.
Any suggestions?

The problem might be caused by the pollanswerID that you are passing.
If the pollanswerID is the id of the live version of the content item then the value wouldn't be set.
Make sure you set the field value to the of master version of the content type not the live one.
In case you don't know the id of the master version of the content type you can get the master content item by the id of the live version of the content type
var masterItem = dynamicModuleManager.GetDataItems(pollanswerType).Where(dynItem => dynItem.Id == pollanswerItem.OriginalContentId).FirstOrDefault();
if (masterItem != null)
{
masterItem.SetValue("VoteCount", int.Parse(masterItem.GetValue("VoteCount").ToString()) + 5);
}

you should be always doing this
Get Master
Checkout Master
Checkin Master
Save Changes
Publish changes – this will update live.
bookingItemLive is the live record
var bookingItemMaster = dynamicModuleManager.Lifecycle.Edit(bookingItemLive) as DynamicContent;
//Check out the master to get a temp version.
DynamicContent bookingItemTemp = dynamicModuleManager.Lifecycle.CheckOut(bookingItemMaster) as DynamicContent;
//Make the modifications to the temp version.
bookingItemTemp.SetValue("CleanerId", cleanerId);
bookingItemTemp.SetValue("SubCleanerId", subCleanerId);
bookingItemTemp.LastModified = DateTime.UtcNow;
//Checkin the temp and get the updated master version.
//After the check in the temp version is deleted.
bookingItemMaster = dynamicModuleManager.Lifecycle.CheckIn(bookingItemTemp) as DynamicContent;
dynamicModuleManager.SaveChanges();
//Publish the item now
ILifecycleDataItem publishedBookingItem = dynamicModuleManager.Lifecycle.Publish(bookingItemMaster);
bookingItemMaster.SetWorkflowStatus(dynamicModuleManager.Provider.ApplicationName, "Published");

#Joseph Ghassan: You can follow below step.
Step 1: Get Live
var bookingItemLive= manager.GetDataItem(ModuleType, GuidId);
Step 2: Get Master
var bookingItemMaster = manager.Lifecycle.GetMaster(bookingItemLive) as DynamicContent;
Step 2: Checkout Master --> will be created a draft item( you will update data by draft)
if (bookingItemMaster == null)
{
return new HttpResponseMessage
{
Content = new JsonContent(new { Result = false })
};
}
var bookingItemDraff = manager.Lifecycle.CheckOut(bookingItemMaster) as DynamicContent;
//Make the modifications to the temp version.
bookingItemDraff.SetValue("CleanerId", cleanerId);
bookingItemDraff.SetValue("SubCleanerId", subCleanerId);
bookingItemDraff.LastModified = DateTime.UtcNow;
Step 3: Checkin Master
// Now we need to check in, so the changes apply
var checkInItem = manager.Lifecycle.CheckIn(bookingItemDraff);
Step 4: Publish changes
manager.Lifecycle.Publish(checkInItem);
Step 5: Save Changes - this will save to Database and update live.
bookingItemDraff.SetWorkflowStatus(manager.Provider.ApplicationName, CustomFieldName.PublishedStatus);
manager.SaveChanges();

Related

IntelliJ IDEA LiveTemplate auto increment between usages

I am trying to make my life easier with Live Templates in intelliJ
I need to increment some param by 1 every-time I use the snippet.
So I tried to develop some groovyScript, and I am close, but my groovy capabilities keeps me back. the number is not incremented by 1, but incremented by 57 for some reason... (UTF-8?)
here is the script:
File file = new File("out.txt");
int code = Integer.parseInt(file.getText('UTF-8'));
code=code+1;
try{
if(_1){
code = Integer.parseInt(_1);
}
} catch(Exception e){}
file.text = code.toString();
return code
So whenever there's param passed to this script (with _1) the initial value is set, and otherwise simply incremented.
this script needs to be passed to the live template param with:
groovyScript("File file = new File(\"out.txt\");int code = Integer.parseInt(file.getText(\'UTF-8\'));code=code+1;String propName = \'_1\';if(this.hasProperty(propName) && this.\"$propName\"){code = Integer.parseInt(_1);};file.text =code.toString();return code", "<optional initial value>")

Unable to branch my tests using a variable in Postman

I have a collection with two folders, one for POSTs and one for GETs
At the collection level, I have set variables
And the following collection-level scripts to be run after every request:
requestLast = pm.variables.get("requestLast");
requestCurrent = pm.variables.get("requestCurrent");
statusGet = pm.variables.get("statusGet");
requestLast = requestCurrent;
requestCurrent = pm.request.name;
I want to always be keeping track of the previously run request, so I can return to it when necessary.
In the 'positivePosts' folder I have the following test script:
if(statusGet === 0) {
postman.setNextRequest("resultsPositive");
}
else {
statusGet = 0;
}
pm.variables.set("requestLast", requestLast);
pm.variables.set("requestCurrent", requestCurrent);
pm.variables.set("statusGet", statusGet);
The individual POST requests have no test scripts.
The results folder does not have any tests, but the resultsPositive GET has this test script:
var jsonData = JSON.parse(responseBody);
schema = pm.variables.get("schemaPositive");
tests["Valid Schema"] = tv4.validate(jsonData, schema);
tests["Status code is 200"] = responseCode.code === 200;
statusGet = 1;
postman.setNextRequest(requestLast);
pm.variables.set("requestLast", requestLast);
pm.variables.set("requestCurrent", requestCurrent);
pm.variables.set("statusGet", statusGet);
There are no pre-request scripts anywhere in the collection.
When running the collection, I would expect this order:
postRich
resultsPositive
postAllProperties
resultsPositive
postMinimum
resultsPositive
However, what I actually see is:
postRich
postAllProperties
postPositive
I also don't understand why postPositive is not run after postRich.

EPiServer 9 - Add block to new page programmatically

I have found some suggestions on how to add a block to a page, but can't get it to work the way I want, so perhaps someone can help out.
What I want to do is to have a scheduled job that reads through a file, creating new pages with a certain pagetype and in the new page adding some blocks to a content property. The blocks fields will be updated with data from the file that is read.
I have the following code in the scheduled job, but it fails at
repo.Save((IContent) newBlock, SaveAction.Publish);
giving the error
The page name must contain at least one visible character.
This is my code:
public override string Execute()
{
//Call OnStatusChanged to periodically notify progress of job for manually started jobs
OnStatusChanged(String.Format("Starting execution of {0}", this.GetType()));
//Create Person page
PageReference parent = PageReference.StartPage;
//IContentRepository contentRepository = EPiServer.ServiceLocation.ServiceLocator.Current.GetInstance<IContentRepository>();
//IContentTypeRepository contentTypeRepository = EPiServer.ServiceLocation.ServiceLocator.Current.GetInstance<IContentTypeRepository>();
//var repository = EPiServer.ServiceLocation.ServiceLocator.Current.GetInstance<IContentRepository>();
//var slaegtPage = repository.GetDefault<SlaegtPage>(ContentReference.StartPage);
IContentRepository contentRepository = EPiServer.ServiceLocation.ServiceLocator.Current.GetInstance<IContentRepository>();
IContentTypeRepository contentTypeRepository = EPiServer.ServiceLocation.ServiceLocator.Current.GetInstance<IContentTypeRepository>();
SlaegtPage slaegtPage = contentRepository.GetDefault<SlaegtPage>(parent, contentTypeRepository.Load("SlaegtPage").ID);
if (slaegtPage.MainContentArea == null) {
slaegtPage.MainContentArea = new ContentArea();
}
slaegtPage.PageName = "001 Kim";
//Create block
var repo = ServiceLocator.Current.GetInstance<IContentRepository>();
var newBlock = repo.GetDefault<SlaegtPersonBlock1>(ContentReference.GlobalBlockFolder);
newBlock.PersonId = "001";
newBlock.PersonName = "Kim";
newBlock.PersonBirthdate = "01 jan 1901";
repo.Save((IContent) newBlock, SaveAction.Publish);
//Add block
slaegtPage.MainContentArea.Items.Add(new ContentAreaItem
{
ContentLink = ((IContent) newBlock).ContentLink
});
slaegtPage.URLSegment = UrlSegment.CreateUrlSegment(slaegtPage);
contentRepository.Save(slaegtPage, EPiServer.DataAccess.SaveAction.Publish);
_stopSignaled = true;
//For long running jobs periodically check if stop is signaled and if so stop execution
if (_stopSignaled) {
return "Stop of job was called";
}
return "Change to message that describes outcome of execution";
}
You can set the Name by
((IContent) newBlock).Name = "MyName";

Switch / Checkout Branch ist not working

I'm using Version 0.19
I've a remote branch named 'dev'
after cloning i want to switch to this branch.
i found some code which performs an update to the branch. but for me it doesn't work.
I also try to run a checkout after this which also doesnt work.
When viewing the git log after the code i see the changesets of the master branch. But the local branch name is the name of the given name for the created branch (e.G. "dev")
what am i doing wrong?
private static Branch SwitchBranch(Repository repo, RepositoryProperties properties)
{
string branchname = properties.Branch;
Branch result = null;
if (!string.IsNullOrWhiteSpace(properties.Branch))
{
Branch remote = null;
foreach (var branch in repo.Branches)
{
if (string.Equals(branch.Name, "origin/" + branchname))
{
remote = branch;
break;
}
}
string localBranchName = properties.Branch;
Branch localbranch = repo.CreateBranch(localBranchName);
Branch updatedBranch = repo.Branches.Update(localbranch,
b =>
{
b.TrackedBranch = remote.CanonicalName;
});
repo.Checkout(updatedBranch);
result = updatedBranch;
}
return result;
}
The xml documentation of the CreateBranch() overload you're using states "Creates a branch with the specified name. This branch will point at the commit pointed at by Repository.Head".
From your question, it looks like you'd like this branch to also point to the same Commit than the remote tracking one.
As such, I'd suggest you to change your code as follows:
Branch localbranch = repo.CreateBranch(localBranchName, remote.Tip);
Be aware that you can only create the local branch once. So you're going to get an error the second time. At least, I did.
Branch localbranch = repo.Branches.FirstOrDefault(x => !x.IsRemote && x.FriendlyName.Equals(localBranchName));
if (localbranch == null)
{
localbranch = repo.CreateBranch(localBranchName, remote.Tip);
}
Branch updatedBranch = repo.Branches.Update(localbranch,
b =>
{
b.TrackedBranch = remote.CanonicalName;
});
repo.Checkout(updatedBranch);

API to update users image - Identity Extended Properties not saving

I'm trying to write a small script to set all users images to their AD image, I did some jumping around in ILSpy and found out what to set using the TFS Server API, however the code needs to be a bit different because I'm using the client API instead.
The code I have below can succesfully iterate through all the users in tfs, look them up in AD, grab the thumbnail, set the property on the TFS identity. But I can't for the life of me figure get the extended property to save back into TFS.
The code doesn't exception, but the property isn't set to the value I set it to when I next run the application.
Does anyone know the way to save extended properties via the client api?
Microsoft.TeamFoundation.Client.TeamFoundationServer teamFoundationServer = new Microsoft.TeamFoundation.Client.TeamFoundationServer("{URL TO TFS}");
FilteredIdentityService service = teamFoundationServer.GetService<FilteredIdentityService>(); ;
IIdentityManagementService2 service2 = teamFoundationServer.GetService<IIdentityManagementService2>();
foreach (var identity in service.SearchForUsers(""))
{
var user = UserPrincipal.FindByIdentity(new PrincipalContext(ContextType.Domain), identity.UniqueName);
if (user == null) continue;
var de = new System.DirectoryServices.DirectoryEntry("LDAP://" + user.DistinguishedName);
var thumbNail = de.Properties["thumbnailPhoto"].Value as byte[];
identity.SetProperty("Microsoft.TeamFoundation.Identity.CandidateImage.Data", thumbNail);
identity.SetProperty("Microsoft.TeamFoundation.Identity.CandidateImage.UploadDate", DateTime.UtcNow);
service2.UpdateExtendedProperties(identity);
}
Figured it out, needed to set some additional properties.
Microsoft.TeamFoundation.Client.TeamFoundationServer teamFoundationServer = new Microsoft.TeamFoundation.Client.TeamFoundationServer("http://urltotfs");
FilteredIdentityService service = teamFoundationServer.GetService<FilteredIdentityService>(); ;
IIdentityManagementService2 service2 = teamFoundationServer.GetService<IIdentityManagementService2>();
foreach (var identity in service.SearchForUsers(""))
{
var user = UserPrincipal.FindByIdentity(new PrincipalContext(ContextType.Domain), identity.UniqueName);
if (user == null) continue;
var de = new System.DirectoryServices.DirectoryEntry("LDAP://" + user.DistinguishedName);
var thumbNail = de.Properties["thumbnailPhoto"].Value as byte[];
identity.SetProperty("Microsoft.TeamFoundation.Identity.Image.Data", thumbNail);
identity.SetProperty("Microsoft.TeamFoundation.Identity.Image.Type", "image/png");
identity.SetProperty("Microsoft.TeamFoundation.Identity.Image.Id", Guid.NewGuid().ToByteArray());
identity.SetProperty("Microsoft.TeamFoundation.Identity.CandidateImage.Data", null);
identity.SetProperty("Microsoft.TeamFoundation.Identity.CandidateImage.UploadDate", null);
service2.UpdateExtendedProperties(identity);
}