How to retrieve data entered in content control in webaddin - ms-word

I have a richtext content control named firstname in a Word document. I am trying to access its content but am not able retrieve it.
This is a sample method given in msdn. Using it I am able to get the control's id and its type but not the data. Please let me know whether any way to access the same?
function bindContentControl() {
Office.context.document.bindings.addFromNamedItemAsync(
'FirstName', Office.BindingType.Text, {id:'firstName'},
function (result) {
if (result.status === Office.AsyncResultStatus.Succeeded) {
write('Control bound. Binding.id: ' + result.value.id + ' Binding.type: ' + result.value.type); }
else {
write('Error:', result.error.message);
}
});
}
// Function that writes to a div with id='message' on the page.
Funktion write(message){
document.getElementById('message').innerText += message; }  

The sample code you provided creates a binding to an object with the name 'FirstName'.
You will want to use context.document.contentControls.getByTitle() to retrieve the content control of a given name. Here's my sample code.
await Word.run(async (context) => {
let controls = context.document.contentControls.getByTitle("FirstName");
controls.load();
await context.sync();
//assuming there's only one para.
controls.items[0].paragraphs.load();
await context.sync();
console.log(controls.items[0].paragraphs.items[0].text);
});

Related

display single record by id with vue js and axios

I have a mongodb express vue js app that displays a list of items in cards which are links to a detail view of each record. If I hover over the card the correct id for the link displays but click any card and it goes to the first document from mongo and the record does not display. The view retrieves an item but always the first one.
How to display a record of the ID of item clicked?
Report.vue
the backend request which works in postman is
// Get Simgle Report
router.get('/:id', async (req, res) => {
const reports = await loadReportsCollection()
await reports.findOne({_id: new mongodb.ObjectID( req.params.id)})
res.send(await reports.find({}).limit(1).toArray())
res.status(200).send()
}
)
ReportService.js looks like
//Find Single Report
static getReport(id) {
return axios.get(`${url}${id}`)
}
and the Report.vue file looks like
mounted () {
this.getReport()
},
methods: {
async getReport() {
try {
const response = await ReportService.getReport(this.$route.params.id)
this.report = response.data
} catch(err) {
this.err = err.message
}
},
}
many thanks for help!
It would seem you are trying to access a param in your api without passing one in your request. You ask for params here:
await reports.findOne({_id: new mongodb.ObjectID( req.params.id)})
but haven't passed any in your request. This should do it:
return axios.get('/:id', {
params: {
id: `${id}`
}
})
To not only get the first entry, but the one you are looking for you need to change your send() parameter.
Here is the working code:
// Get Simgle Report
router.get('/:id', async (req, res) => {
const reports = await loadReportsCollection()
const report = await reports.findOne({_id: new mongodb.ObjectID(req.params.id)})
res.send(await report)
res.status(200).send()
}
)
And as Andrew1325 stated you need to change your axios.get() call also to pass the correct params to it.

Pg-promise - How to stream binary data directly to response

