Docusign REST API: Downloading document to string - docusignapi

I am building an app using the docusign API and PHP. I have most of this working except I cannot figure out how to download the document. I have been searching on this site and on the Docusign site. Docusign has an example here, that shows how to get a list of docs in PHP, but the downloading does not have a PHP example. In the Docusign REST API docs they explain the method here. But this says the response is "PDF File".
In my sample code below, I have tried to put the contents into a file, but it creates and empty file. If I print_r($data), I get this:
SplFileObject Object
(
[pathName:SplFileInfo:private] => /tmp/419ULk
[fileName:SplFileInfo:private] => 419ULk
[openMode:SplFileObject:private] => w
[delimiter:SplFileObject:private] => ,
[enclosure:SplFileObject:private] => "
)
It does create the file in /tmp, but I want to keep the document in a string so I send or save to DB.
Here is my controller function:
public function get_document($envelopeId, $cert = FALSE)
{
$save_dir = BASEPATH."../documents/";
if ($envelopeId) {
$this->load->model('docusign_model');
$data = $this->docusign_model->get_document($envelopeId, $cert);
}
file_put_contents($save_dir.$envelopeId.".pdf", $data);
//print_r($data);
die("116");
}
This is in docusign_model:
public function get_document($envelopeId, $cert)
{
$docuSignAuth = $this->auth();
if ($docuSignAuth) {
$envelopeApi = new EnvelopesApi($docuSignAuth->apiClient);
$options = new GetDocumentOptions();
if($cert) {
$options->setCertificate(TRUE);
} else {
$options->setCertificate(FALSE);
}
return $envelopeApi->getDocument($docuSignAuth->accountId, 1, $envelopeId, $options);
}
return false;
}
How can I get this document and keep it in a string?
Any and all help is greatly appreciated!

The content comes back as a file, you have to read the temp file and save that to the desired file
Quick snippet using file_get_contents and file_put_contents
$docStream = $envelopeApi->getDocument($accountId, 1, $envelopeId);
file_put_contents("my_document.pdf", file_get_contents($docStream->getPathname()));
More info DocuSign REST API :: EnvelopeDocuments: get under Get a Single Document as a PDF File

Related

Exporting an Excel file with WebAPI, VueJS, EPPlus

I need to export an excel file that is comprised of formulas, formatted, etc. It's not just a table of data. I.e., top portion will be descriptions/calculations, and then the lower half will loop through a list of items. Adding this bc I need more functionality than vue-json-excel or vue-json-export offer (I think)
I know how to do this with webforms/code-behind, but I've been dabbling with VueJS and MVC and am trying to figure out how to get this done with that. I am using EPPlus.
From VueJS, I'm calling a webapi that hits my "reports" controller. For now, I'm just trying to see if I can actually export an Excel file from code-behind.
Right now, when I attempt to export a dummy file... nothing happens? There aren't any errors, but there is no prompt that says "Download file or Open" (or whatever).
public class ReportController : ApiController
{
public HttpResponseMessage Get(string aliases, string startDate, string endDate, string level)
{
//attempting to just export a dummy excel - not working :(
MediaTypeHeaderValue mediaType = MediaTypeHeaderValue.Parse("application/octet-stream");
MemoryStream memoryStream = new MemoryStream(Resources.AbsenceReport);
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StreamContent(memoryStream);
response.Content.Headers.ContentType = mediaType;
response.Content.Headers.ContentDisposition =
new ContentDispositionHeaderValue("fileName") { FileName = "Test.xlsx" };
return response;
}
}
Am I missing something? In my Vue portion, I just have:
AR.getTeamReport(aliasesToSearch, startDate, endDate, level)
.then(response => {
//IDK MAN WILL IT WORK :X
})
.catch(error => {
console.log(error);
this.sentToastError(
"Unable to pull report. Please refresh and try again."
);
});

Shopware show product image in invoice pdf

