SharePoint 2013 REST API - Post SocialRestPostCreationData - rest

I’m currently working on a small application to push Post to a SharePoint 2013 SiteFeed using the Social.Feed API.
Basic Posts using the following JSON Object structure are working fine but I’m struggling using a Social-Attachment.
As long I’m referencing to the files located somewhere in the internet everything works. Posts will create listitems in micro-feed list with HTTP-Reference to the Files. The Object I'm using is set up like this
var creationInfo = new
{
restCreationData = new
{
__metadata = new { type = "SP.Social.SocialRestPostCreationData" },
ID = array,
creationData = new
{
__metadata = new { type = "SP.Social.SocialPostCreationData" },
Attachment = new
{
__metadata = new { type = "SP.Social.SocialAttachment" },
AttachmentKind = 0,
ContentUri = "https://www.google.com/images/icons/hpcg/ribbon-black_68.png",
Description = "Look at this",
Name = "Test",
Uri = "https://www.google.com/images/icons/hpcg/ribbon-black_68.png"
},
ContentText = text,
UpdateStatusText = false,
}
}
};
Is there a possibility to use a local file instead? - Removing the google paths and using a local path in ContentUri will end up in a BAD-Request error.
I guess that the files has to be uploaded somehow before.
Thanks for you help.
Iki

After some trying we now ended up with the following solution.
Before we create the SocialPost, we upload the picture into an image gallery where all Feed users have access to.
Then we create the post containing a link to the image
-> This will do the trick.

Related

Using [google-text-to-speech] v1Beta1 version in c#

Does any one know how to use the V1Beta1 version in c#. It will be a great help if some one can point me to some example. Google has not created a Client for this version.
https://cloud.google.com/text-to-speech/docs/reference/rest/v1beta1/text/synthesize#TimepointType
I had the same problem (for Google.Apis.Texttospeech.v1) and could not find an example anywhere. I pieced it together from some Ruby Api docs, so, this works for me.
How to use Google.Apis.Texttospeech.v1 in C#:
var request = new Google.Apis.Texttospeech.v1.Data.SynthesizeSpeechRequest();
request.AudioConfig = new Google.Apis.Texttospeech.v1.Data.AudioConfig()
{
AudioEncoding = "Linear16" // = WAV, or "MP3", "OGG_OPUS"
};
request.Input = new Google.Apis.Texttospeech.v1.Data.SynthesisInput
{
Text = "Sample Speaker Text" // Or use Ssml = "<speak> Your SSML Text.
</speak>"
};
request.Voice = new Google.Apis.Texttospeech.v1.Data.VoiceSelectionParams
{
LanguageCode = "en-EN",
Name = "en-US-Wavenet-C"
};
var service = new Google.Apis.Texttospeech.v1.TexttospeechService(new
Google.Apis.Services.BaseClientService.Initializer
{
ApplicationName = "My Sample App",
ApiKey = "[Your API Key]"
}
);
var response = service.Text.Synthesize(request).Execute();
using (var output = System.IO.File.Create("audioclip.wav"))
{
var bytes = System.Convert.FromBase64String(response.AudioContent);
output.Write(bytes, 0, bytes.Length);
}

How to allow users to upload files with Google Form without login?