Forgive me I'm still learning. I'm trying to download some mp3 files that I have stored in a table. I can download files directly from the file system like this:
if (fs.existsSync(filename)) {
res.setHeader('Content-disposition', 'attachment; filename=' + filename);
res.setHeader('Content-Type', 'application/audio/mpeg3');
var rstream = fs.createReadStream(filename);
rstream.pipe(res);
I have stored the data in the table using pg-promise example in the docs like so:
const rs = fs.createReadStream(filename);
function receiver(_, data) {
function source(index) {
if (index < data.length) {
return data[index];
}
}
function dest(index, data) {
return this.none('INSERT INTO test_bin (utterance) VALUES($1)', data);
}
return this.sequence(source, {dest});
} // end receiver func
rep.tx(t => {
return streamRead.call(t, rs, receiver);
})
.then(data => {
console.log('DATA:', data);
})
.catch(error => {
console.log('ERROR: ', error);
});
But now I want to take that data out of the table and download it to the client. The example in the docs of taking data out of binary converts it to JSON and then prints it to the console like this:
db.stream(qs, s => {
s.pipe(JSONStream.stringify()).pipe(process.stdout)
})
and that works. So the data is coming out of the database ok. But I can't seem to send it to the client. It seems that the data is already a stream so I have tried:
db.stream(qs, s => {
s.pipe(res);
});
But I get a typeerror: First argument must be a string or Buffer
Alternatively, I could take that stream and write it to the file system, and then serve it as in the top step above, but that seems like a workaround. I wish there was an example of how to save to a file in the docs.
What step am I missing?

Protractor- automate the error message on tab out when input field is empty

I have an angular2 application where I am trying to write end to end test cases to automate things.I have just begun with learning Protractor for this and trying to implement a negative test case for a form field where if any field is empty, the error message should be shown. I have tried something like below to automate the form and its working fine.
In my spec.ts-
import userDetailsPage from './userDetails.e2e-po;
it('should fill out User Details', () => {
const userDetail: IUserDetail = {
firstName: 'Lorem',
lastName: 'Ipsum'
};
userDetailsPage.populateUserDetails(userDetail);
});
In userDetails.e2e-po-
populateUserDetails(details: IUserDetail) {
this.fillFirstName(details.firstName)
.fillLastName(details.lastName)
return this;
}
I am writing the below code which automatically inputs the firstName and lastName field.
fillLastName(last: string) {
let el = element(by.css('input[name="lastName'));
el.clear().then(() => {
el.sendKeys(last);
});
return this;
}
The above scenario works fine. But I am also trying to achieve a scenario where I do not input either first name or last name field, should throw me an error message.Can someone let me know what else should I add to achieve this.
I am already handling the validation in my HTML.
Any help is much appreciated.
Instead of details.firstname and details.lastname put empty strings and then validate the error that occurs on the page.
I think you can try the following method as a reusable function
function formValidate(donefn){
newProjBtn.click().then(async function () {
var lastName_fld = element(by.css('input[name="lastName'));
await lastName_fld.sendKeys("", protractor.Key.TAB);
//browser.sleep(2000);
var elm = element(by.css(".error-message"));
elm.isPresent().then(function(result){
if(result){
console.log("Error message displayed")
//some more code to do like selecting the field and enter the test
return result;
}else{
console.log("Error message not displayed")
return result;
}
})
donefn();
})
I solved it in this way:
await input.sendKeys(protractor.Key.CONTROL, 'a');
await input.sendKeys(protractor.Key.BACK_SPACE);
await input.sendKeys(protractor.Key.TAB);
//then the error-message will appear

How to get the entire document text in onDidChangeTextDocument on vscode Language Server implementation?

I want to parse a file allways that the user change it, so I implement the onDidChangeTextDocument method from connection.
But this event just give me the URI and the content changes. How can I get the entiry document?
Obs.: I also tried to implement the onDidChangeContent from documents, but it was never called.
The document is in the event passed in to onDidChangeTextDocument. This is how I handle it:
var changeTimeout;
vscode.workspace.onDidChangeTextDocument(function (event) {
if (changeTimeout != null)
clearTimeout(changeTimeout);
changeTimeout = setInterval(function () {
clearTimeout(changeTimeout);
changeTimeout = null;
backend.reparse(event.document.fileName, event.document.getText());
processDiagnostic(event.document);
}, 500);
});
This is what MS writes in the documentation:
// The content of a text document has changed. This event is emitted
// when the text document first opened or when its content has changed.
documents.onDidChangeContent((change) => {
let diagnostics: Diagnostic[] = [];
let lines = change.document.getText().split(/\r?\n/g);
lines.forEach((line, i) => {
let index = line.indexOf('typescript');
if (index >= 0) {
diagnostics.push({
severity: DiagnosticSeverity.Warning,
range: {
start: { line: i, character: index},
end: { line: i, character: index + 10 }
},
message: `${line.substr(index, 10)} should be spelled TypeScript`,
source: 'ex'
});
}
})
// Send the computed diagnostics to VS Code.
connection.sendDiagnostics({ uri: change.document.uri, diagnostics });
});
so the document (and so the text) should be available in the event.
Obs.: I also tried to implement the onDidChangeContent from documents, but it was never called.
What I wonder is why onDidChangeContent stops being called when using any of those: onDidChangeTextDocument, onDidOpenTextDocument, onDidCloseTextDocument. It seems we can only use one way or the other.
So, what you're looking for is this:
documents.onDidChangeContent(change => {
connection.console.log(change.document.getText())
})
All change.document members: uri,languageId,version,getText,update,getLineOffsets,positionAt,offsetAt,lineCount

Read file from GridFS based on _ID using mongoskin & nodejs

I am using mongoskin in my nodejs based application. I have used GridFS to uplaod the file. I am able to upload and read it back using the "filename" however I want to read it back using _id. How can i do? Following are code details.
Working code to read the file based on filename:
exports.previewFile = function (req, res) {
var contentId = req.params.contentid;
var gs = DBModule.db.gridStore('69316_103528209714703_155822_n.jpg', 'r');
gs.read(function (err, data) {
if (!err) {
res.setHeader('Content-Type', gs.contentType);
res.end(data);
} else {
log.error({err: err}, 'Failed to read the content for id '+contentId);
res.status(constants.HTTP_CODE_INTERNAL_SERVER_ERROR);
res.json({error: err});
}
});
};
How this code can be modified to make it work based on id?
After few hit & trial following code works. This is surprise bcz input parameter seems searching on all the fields.
//view file from database
exports.previewContent = function (req, res) {
var contentId = new DBModule.BSON.ObjectID(req.params.contentid);
console.log('Calling previewFile inside FileUploadService for content id ' + contentId);
var gs = DBModule.db.gridStore(contentId, 'r');
gs.read(function (err, data) {
if (!err) {
//res.setHeader('Content-Type', metadata.contentType);
res.end(data);
} else {
log.error({err: err}, 'Failed to read the content for id ' + contentId);
res.status(constants.HTTP_CODE_INTERNAL_SERVER_ERROR);
res.json({error: err});
}
});
};