Eclipse plugin project preference saving exception - properties

I am currently developing an eclipse plugin, i created my own property page which will be displayed when right-clicking on the context menu of selected project. I tried to save values of that page by pressing OK button on that page, but i got exception saying: "Exception occurred while saving project preferences: /test/.settings/com.example.plugin.prefs.Resource is out of sync with the file system: '/test/.settings/com.example.plugin.prefs'."
Following is what i implemented:
//Get the project
IAdaptable resource = getElement();
if (resource != null) {
IProject project = (IProject) resource.getAdapter(IProject.class);
}
//Define project scope
IScopeContext projectScope = new ProjectScope(project);
//Get node by qualified name
Preferences projectNode = projectScope.getNode(MyPlugin.PLUGIN_ID);
//set the value and save it
if (projectNode != null) {
projectNode.put(PROPERTIES_SERVICENAME, serviceName);
}
try {
projectNode.flush(); // Exception occurs here!!!
} catch (BackingStoreException e) {
e.printStackTrace();
}
To my knowledge, it should automatically save a file like "com.example.plugin.prefs" under runtime-EclipseApplication\test.settings as well, is that correct?
Anybody has idea how to solve this problem?

Related

Google Drive Api Error 403 cannotAddParent with service account

Using a service account, Google Drive API and Google SpreadSheet API, I create a spreadsheet that i then move to a specific folder, using the following code :
public async Task<File> SaveNewSpreadsheet(Spreadsheet spreadsheet, File folder)
{
try
{
Spreadsheet savedSpreadsheet = await _sheetService.Spreadsheets.Create(spreadsheet).ExecuteAsync();
string spreadsheetId = GetSpreadsheetId(savedSpreadsheet);
File spreadsheetFile = await GetFileById(spreadsheetId);
File spreadsheetFileMoved = await MoveFileToFolder(spreadsheetFile, folder);
return spreadsheetFileMoved;
}
catch (Exception e)
{
_logger.LogError(e, $"An error has occured during new spreadsheet save to Google drive API");
throw;
}
}
public async Task<File> MoveFileToFolder(File file, File folder)
{
try
{
var updateRequest = _driveService.Files.Update(new File(), file.Id);
updateRequest.AddParents = folder.Id;
if (file.Parents != null)
{
string previousParents = String.Join(",", file.Parents);
updateRequest.RemoveParents = previousParents;
}
file = await updateRequest.ExecuteAsync();
return file;
}
catch (Exception e)
{
_logger.LogError(e, $"An error has occured during file moving to folder.");
throw;
}
}
This used to work fine for a year or so, but since today, the MoveFileToFolder request throw the following exception:
Google.GoogleApiException: Google.Apis.Requests.RequestError
Increasing the number of parents is not allowed [403]
Errors [
Message[Increasing the number of parents is not allowed] Location[ - ] Reason[cannotAddParent] Domain[global]
]
The weird thing is that if I create a new service account and use it instead of the previous one, it works fine again.
I've looked for info on this "cannotAddParent" error but I couldn't find anything.
Any ideas on why this error is thrown ?
I have the same problem and filed in issue in the Google Issue Tracker. This is intended behavior, unfortunately. You are no longer able to place a file in multiple parents as in your example. See the linked documentation for migration.
Beginning Sept. 30, 2020, you will no longer be able to place a file in multiple parent folders; every file must have exactly one parent folder location. Instead, you can use a combination of status checks and a new shortcut implementation to accomplish file-related operations.
https://developers.google.com/drive/api/v2/multi-parenting

Delete build definitions in TFS via API