Where can I find code and instruction on how to allow users to upload files with Google Form without login?
I searched all over here and couldn't find any information.
https://developers.google.com/apps-script/reference
Thanks in advance.
The user will be uploading the files to your drive. So, google needs to verify the user. If there is no verification, someone can fill your drive in no time.
It is for your safety to know who has uploaded, so, login is must.
There's a workaround, I'm in a hurry to write the code now, but if you're interested let me know and I'll edit later.
Basically, you set up a web app with apps script, then you setup a custom HTML form, you'll have to manually collect the file, convert is to base64 then json, then when you catch it in apps script you reverse the process and save it wherever you want in your drive.
Since the user will be executing the script as you, there's no verification required
/*
These functions basically go through a file array and reads the files first as binary string (in second function), then converts the files to base64 string (func 1) before stringifying the files (after putting their base64 content into an object with other metadata attached; mime, name e.t.c);
You pass this stringified object into the body part of fetch(request,{body:"stringified object goes here"})
see next code block for how to read in apps script and save the files to google drive
N.B. The body data will be available under doPost(e){e.postData.contents}
*/
async function bundleFilesForUpload(){
let filesDataObj = [];
let copy = {fileInfo:{"ogname":"","meme":""},fileData:""};
for(let i = 0 ; i < counters.localVar.counters.filesForUploadArr.length ; i++){
let tempObj = JSON.parse(JSON.stringify(copy));
let file = counters.localVar.counters.filesForUploadArr[i];
tempObj.fileInfo.ogname = file.name;
tempObj.fileInfo.meme = file.type;
tempObj.fileData = await readFile(file).then((file)=>{
file = btoa(file);
return file;
}).then((file)=>{
return file;
})
filesDataObj.push(tempObj);
}
return filesDataObj;
}
async function readFile (file){
const toBinaryString = file => new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsBinaryString(file);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
let parsedFile = null;
parsedFile = await toBinaryString(file);
return parsedFile;
}
/*From doPost downward, we read the file Array convert the base64 to blob and make a file in google drive using the blob and metadata we have, you may also see some sheet code, I'm using sheet as db for this */
//in buit function doPost in Code.gs
doPost(e){
const myDataObj = JSON.parse(e.postData.contents);
mainFileFunc(myDataObj.params[0].dataObj.images);
//the actual object structure might look different from yours, console log around
}
function mainFileFunc(fileArr) {
let myArrObj = [{"madeit":"toFileF"}];
let copy = JSON.parse(JSON.stringify(myArrObj[0]));
//sheet.getRange("A1").setValue(JSON.stringify(fileArr.length));
for(let i=0 ; i < fileArr.length ; i++){
myArrObj.push(copy);
let blob = doFileStuff(fileArr[i].data,fileArr[i].info[0].mime,fileArr[i].id);
myArrObj[i] = uploadFileOne(blob,fileArr[i].id);
myArrObj[i].mime = fileArr[i].info[0].mime;
myArrObj[i].realName = fileArr[i].name;
// sheet.getRange("A"+(i+1)).setValue(myArrObj[i].name);
// sheet.getRange("B"+(i+1)).setValue(myArrObj[i].url);
// sheet.getRange("C"+(i+1)).setValue(myArrObj[i].mime);
// sheet.getRange("D"+(i+1)).setValue(myArrObj[i].size);
}
return myArrObj;
}
function doFileStuff(filedata,filetype,filename){
var data = Utilities.base64Decode(filedata, Utilities.Charset.UTF_8);
var blob = Utilities.newBlob(data,filetype,filename);
return blob;
}
function uploadFileOne(data,filename) {
let myObj = {}
myObj["name"] = "";
myObj["realName"] = "Story_Picture";
myObj["url"] = "";
myObj["mime"] = "";
myObj["size"] = "";
myObj["thumb"] = "nonety";
var folders = DriveApp.getFoldersByName("LadhaWeb");
while (folders.hasNext()) {
var folder = folders.next();
folder.createFile(data);
}
var files = DriveApp.getFilesByName(filename);
while (files.hasNext()) {
var file = files.next();
myObj.name = file.getName();
myObj.url = file.getUrl();
myObj.mime = file.getMimeType();
myObj.size = file.getSize();
}
return myObj;
}
You can view the full frontend code for this project here and the backend here.
Hope this helps someone.

Word found unreadable content in xxx.docx after split a docx using openxml