I have issue with showing order product images in generated pdf invoices, but they are showed in credit notes. I have invoice template(index.tpl) where the images have to be showed. The credit note template (index_gs.tpl) which extends the invoice template(index.tpl) is working.
I need some help with the following:
How to debug shopware requests and queries?
Where is the data for templates loaded?
If you need information about anything like plugins, source of templates i will provide it.
Documents creation goes in Shopware_Components_Document.
public static function getSubscribedEvents()
{
return [
'Shopware_Components_Document::assignValues::after' => 'onAfterRenderDocument',
];
}
public function onAfterRenderDocument(\Enlight_Hook_HookArgs $args) {
$document = $args->getSubject();
$view = $document->_view;
$Order = $view->getTemplateVars('Order');
$User = $view->getTemplateVars('User');
$userID = $Order['_order']['userID'];
$orderID = $Order['_order']['id'];
$shopID = $Order['_order']['subshopID'];
$view->assign('customVar', 'Custom Value'); // This variable will be available in document.
}
How to debug shopware requests and queries?
You can use var_dump/print_r + exit in method above to see what you need.

Paging in MS Graph API

Graph API Paging explains that the response would contain a field #odata.nextLink which would contain a skiptoken pointing to the next page of contents.
When I test the API, I'm getting a fully-qualified MS Graph URL which contains the skiptoken as a query param. E.g. Below is the value I got for the field #odata.nextLink in the response JSON.
https://graph.microsoft.com/v1.0/users?$top=25&$skiptoken=X%27445370740200001E3A757365723134406F33363561702E6F6E6D6963726F736F66742E636F6D29557365725F31363064343831382D343162382D343961372D383063642D653136636561303437343437001E3A7573657235407368616C696E692D746573742E31626F74322E696E666F29557365725F62666639356437612D333764632D343266652D386335632D373639616534303233396166B900000000000000000000%27
Is it safe to assume we'll always get the full URL and not just the skiptoken? Because if it's true, it helps avoid parsing the skiptoken and then concatenating it to the existing URL to form the full URL ourselves.
EDIT - Compared to MS Graph API, response obtained from Azure AD Graph API differs in that the JSON field #odata.nextLink contains only the skipToken and not the fully-qualified URL.
if you would like to have all users in single list, you can achieve that using the code that follows:
public static async Task<IEnumerable<User>> GetUsersAsync()
{
var graphClient = GetAuthenticatedClient();
List<User> allUsers = new List<User>();
var users = await graphClient.Users.Request().Top(998)
.Select("displayName,mail,givenName,surname,id")
.GetAsync();
while (users.Count > 0)
{
allUsers.AddRange(users);
if (users.NextPageRequest != null)
{
users = await users.NextPageRequest
.GetAsync();
}
else
{
break;
}
}
return allUsers;
}
I am using graph client library
Yes. In Microsoft Graph you can assume that you'll always get the fully qualified URL for the #odata.nextLink. You can simply use the next link to get the next page of results, and clients should treat the nextLink as opaque (which is described in both OData v4 and in the Microsoft REST API guidelines here: https://github.com/Microsoft/api-guidelines/blob/master/Guidelines.md#98-pagination.
This is different from AAD Graph API (which is not OData v4), which doesn't return the fully qualified next link, and means you need to do some more complicated manipulations to get the next page of results.
Hence Microsoft Graph should make this simpler for you.
Hope this helps,
The above code did not work for me without adding a call to 'CurrentPage' on the last line.
Sample taken from here.
var driveItems = new List<DriveItem>();
var driveItemsPage = await graphClient.Me.Drive.Root.Children.Request().GetAsync();
driveItems.AddRange(driveItemsPage.CurrentPage);
while (driveItemsPage.NextPageRequest != null)
{
driveItemsPage = await driveItemsPage.NextPageRequest.GetAsync();
driveItems.AddRange(driveItemsPage.CurrentPage);
}
I followed Tracy's answer and I was able to fetch all the messages at one go.
public List<Message> GetMessages()
{
var messages = new List<Message>();
var pages = Client.Users[_email]
.Messages
.Request(QueryOptions)
// Fetch the emails with attachments directly instead of downloading them later.
.Expand("attachments")
.GetAsync()
.Result;
messages.AddRange(pages.CurrentPage);
while (pages.NextPageRequest != null)
{
pages = pages.NextPageRequest.GetAsync().Result;
messages.AddRange(pages.CurrentPage);
}
return messages;
}