When creating TFS build definitions via the API, I need to first delete, if the definition pre-exists:
if (BuildServer.QueryBuildDefinitions(teamProject).Any(d => d.Name == buildDefinitionName))
{
buildDefinition = BuildServer.GetBuildDefinition(teamProject, buildDefinitionName);
var builds = BuildServer.QueryBuilds(buildDefinition);
if (builds != null && builds.Any())
{
Console.WriteLine("delete {0} builds for build definition: {1}", builds.Count(), buildDefinition.Name);
BuildServer.DeleteBuilds(builds);
}
if (buildDefinition.Workspace.Mappings.Any())
{
var mappings = buildDefinition.Workspace.Mappings.Select(m => m.ServerItem).ToArray();
foreach (var mapping in mappings)
{
Console.WriteLine("remove workspace mapping: {0}", mapping);
buildDefinition.Workspace.RemoveMapping(mapping);
}
}
Console.WriteLine("delete build definition: {0}", buildDefinition.Name);
BuildServer.DeleteBuildDefinitions(new[] { buildDefinition });
}
This works as does the subsequent:
buildDefinition = BuildServer.CreateBuildDefinition(teamProject);
buildDefinition.Name = buildDefinitionName;
However, when the first build gets run, it throws an error about conflicting workspaces:
Exception Message: Unable to create the workspace 'some-new-workspace' due to a mapping conflict. You may need to manually delete an old workspace. You can get a list of workspaces on a computer with the command 'tf workspaces /computer:%COMPUTERNAME%'.
Details: The path C:\some-path is already mapped in workspace some-old-workspace. (type MappingConflictException)
As you can see in the first snippet, my attempt to delete workspaces with .Workspace.RemoveMapping(), has no effect. The workspaces still exist on the build controller. I can delete them manually but they really should get deleted when I delete the build definition. Is there some other DeleteWorkspace() mechanism in the API?
A more complete code gist is here: https://gist.github.com/grenade/cce374cb4e27e366bc5b
It turns out that the reason it's complicated is that the owner of the various workspaces created by the build could be some other user (that the build agent runs under).
I found a way to do it by relying on the previous build definition id which is used in the workspace naming convention [build definition id]_[build agent id]_[workspace host]:
var workspaceNamePrefix = string.Concat(buildDefinition.Id, '_');
var workSpaces = VersionControlServer.QueryWorkspaces(null, null, null).Where(w => w.Name.StartsWith(workspaceNamePrefix)).ToArray();
for (var i = workSpaces.Count() - 1; i > -1; i--)
{
try
{
workSpaces[i].Delete();
Console.WriteLine("delete workspace: {0}", workSpaces[i].Name);
}
catch (ResourceAccessException rae)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine(rae.Message);
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("workspace needs to be deleted by an administrator using the following command:");
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("tf workspace /delete {0};{1}", workSpaces[i].Name, workSpaces[i].OwnerName);
Console.ResetColor();
}
}
I have updated the gist: https://gist.github.com/grenade/cce374cb4e27e366bc5b

Custom Error Message for Event Receiver in SharePoint 2010

I want users to upload the .doc files only in the document library.
To do so, I have developed an event receiver in Visual Studio 2010.
My code is as follows:
public override void ItemAdding(SPItemEventProperties properties)
{
try
{
base.ItemAdding(properties);
EventFiringEnabled = false;
if (!properties.AfterUrl.EndsWith("doc"))
{
properties.ErrorMessage = "You are allowed to updload only .doc files";
properties.Status = SPEventReceiverStatus.CancelWithError;
properties.Cancel = true;
}
}
catch (Exception ex)
{
properties.Status = SPEventReceiverStatus.CancelWithError;
properties.ErrorMessage = ex.Message.ToString();
properties.Cancel = true;
}
}
The code is referred from this example.
My problem is that while I am uploading non-doc files it is preventing but with the system error message not the user friendly as defined in properties.ErrorMessage.
How do I solve this?
Please help.
I used the same code you have provided in your question, I get custom error message displayed as shown in below image -
Please provide details of the error you are getting.

Custom icon for ClickOnce application in 'Add or Remove Programs'