I have a full.docx which includes two math questions, the docx embeds some pictures and MathType equation (oleobject), I split the doc according to this, get two files (first.docx, second.docx) , first.docx works fine, the second.docx, however, pops up a warning dialog when I try to open it:
"Word found unreadable content in second.docx. Do you want to recover the contents of this document? If you trust the source of this document, click Yes."
After click "Yes", the doc can be opened, the content is also correct, I want to know what is wrong with the second.docx? I have checked it with "Open xml sdk 2.5 productivity tool", but found no reason. Very appreciated for any help. Thanks.
The three files have been uploaded to here.
Show some code:
byte[] templateBytes = System.IO.File.ReadAllBytes(TEMPLATE_YANG_FILE);
using (MemoryStream templateStream = new MemoryStream())
{
templateStream.Write(templateBytes, 0, (int)templateBytes.Length);
string guidStr = Guid.NewGuid().ToString();
using (WordprocessingDocument document = WordprocessingDocument.Open(templateStream, true))
{
document.ChangeDocumentType(DocumentFormat.OpenXml.WordprocessingDocumentType.Document);
MainDocumentPart mainPart = document.MainDocumentPart;
mainPart.Document = new Document();
Body bd = new Body();
foreach (DocumentFormat.OpenXml.Wordprocessing.Paragraph clonedParagrph in lst)
{
bd.AppendChild<DocumentFormat.OpenXml.Wordprocessing.Paragraph>(clonedParagrph);
clonedParagrph.Descendants<Blip>().ToList().ForEach(blip =>
{
var newRelation = document.CopyImage(blip.Embed, this.wordDocument);
blip.Embed = newRelation;
});
clonedParagrph.Descendants<DocumentFormat.OpenXml.Vml.ImageData>().ToList().ForEach(imageData =>
{
var newRelation = document.CopyImage(imageData.RelationshipId, this.wordDocument);
imageData.RelationshipId = newRelation;
});
}
mainPart.Document.Body = bd;
mainPart.Document.Save();
}
string subDocFile = System.IO.Path.Combine(this.outDir, guidStr + ".docx");
this.subWordFileLst.Add(subDocFile);
File.WriteAllBytes(subDocFile, templateStream.ToArray());
}
the lst contains Paragraph cloned from original docx using:
(DocumentFormat.OpenXml.Wordprocessing.Paragraph)p.Clone();
Using productivity tool, found oleobjectx.bin not copied, so I add below code after copy Blip and ImageData:
clonedParagrph.Descendants<OleObject>().ToList().ForEach(ole =>
{
var newRelation = document.CopyOleObject(ole.Id, this.wordDocument);
ole.Id = newRelation;
});
Solved the issue.

Set An Alert on Sharepoint 2013 for multiple list and library

I have some sites with many list and library. I want to know about their changes. set alert for any list and library is very difficult and It takes a long time.
Is there any soloution ?
We can use create alert for all the custom list and document library using C# code or PowerShell script.
The following C# code for your reference.
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite("http://sp2013"))
{
using (SPWeb web = site.OpenWeb())
{
foreach(SPList list in web.Lists)
{
if (list.BaseType == SPBaseType.GenericList || list.BaseType == SPBaseType.DocumentLibrary)
{
SPUser user = web.EnsureUser(#"domain\admin");
SPAlert newAlert = user.Alerts.Add();
newAlert.Title = "My Custom Alert";
newAlert.AlertType = SPAlertType.List;
newAlert.List = list;
newAlert.DeliveryChannels = SPAlertDeliveryChannels.Email;
newAlert.EventType = SPEventType.Add;
newAlert.AlertFrequency = SPAlertFrequency.Immediate;
newAlert.Update();
}
}
}
}
});
Reference:
Programmatically Creating Alerts in SharePoint
Create - Edit - Find - Delete SharePoint Alerts using PowerShell

Openxml: Added ImagePart is not showing in Powerpoint / Missing RelationshipID

I'm trying to dynamically create a PowerPoint presentation. One slide has a bunch of placeholder images that need to be changed based on certain values.
My approach is to create a new ImagePart and link it to the according Blip. The image is downloaded and stored to the presentation just fine. The problem is, that there is no relationship created in slide.xml.rels file for the image, which leads to an warning about missing images and empty boxes on the slide.
Any ideas what I am doing wrong?
Thanks in advance for your help! Best wishes
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite siteCollection = new SPSite(SPContext.Current.Site.RootWeb.Url))
{
using (SPWeb oWeb = siteCollection.OpenWeb())
{
SPList pictureLibrary = oWeb.Lists[pictureLibraryName];
SPFile imgFile = pictureLibrary.RootFolder.Files[imgPath];
byte[] byteArray = imgFile.OpenBinary();
int pos = Convert.ToInt32(name.Replace("QQ", "").Replace("Image", ""));
foreach (DocumentFormat.OpenXml.Presentation.Picture pic in pictureList)
{
var oldimg = pic.BlipFill.Blip.Embed.ToString(); ImagePart ip = (ImagePart)slidePart.AddImagePart(ImagePartType.Png, oldimg+pos);
using (var writer = new BinaryWriter(ip.GetStream()))
{
writer.Write(byteArray);
}
string newId = slidePart.GetIdOfPart(ip);
setDebugMessage("new img id: " + newId);
pic.BlipFill.Blip.Embed = newId;
}
slidePart.Slide.Save();
}
}
});
So, for everyone who's experiencing a similar problem, I finally found the solution. Quite a stupid mistake. Instad of PresentationDocument document = PresentationDocument.Open(mstream, true); you have to use
using (PresentationDocument document = PresentationDocument.Open(mstream, true))
{
do your editing here
}
This answer brought me on the right way.