Copying annotations leads to a corrupted attachment - c#

I'm implementing a plugin (POST Quote Create, Synchronous, Sandbox) to make it so that Notes are copied to the new record when a quote is revised.
My plugin boils down to this (snippet):
var serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
var Service = serviceFactory.CreateOrganizationService(context.UserId);
var notesQuery = new QueryExpression("annotation");
notesQuery.ColumnSet = new ColumnSet(true);
notesQuery.Criteria = new FilterExpression
{
FilterOperator = LogicalOperator.And,
Conditions =
{
new ConditionExpression("objecttypecode", ConditionOperator.Equal, "quote"),
new ConditionExpression("objectid", ConditionOperator.Equal, revisedQuoteId)
}
};
var notes = Service.RetrieveMultiple(notesQuery).Entities;
foreach (var n in notes)
{
var newNote = new Entity("annotation");
newNote.Attributes.Add("ownerid", n.GetAttributeValue<EntityReference>("ownerid"));
newNote.Attributes.Add("objectid", new EntityReference("quote", sourceEntity.Id));
newNote.Attributes.Add("objecttypecode", "quote");
newNote.Attributes.Add("subject", n.GetAttributeValue<string>("subject"));
newNote.Attributes.Add("notetext", n.GetAttributeValue<string>("notetext"));
newNote.Attributes.Add("isdocument", n.GetAttributeValue<bool>("isdocument"));
if (n.GetAttributeValue<bool>("isdocument"))
{
newNote.Attributes.Add("filesize", n.GetAttributeValue<int>("filesize"));
newNote.Attributes.Add("documentbody", n.GetAttributeValue<string>("documentbody"));
newNote.Attributes.Add("filename", n.GetAttributeValue<string>("filename"));
newNote.Attributes.Add("mimetype", n.GetAttributeValue<string>("mimetype"));
}
Service.Create(newNote);
}
Basically, I copy everything over, including an eventual attachment. Everything seems fine, the new revision shows fields, detail records and notes properly... everything but the attachment of the notes.
If I have a single note, with an attached test.txt which content is:
Test attachment
The OrganizationData service reads as follows:
<d:FileName>test.txt</d:FileName>
<d:FileSize m:type="Edm.Int32">39</d:FileSize>
<d:DocumentBody>H4sIAAAMaVMA/wtJLS5RSCwpSUzOyE3NK+HlAgCLmj1zEQAAAA==</d:DocumentBody>
Its "clone" has the correct subject and text, and also shows a test.txt attached which content is
‹ iS ÿI-.QH,)ILÎÈMÍ+áå ‹š=s
mimetype and filesize (while checking odata, I noticed that filesize is not actually correct!) appear to be correct (aka: the same as the original note I'm trying to copy), but OData seems to confirm something's off (it's different!):
<d:FileName>test.txt</d:FileName>
<d:FileSize m:type="Edm.Int32">60</d:FileSize
<d:DocumentBody>H4sIAED6aVMA/5Pv5mBg4MkMZvjP7amrF+iho+npc+6E71nth0+ZGLpn2RYLMjAwAABXqCwTJQAAAA==</d:DocumentBody>
The test.txt file was created from a command prompt (COPY CON test.txt, type, CTRL+Z).
I tried to change the file, and created a test.pdf through PDFCreator: AcroRead in turn whines and says the document is corrupted (so it seems like the issue is mimetype-agnostic).
I also tried re-implementing the same code through early binding (via the CRMSVCUTIL-generated classes) but it yields the exact same result (garbage instead of the attachment contents).
I attempted to hand-craft the documentbody like this:
// "VGVzdCBhdHRhY2htZW50" is Base64 for "Test attachment"
newNote.Attributes.Add("documentbody", "VGVzdCBhdHRhY2htZW50");
and the created file is correct.
I can't figure out what's going on: as far as I know, documentbody is supposed to be a Base64-encoded string which (again, as far as I know) shouldn't be any different when copied around. What am I missing ?
For reference, CRM is updated to UR13 but I repro'd it on a UR16 environment.

EDIT: Does NOT work (only for CRM 4)
Try this (not verified):
var notes = Service.RetrieveMultiple(notesQuery).Entities;
foreach (var newNote in notes)
{
newNote.annotationid = null;
newNote.Attributes.Add("objectid", new EntityReference("quote", sourceEntity.Id));
newNote.Attributes.Add("objecttypecode", "quote");
Service.Create(newNote);
}

Just saw this, in an article from MSDN:
Annotation setupAnnotation = new Annotation()
{
Subject = "Example Annotation",
FileName = "ExampleAnnotationAttachment.txt",
DocumentBody = Convert.ToBase64String(
new UnicodeEncoding().GetBytes("Sample Annotation Text")),
MimeType = "text/plain"
};
I see the document body is encoded according to the Unicode encoding. Maybe you should try to retrieve the encoding from the file and convert it to a string accordingly.

Related

S3PutObjectCopy Batch Operations change destination structure of output directories in .NET

I'm using AWS.NET SDK and I'm trying to use S3CopyObjectOperation with CreateJob from batch operations. It works fine, I'm generating manifest on the fly with the following content:
mysourcebucket,folder/subdir/file1.txt
mysourcebucket,folder/subdir/file2.txt
Now I'm creating a job with CreateJob with the following request:
new CreateJobRequest(){
// some values ommited
Operation = new JobOperation(){
S3PutObjectCopy = new S3CopyObjectOperation{
StorageClass = Standard,
TargetResource = dstBucketArn,
TargetKeyPrefix = dstSubdir
}
},
Manifest = new JobManifest(){
Spec = new JobManifestSpec(){Fields={"Bucket","Key"}, Format= JobManifestFormat.S3BatchOperations_CSV_20180820},
Location= new JobManifestLocation(){
ObjectArn = //manifest key,
Etag = // manifest Etag
}
}
}
It is copying the files correctly under dstBucket. Output:
dstSubdir/folder/subdir/file1.txt
dstSubdir/folder/subdir/file2.txt
Is it possible to change target path somehow, so it doesn't include folder? Expected output:
dstSubdir/subdir/file1.txt
dstSubdir/subdir/file2.txt
Edit: Imageine simple scenario where I want to copy these objects and at some point copy them back into the same location. I won't be able to do that if I use TargetPrefix. In above example I'd create
targetbucket,dstSubdir/folder/subdir/file1.txt
targetbucket,dstSubdir/folder/subdir/file2.txt
And output would be in srcbucket:
srcSubdir/dstSubdir/folder/subdir/file1.txt
srcSubdir/dstSubdir/folder/subdir/file2.txt
The only solution that would work is not to use TargetPrefix at all and keep the same structure in src and dst buckets which is quite a big restriction in my case.
Ideally I'd like to pass
my-bucket,{"origKey": "object1key", "newKey": "newObject1Key"}
my-bucket,{"origKey": "object2key", "newKey": "newObject2Key"}
my-bucket,{"origKey": "object3key", "newKey": "newObject3Key"}
as presented in this example https://docs.aws.amazon.com/AmazonS3/latest/userguide/batch-ops-invoke-lambda.html

How to attach files to Mantis Connect mc_issue_add

Im wondering if I can attach files using filename on MantisConnect. I've tried the ff without luck.
var mc = new MantisBt.Service.Client.MantisBt.Api.MantisConnect();
IssueData iIssue = new IssueData() {
//some other properties here...
attachments = new AttachmentData[] {
filename = "path-to-my-attachment",
date_submitted = DateTime.Now
}
};
string issueID = mc.mc_issue_add(MyUserID, MyPassword, iIssue);
The issue was posted in Mantis but the attachment is not added. I'm sure that the "path-to-my-attachment" exists: (FileInfo.Exists == true)
I have also tried:
IssueData iIssue = new IssueData();
//some other properties here
iIssue.attachments =
//tried converting a List<AttachmentData> to array
//tried the usual AttachmentData[] method
//tried adding AttachmentData["length here"]
but the same thing, issue is posted, no attachments added.
Anyone?
The function you're looking for is mc_issue_attachment_add, mc_issue_add and mc_issue_update don't allow adding attachments.
I figured out that somehow, populating the attachments property of IssueData and saving the issue via mc_issue_add or mc_issue_update does not save the attachments. only way is to save the issue first, use the id then use mc_issue_attachment_add.
So NO. you cannot use the attachments property to add bulk attachments. you need to add them one-by-one using mc_issue_attachment_add.

Updating a file in GitHub repository using Octokit

I am trying to develop a windows forms application that can create, update and delete files in a GitHub repository using Octokit.
public Form1()
{
InitializeComponent();
var ghClient = new GitHubClient(new ProductHeaderValue("Octokit-Test"));
ghClient.Credentials = new Credentials("-personal access token here-");
// github variables
var owner = "username";
var repo = "repository name";
var branch = "master";
// create file
//var createChangeSet = ghClient.Repository.Content.CreateFile(owner,repo,"path/file2.txt",new CreateFileRequest("File creation", "Hello World!", branch));
// update file
var updateChangeSet = ghClient.Repository.Content.UpdateFile(owner, repo,"path/file2.txt", new UpdateFileRequest("File update","Hello Universe!", "SHA value should be here", branch));
}
Firstly, I managed to create a file (check the commented out code), which is fully functional. Then I tried to update that file using,
var updateChangeSet = ghClient.Repository.Content.UpdateFile(owner, repo,"path/file2.txt", new UpdateFileRequest("File update","Hello Universe!", "SHA value should be here", branch));
As you can see, in this situation, I have to get the sha value since the requirement for the "UpdateFileRequest" is,
UpdateFileRequest(string message, string content, string sha, string branch)
How can I receive this Sha value for my file from GitHub?
I am following this tutorial but when I try "createChangeSet.Content.Sha"(without commenting out createChangeSet), it draws a red line underneath "Content" and says,
Task<RepositoryChangeSet> does not contain a definition for 'Content' and no extention method 'Content' accepting a first argument of type Task<RepositoryChangeSet> could be found
I looked at GitHub Documentation and it says I should use,
GET /repos/:owner/:repo/contents/:path
to return the contents of a file or directory in a repository so I assume I will be able to obtain the sha value this way.
How can I implement this method to receive the sha value for my file in the repository so I can use that value to update the file?
I had the same problem and to get the sha you will need to get the existing file first and with this file you also get the last commit sha, which can be used to update the file.
Full demo code:
var ghClient = new GitHubClient(new ProductHeaderValue("Octokit-Test"));
ghClient.Credentials = new Credentials("//...//");
// github variables
var owner = "owner";
var repo = "repo";
var branch = "branch";
var targetFile = "_data/test.txt";
try
{
// try to get the file (and with the file the last commit sha)
var existingFile = await ghClient.Repository.Content.GetAllContentsByRef(owner, repo, targetFile, branch);
// update the file
var updateChangeSet = await ghClient.Repository.Content.UpdateFile(owner, repo, targetFile,
new UpdateFileRequest("API File update", "Hello Universe! " + DateTime.UtcNow, existingFile.First().Sha, branch));
}
catch (Octokit.NotFoundException)
{
// if file is not found, create it
var createChangeSet = await ghClient.Repository.Content.CreateFile(owner,repo, targetFile, new CreateFileRequest("API File creation", "Hello Universe! " + DateTime.UtcNow, branch));
}
I'm not sure if there is a better way to do it - if the searched file is not found an exception is thrown.
But it seems to work that way.

Creating an Ektron Smart Form Definition via the API

I've been trying to create a smart form definition from another application. The app successfully creates the smart form, but I'm unable to get the FieldList, DisplayXSLT or Schema fields to populate.
This leaves me with a blank smart form definition (less that ideal).
Here's the code I have to perform the action. Any ideas?
// form is a simple POCO with values copied from an existing SmartForm Definition
var config = new SmartFormConfigurationData();
config.SmartformTitle = form.Name;
config.SmartformDescription = form.Description;
config.XmlSchema = form.Schema;
config.PackageDisplayXslt = form.Xslt;
config.FieldList = form.FieldList;
config.Type = EkEnumeration.XmlConfigType.Content;
var api = new SmartFormConfigurationManager(ApiAccessMode.Admin);
api.RequestInformation.ServicesPath = this.EktronServiceHost;
api.RequestInformation.AuthenticationToken = this.GetAdminAuthToken();
api.Add(config);
Update:
I heard back from Ektron Support on this issue. It's not so much a "bug" per-se... It's more a case of this API class looking very similar to the ContentManager but not behaving like it. I expected that since it looked so similar to ContentManager and many of the other classes, I would be able to call Add() and it would just magically work. It turns out the solution is a little more complicated.
Adding a smartform is a two-step process: first Add(), then Update().
The Add method doesn't set all of the fields and in fact passes in NULL for a few of the parameters on the stored procedure that creates the entry in xml_collection_tbl.
The real fun comes in step 2. Basically, you start with the SmartForm's HTML -- the stuff you see when you're in the "Data Design" view for editing the smart form definition and you click that <> button ("HTML") at the bottom of the editor. You run that through a whole bunch of XSLTs that are burried in the WorkArea folder to construct the missing fields, and then you call update. Here's the code that worked for me:
var sfManager = new SmartFormConfigurationManager();
var data = sfManager.GetItem(12);
if (data == null) return;
var sfcData = new SmartFormConfigurationData();
sfcData.Type = EkEnumeration.XmlConfigType.Content;
sfcData.SmartformTitle = "SmartForm12 copy";
sfcData.SmartformDescription = "SmartForm12 copy";
sfcData.XmlSchema = "";
sfcData.PackageDisplayXslt = data.PackageDisplayXslt;
sfcData.FieldList = data.FieldList;
sfcData = sfManager.Add(sfcData);
Response.Write("SmartForm added with id: " + sfcData.Id);
var design = System.IO.File.ReadAllText(Server.MapPath("~/NewsArticleSmartForm.html"));
var contentApi = new ContentAPI();
var schema = contentApi.TransformXsltPackage(design, Server.MapPath("~/WorkArea/ContentDesigner/DesignToSchema.xslt"), true);
var fieldList = contentApi.TransformXsltPackage(design, Server.MapPath("~/WorkArea/ContentDesigner/DesignToFieldList.xslt"), true);
var viewEntryXslt = contentApi.TransformXsltPackage(design, Server.MapPath("~/WorkArea/ContentDesigner/DesignToEntryXSLT.xslt"), true);
var xsltArgs = new XsltArgumentList();
xsltArgs.AddParam("srcPath", "", "/WorkArea/ContentDesigner/");
var viewXsltSource = string.Concat("<root>", design, "<ektdesignpackage_list>", fieldList, "</ektdesignpackage_list></root>");
var viewXslt = contentApi.XSLTransform(viewXsltSource, Server.MapPath("~/WorkArea/ContentDesigner/DesignToViewXSLT.xslt"), true, false, xsltArgs, false);
var initialDocument = contentApi.TransformXsltPackage(design, Server.MapPath("~/WorkArea/ContentDesigner/PresentationToData.xslt"), true);
var sbPackage = new StringBuilder("<ektdesignpackage_forms><ektdesignpackage_form><ektdesignpackage_designs><ektdesignpackage_design>");
sbPackage.Append(design);
sbPackage.Append("</ektdesignpackage_design></ektdesignpackage_designs><ektdesignpackage_schemas><ektdesignpackage_schema>");
sbPackage.Append(schema);
sbPackage.Append("</ektdesignpackage_schema></ektdesignpackage_schemas><ektdesignpackage_lists><ektdesignpackage_list>");
sbPackage.Append(fieldList);
sbPackage.Append("</ektdesignpackage_list></ektdesignpackage_lists><ektdesignpackage_views><ektdesignpackage_view>");
sbPackage.Append(viewEntryXslt);
sbPackage.Append("</ektdesignpackage_view><ektdesignpackage_view>");
sbPackage.Append(viewXslt);
sbPackage.Append("</ektdesignpackage_view></ektdesignpackage_views><ektdesignpackage_initialDocuments><ektdesignpackage_initialDocument>");
sbPackage.Append(initialDocument);
sbPackage.Append("</ektdesignpackage_initialDocument></ektdesignpackage_initialDocuments></ektdesignpackage_form></ektdesignpackage_forms>");
sfcData.PackageXslt = sbPackage.ToString();
sfcData.FieldList = fieldList;
var baseFilename = "SmartForm" + sfcData.Id;
var schemaFilename = "/" + baseFilename + "Schema.xsd";
var xsltFilename = "/" + baseFilename + "Xslt.xslt";
sfcData.XmlSchema = schemaFilename; // The file will be prefixed with /XmlFiles
var unPackDisplayXslt = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"><xsl:output method=\"xml\" version=\"1.0\" encoding=\"UTF-8\" indent=\"yes\"/><xsl:template match=\"/\"><xsl:choose><xsl:when test=\"ektdesignpackage_forms/ektdesignpackage_form[1]/ektdesignpackage_views/ektdesignpackage_view[2]\"><xsl:copy-of select=\"ektdesignpackage_forms/ektdesignpackage_form[1]/ektdesignpackage_views/ektdesignpackage_view[2]/node()\"/></xsl:when><xsl:otherwise><xsl:copy-of select=\"ektdesignpackage_forms/ektdesignpackage_form[1]/ektdesignpackage_views/ektdesignpackage_view[1]/node()\"/></xsl:otherwise></xsl:choose></xsl:template></xsl:stylesheet>";
var displayXslt = contentApi.TransformXsltPackage(sbPackage.ToString(), unPackDisplayXslt, false);
System.IO.File.WriteAllText(Server.MapPath("~/XmlFiles" + xsltFilename), displayXslt);
sfcData.Xslt1 = xsltFilename; // The file will be prefixed with /XmlFiles
sfcData.DefaultXslt = 1;
sfManager.Update(sfcData);
I extracted the HTML for my existing smart form and saved in the root of my site as NewsArticleSmartForm.html. Here's what my file looked like:
<p>Author: <input type="text" name="Author" id="Author" ektdesignns_caption="Author" ektdesignns_name="Author" title="Author" ektdesignns_indexed="false" ektdesignns_nodetype="element" size="24" class="design_textfield" /></p>
<p> </p>
<p>Article Summary: <textarea name="Summary" id="Summary" ektdesignns_caption="Summary" ektdesignns_name="Summary" title="Summary" ektdesignns_indexed="false" ektdesignns_nodetype="element" cols="40" rows="3" class="design_textfield"></textarea>
</p>
<p> </p>
<p>Article Body:</p>
<p> </p>
<ektdesignns_richarea id="Body" name="Body" ektdesignns_caption="Body" ektdesignns_name="Body" title="Body" ektdesignns_indexed="false" ektdesignns_nodetype="element"> </ektdesignns_richarea>
<p> </p>
Good luck!
Original Answer:
Creating a copy of a SmartForm configuration should be fairly straight-forward. The SmartFormConfigurationData object has a Clone() method on it which makes it really easy to create a copy of an existing SmartForm. I say "should be" because it doesn't work.
I had an answer all typed out ready to post; I tried some code and it appeared to work. The new smartform was listed in the workarea, but when I clicked on that new smartform to view its details, I realized something was wrong.
I tried the following code:
var sfManager = new SmartFormConfigurationManager();
var config = sfManager.GetItem(7);
if (config == null) return;
var newSmartForm = config.Clone();
newSmartForm.SmartformTitle += " copy";
sfManager.Add(newSmartForm);
Here are the details from the original smartform:
And here's what the new smartform looked like -- the one I created with the frameworkAPI:
I did find one API method that successfully created a copy of an existing smartform:
var sfApi = new Ektron.Cms.ContentAPI();
var newId = sfApi.ReplicateXmlConfiguration(7, "copied sf title");
The problem with that method is that the smartform must exist on your system and you can only change the title. So, I went digging into the database to see what was happening. It turns out that after calling this ReplicateXmlConfiguration() method, the two database records are identical (except for the expected LastUpdated type of fields).
After calling the frameworkAPI's Update() method (same holds true when calling Add()), the "updated" record is clearly different.
I think we've got a genuine bug here. This happens both in v8.7 sp2 and v9.0 sp1. I've opened a case with Ektron support, and I'll update my answer as I hear back. They have always been very responsive when I've dealt with them in the past.

How do you use the CopyIntoItems method of the SharePoint Copy web service?

I am attempting to load document files into a document library in SharePoint using the CopyIntoItems method of the SharePoint Copy web service.
The code below executes and returns 0 (success). Also, the CopyResult[] array returns 1 value with a "Success" result. However, I cannot find the document anywhere in the library.
I have two questions:
Can anyone see anything wrong with my code or suggest changes?
Can anyone suggest how I could debug this on the server side. I don't have a tremendous amount of experience with SharePoint. If I can track what is going on through logging or some other method on the server side it may help me figure out what is going on.
Code Sample:
string[] destinationUrls = { Uri.EscapeDataString("https://someaddress.com/Reports/Temp") };
SPCopyWebService.FieldInformation i1 = new SPCopyWebService.FieldInformation { DisplayName = "Name", InternalName = "Name", Type = SPListTransferSpike1.SPCopyWebService.FieldType.Text, Value = "Test1Name" };
SPCopyWebService.FieldInformation i2 = new SPCopyWebService.FieldInformation { DisplayName = "Title", InternalName = "Title", Type = SPListTransferSpike1.SPCopyWebService.FieldType.Text, Value = "Test1Title" };
SPCopyWebService.FieldInformation[] info = { i1, i2 };
SPCopyWebService.CopyResult[] result;
byte[] data = File.ReadAllBytes("C:\\SomePath\\Test1Data.txt");
uint ret = SPCopyNew.CopyIntoItems("", destinationUrls, info, data, out result);
Edit that got things working:
I got my code working by adding "http://null" to the SourceUrl field. Nat's answer below would probably work for that reason. Here is the line I changed to get it working.
// Change
uint ret = SPCopyNew.CopyIntoItems("http://null", destinationUrls, info, data, out result);
I think the issue may be in trying to set the "Name" property using the webservice. I have had some fail doing that.
Given the "Name" is the name of the document, you may have some success with
string targetDocName = "Test1Name.txt";
string destinationUrl = Uri.EscapeDataString("https://someaddress.com/Reports/Temp/" + targetDocName);
string[] destinationUrls = { destinationUrl };
SPCopyWebService.FieldInformation i1 = new SPCopyWebService.FieldInformation { DisplayName = "Title", InternalName = "Title", Type = SPListTransferSpike1.SPCopyWebService.FieldType.Text, Value = "Test1Title" };
SPCopyWebService.FieldInformation[] info = { i1};
SPCopyWebService.CopyResult[] result;
byte[] data = File.ReadAllBytes("C:\\SomePath\\Test1Data.txt");
uint ret = SPCopyNew.CopyIntoItems(destinationUrl, destinationUrls, info, data, out result);
Note: I have used the "target" as the "source" property. Don't quite know why, but it does the trick.
I didn't understand very well what you're tying to do, but if you're trying to upload a file from a local directory into a sharepoint library, i would suggest you create a webclient and use uploadata:
Example (VB.NET):
dim webclient as Webclient
webClient.UploadData("http://srvasddress/library/filenameexample.doc", "PUT", filebytes)
Then you just have to check in the file using the lists web service, something like:
listService.CheckInFile("http://srvasddress/library/filenameexample.doc", "description", "1")
Hope it was of some help.
EDIT: Don't forget to set credentials for the web client, etc.
EDIT 2: Update metada fields using this:
listService.UpdateListItems("Name of the Library, batchquery)
You can find info on building batch query's in here: link
The sourceurl is used in Sharepoint. It is a link back to the "Source Document." When in your document library, hover over the item, to the right appears a down pointing triangle. Clicking on it, brings up a menu. Click on the "View Properties" Option. On this page you will see the following "This item is a copy of http://null ( Go To Source Item | Unlink )"
Because we are using the Copy function Sharepoint is keeping track of the "Source item" as part of the Document Management feature.

Categories

Resources