A ClickOnce application created using Mage is not showing the icon that was specified in for the Mage command-line parameter in control panel Add or Remove Programs.
I read some blogs, like:
Application icon is not displayed in Add/Remove Programs dialog
Missing Icon in Add/Remove Programs for ClickOnce Application
How can I achieve this without editing registry keys? Is it possible?
There's no way to do this without editing the registry, but you can do it programmatically. You have to be sure the icon is included in the deployment. We set our assembly description to the same string as our Product Name, so we can look through the uninstall strings for the right application by searching for the assembly description. This way, we don't have to hardcode the product name in this code.
private static void SetAddRemoveProgramsIcon()
{
//only run if deployed
if (System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed
&& ApplicationDeployment.CurrentDeployment.IsFirstRun)
{
try
{
Assembly code = Assembly.GetExecutingAssembly();
AssemblyDescriptionAttribute asdescription =
(AssemblyDescriptionAttribute)Attribute.GetCustomAttribute(code, typeof(AssemblyDescriptionAttribute));
string assemblyDescription = asdescription.Description;
//the icon is included in this program
string iconSourcePath = Path.Combine(System.Windows.Forms.Application.StartupPath, "youriconfile.ico");
if (!File.Exists(iconSourcePath))
return;
RegistryKey myUninstallKey = Registry.CurrentUser.OpenSubKey(#"Software\Microsoft\Windows\CurrentVersion\Uninstall");
string[] mySubKeyNames = myUninstallKey.GetSubKeyNames();
for (int i = 0; i < mySubKeyNames.Length; i++)
{
RegistryKey myKey = myUninstallKey.OpenSubKey(mySubKeyNames[i], true);
object myValue = myKey.GetValue("DisplayName");
if (myValue != null && myValue.ToString() == assemblyDescription)
{
myKey.SetValue("DisplayIcon", iconSourcePath);
break;
}
}
}
catch (Exception ex)
{
//log an error
}
}
}

Unable to delete SharePoint 2010 ContentType "Contenty type in use."

I have tried all the recommendations on the web, to no avail.
I wrote a console application per these instructions: http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spcontenttypecollection.delete.aspx
The "Usages.Count" is = 0. Yet, when it tries to delete the Content Type I get an Exception:
"The content type is in use."
This is a brand new (development) install. I created a test site in SP Designer, created a Content Type,then a list. Then, I removed the list, removed it from Recycle Bin and tried to remove the content type...... Ugh.
I was frustrated by this issue until I found your comment. Excellent advice.
Delete from site recycle bin.
Delete from Site Collection > Site Settings > Site Collection Administration > Recycle Bin.
Delete from End User Recycle Bin Items.
Delete from "Deleted From End User Recycle Bin."
That's a lot of recycling! Once complete, I was able to delete the content type.
In addition to the recycling bins there's also the page called "Manage files which have no checked in version" under "Permissions and Management" on document libraries - the files in there can also prevent deletion of a content type.
this powershell script form this post also worked for me
$siteURL = "The Site url"
$contentType = "Content type Name"
$web = Get-SPWeb $siteURL
$ct = $web.ContentTypes[$contentType]
if ($ct) {
$ctusage = [Microsoft.SharePoint.SPContentTypeUsage]::GetUsages($ct)
foreach ($ctuse in $ctusage) {
$list = $web.GetList($ctuse.Url)
$contentTypeCollection = $list.ContentTypes;
$contentTypeCollection.Delete($contentTypeCollection[$contentType].Id);
Write-host "Deleted $contentType content type from $ctuse.Url"
}
$ct.Delete()
Write-host "Deleted $contentType from site."
} else { Write-host "Nothing to delete." }
$web.Dispose()
using System;
using System.Collections.Generic;
using Microsoft.SharePoint;
namespace Test
{
class ConsoleApp
{
static void Main(string[] args)
{
using (SPSite siteCollection = new SPSite("http://localhost"))
{
using (SPWeb webSite = siteCollection.OpenWeb())
{
// Get the obsolete content type.
SPContentType obsolete = webSite.ContentTypes["Test"];
// We have a content type.
if (obsolete != null)
{
IList usages = SPContentTypeUsage.GetUsages(obsolete);
// It is in use.
if (usages.Count > 0)
{
Console.WriteLine("The content type is in use in the following locations:");
foreach (SPContentTypeUsage usage in usages)
Console.WriteLine(usage.Url);
}
// The content type is not in use.
else
{
// Delete it.
Console.WriteLine("Deleting content type {0}...", obsolete.Name);
webSite.ContentTypes.Delete(obsolete.Id);
}
}
// No content type found.
else
{
Console.WriteLine("The content type does not exist in this site collection.");
}
}
}
Console.Write("\nPress ENTER to continue...");
Console.ReadLine();
}
}
}
Create a Console Application with the above code and run that project. This code will tell you the libraries in which the content types are attached. Then simply go that libraries and delete the attached content types. Then finally delete the content type from Site Actions -> Site Settings -> Site Content Types or you may use the above code as well to delete the content type.
This worked for me hope it may also work for you !!!
Thanks.