Getting document attachments using Kentico API

I created book store site on Kentico i used only their adminstration and display the data from my website using Kentico API's but am strugled in getting attachment files related to specific document i've got document data with no problem using
TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser);
var documents = tree.SelectNodes("CMS.Product");
need also to get related attachment files like book PDFs.. i've tried to use
DocumentAttachment
AttachmentInfo
AttachmentInfoProvider
classes but i couldn't get the data .. I would appreciate if any one help me in that.
Actually am searching about something like GetAttachment().Where("AttachmentFile","Ënglish File")
You can filter the returned attachments based on their values in columns (CMS_Attachment table) by using a code like this:
var attachment = AttachmentInfoProvider.GetAttachments()
.WhereEquals("AttachmentName", "Englishfile")
.And()
.WhereEquals("AttachmentExtension", "jpg")
.TopN(1)
.FirstOrDefault();
if (attachment != null)
{
// attachment was found
}
This code will get one .jpg file where attachment name equals to "EnglishFile"
Solved after using something like
var Attachment = AttachmentInfoProvider.GetAttachments(226, true);
This is from Kentico documentation. This example shows how to add an attachment and modify its metadata. You can ignore that part.You will have to make it generic to work for all examples.
Kentico 9 API Links
// Creates a new instance of the Tree provider
TreeProvider tree = new TreeProvider(MembershipContext.AuthenticatedUser);
// Gets a page
TreeNode page = tree.SelectSingleNode(SiteContext.CurrentSiteName, "/Articles", "en-us");
if (page != null)
{
// Gets an attachment by file name
AttachmentInfo attachment = DocumentHelper.GetAttachment(page, "file.png", tree);
// Edits the attachment's metadata (name, title and description)
attachment.AttachmentName += " - modified";
attachment.AttachmentTitle = "Attachment title";
attachment.AttachmentDescription = "Attachment description.";
// Ensures that the attachment can be updated without supplying its binary data
attachment.AllowPartialUpdate = true;
// Saves the modified attachment into the database
AttachmentInfoProvider.SetAttachmentInfo(attachment);
}

How can I check if a file is beeing edited (locked ?) using csom?

I am using sharepoint CSOM to download / upload file from a OneDriveBusiness account.
Before downloading the file I need to check if the file is currently in use.
File.CheckOutType is alway "None".
I though using File.LockedByUser property, using the following code, but I got a ServerObjectNullReferenceException when the file is not locked.
var listItem = clientDocs.GetItemById(item.Id);
clientContext.Load(listItem.File.LockedByUser);
clientContext.ExecuteQuery();
var locked = listItem.File.LockedByUser.UserId;
I was hoping to be able to do do something like :
if (file."locked")
{
throw exception...
}
enter code here
Any idea ?
Thanks !
File.LockedByUser property is a deferred property, it need to be requested explicitly as demonstrated below:
var list = ctx.Web.Lists.GetByTitle(listTitle);
var listItem = list.GetItemById(itemId);
ctx.Load(listItem, i => i.File.CheckOutType, i => i.File.CheckedOutByUser, i => i.File.LockedByUser);
ctx.ExecuteQuery();
if(listItem.File.CheckOutType != CheckOutType.None) //Is checked out?
{
var checkoutUserName = listItem.File.CheckedOutByUser.LoginName;
var lockedUserName = listItem.File.LockedByUser.LoginName;
}

Resources