示例#1
0
        /// <summary>
        /// Assembles a document from the given template, answers and settings.
        /// </summary>
        /// <param name="template">The template to assemble.</param>
        /// <param name="answers">The answers to use during the assembly.</param>
        /// <param name="settings">The settings for the assembly.</param>
        /// <include file="../../Shared/Help.xml" path="Help/string/param[@name='logRef']"/>
        /// <returns>An <c>AssembleDocumentResult</c> that contains the results of the assembly.</returns>
        public AssembleDocumentResult AssembleDocument(Template template, System.IO.TextReader answers, AssembleDocumentSettings settings, string logRef)
        {
            // Validate input parameters, creating defaults as appropriate.
            string logStr = logRef == null ? string.Empty : logRef;

            if (template == null)
            {
                throw new ArgumentNullException("template", string.Format(@"Cloud.Services.AssembleDocument: the ""template"" parameter passed in was null, logRef: {0}", logStr));
            }

            if (settings == null)
            {
                settings = new AssembleDocumentSettings();
            }

            AssembleDocumentResult result    = null;
            AssemblyResult         asmResult = null;

            using (var client = new SoapClient(_subscriberID, _signingKey, HostAddress, ProxyAddress))
            {
                asmResult = client.AssembleDocument(
                    template,
                    answers == null ? "" : answers.ReadToEnd(),
                    settings,
                    logRef
                    );
            }

            if (asmResult != null)
            {
                result = Util.ConvertAssemblyResult(template, asmResult, settings.Format);
            }

            return(result);
        }
示例#2
0
        private static void SaveAssembledDocument(AssembleDocumentResult assembledDocumentResult)
        {
            var fileStream = System.IO.File.Create(@"C:\temp\output" + assembledDocumentResult.Document.FileExtension);

            assembledDocumentResult.Document.Content.CopyTo(fileStream);
            fileStream.Close();
        }
        /// <summary>
        /// <c>AssembleDocument</c> assembles (creates) a document from the given template, answers and settings.
        /// </summary>
        /// <param name="template">An instance of the Template class, from which the document will be assembled.</param>
        /// <param name="answers">The set of answers that will be applied to the template to assemble the document.</param>
        /// <param name="settings">Settings that will be used to assemble the document.
        /// These settings include the assembled document format (file extension), markup syntax, how to display fields with unanswered variables, etc</param>
        /// <param name="logRef">A string to display in logs related to this request.</param>
        /// <returns>returns information about the assembled document, the document type, the unanswered variables, the resulting answers, etc.</returns>
        public AssembleDocumentResult AssembleDocument(Template template, TextReader answers, AssembleDocumentSettings settings, string logRef)
        {
            // Validate input parameters, creating defaults as appropriate.
            string logStr = logRef == null ? string.Empty : logRef;

            if (template == null)
            {
                throw new ArgumentNullException("template", string.Format(@"WebService.Services.AssembleDocument: The ""template"" parameter passed in was null, logRef: {0}.", logStr));
            }

            if (settings == null)
            {
                settings = new AssembleDocumentSettings();
            }

            AssembleDocumentResult result    = null;
            AssemblyResult         asmResult = null;

            using (Proxy client = GetProxy())
            {
                OutputFormat outputFormat;
                if (template.GeneratesDocument)
                {
                    outputFormat = ConvertFormat(settings.Format);
                }
                else                 // avoid requesting any output other than answers from interview templates! (for the HDS web service)
                {
                    outputFormat = OutputFormat.Answers;
                }
                AssemblyOptions assemblyOptions = ConvertOptions(settings);
                string          fileName        = GetRelativePath(template.GetFullPath());
                asmResult = client.AssembleDocument(
                    fileName,
                    answers == null ? null : new BinaryObject[] { Util.GetBinaryObjectFromTextReader(answers) },                     // answers
                    outputFormat,
                    assemblyOptions,
                    null);
                SafeCloseClient(client, logRef);
            }

            if (asmResult != null)
            {
                result = Util.ConvertAssemblyResult(template, asmResult, settings.Format);
            }

            return(result);
        }
        /// <summary>
        /// Assemble a document from the given template, answers and settings.
        /// </summary>
        /// <param name="template">An instance of the Template class.</param>
        /// <param name="answers">Either an XML answer string, or a string containing encoded
        /// interview answers as posted from a HotDocs browser interview.</param>
        /// <param name="settings">An instance of the AssembleDocumentResult class.</param>
        /// <include file="../Shared/Help.xml" path="Help/string/param[@name='logRef']"/>
        /// <returns>An AssemblyResult object containing all the files and data resulting from the request.</returns>
        public AssembleDocumentResult AssembleDocument(Template template, TextReader answers, AssembleDocumentSettings settings, string logRef)
        {
            // Validate input parameters, creating defaults as appropriate.
            string logStr = logRef == null ? string.Empty : logRef;
            if (template == null)
                throw new ArgumentNullException("template", string.Format(@"Local.Services.AssembleDocument: the ""template"" parameter passed in was null, logRef: {0}", logStr));

            if (settings == null)
                settings = new AssembleDocumentSettings();

            HotDocs.Server.AnswerCollection ansColl = new HotDocs.Server.AnswerCollection();
            ansColl.OverlayXMLAnswers(answers == null ? "" : answers.ReadToEnd());
            HotDocs.Server.OutputOptions outputOptions = ConvertOutputOptions(settings.OutputOptions);

            string docPath = CreateTempDocDirAndPath(template, settings.Format);
            _app.AssembleDocument(
                template.GetFullPath(),//Template path
                settings.UseMarkupSyntax ? hdsi.HDAssemblyOptions.asmOptMarkupView : hdsi.HDAssemblyOptions.asmOptNone,
                ansColl,
                docPath,
                outputOptions);

            //Prepare the post-assembly answer set (dropping transient ("don't save") answers when appropriate)
            HotDocs.Sdk.AnswerCollection resultAnsColl = new AnswerCollection();
            resultAnsColl.ReadXml(new StringReader(ansColl.XmlAnswers));
            string resultAnsXml = resultAnsColl.GetXMLString(false, settings.RetainTransientAnswers || _app.PendingAssemblyCmdLineStrings.Count > 0);

            //Build the list of pending assemblies.
            List<Template> pendingAssemblies = new List<Template>();
            for (int i = 0; i < _app.PendingAssemblyCmdLineStrings.Count; i++)
            {
                string cmdLine = _app.PendingAssemblyCmdLineStrings[i];
                string path, switches;
                Util.ParseHdAsmCmdLine(cmdLine, out path, out switches);
                pendingAssemblies.Add(new Template(Path.GetFileName(path), template.Location.Duplicate(), switches));
            }

            //Prepare the document stream and image information for the browser.
            DocumentType docType = settings.Format;
            List<NamedStream> supportingFiles = new List<NamedStream>();
            MemoryStream docStream;
            if (docType == DocumentType.Native)
            {
                docType = Document.GetDocumentType(docPath);
                docStream = LoadFileIntoMemStream(docPath);
            }
            else if (docType == DocumentType.HTMLwDataURIs)
            {
                //If the consumer requested both HTML and HTMLwDataURIs, they'll only get the latter.
                string content = Util.EmbedImagesInURIs(docPath);
                docStream = new MemoryStream(Encoding.UTF8.GetBytes(content));
            }
            else if (docType == DocumentType.MHTML)
            {
                string content = Util.HtmlToMultiPartMime(docPath);
                docStream = new MemoryStream(Encoding.UTF8.GetBytes(content));
            }
            else if (docType == DocumentType.HTML)
            {
                string targetFilenameNoExtention = Path.GetFileNameWithoutExtension(docPath);
                foreach (string img in Directory.EnumerateFiles(Path.GetDirectoryName(docPath)))
                {
                    string ext = Path.GetExtension(img).ToLower();
                    if (Path.GetFileName(img).StartsWith(targetFilenameNoExtention) && (ext == ".jpg" || ext == ".jpeg" || ext == ".gif" || ext == ".png" || ext == ".bmp"))
                        supportingFiles.Add(LoadFileIntoNamedStream(img));
                }

                docStream = LoadFileIntoMemStream(docPath);
            }
            else
            {
                docStream = LoadFileIntoMemStream(docPath);
            }

            //Now that we've loaded all of the assembly results into memory, remove the assembly files.
            FreeTempDocDir(docPath);

            //Return the results.
            Document document = new Document(template, docStream, docType, supportingFiles.ToArray(), _app.UnansweredVariablesList.ToArray());
            AssembleDocumentResult result = new AssembleDocumentResult(document, resultAnsXml, pendingAssemblies.ToArray(), _app.UnansweredVariablesList.ToArray());
            return result;
        }
        /// <summary>
        /// Assemble a document from the given template, answers and settings.
        /// </summary>
        /// <param name="template">An instance of the Template class.</param>
        /// <param name="answers">Either an XML answer string, or a string containing encoded
        /// interview answers as posted from a HotDocs browser interview.</param>
        /// <param name="settings">An instance of the AssembleDocumentResult class.</param>
        /// <include file="../Shared/Help.xml" path="Help/string/param[@name='logRef']"/>
        /// <returns>An AssemblyResult object containing all the files and data resulting from the request.</returns>
        public AssembleDocumentResult AssembleDocument(Template template, TextReader answers, AssembleDocumentSettings settings, string logRef)
        {
            // Validate input parameters, creating defaults as appropriate.
            string logStr = logRef == null ? string.Empty : logRef;

            if (template == null)
            {
                throw new ArgumentNullException("template", string.Format(@"Local.Services.AssembleDocument: the ""template"" parameter passed in was null, logRef: {0}", logStr));
            }

            if (settings == null)
            {
                settings = new AssembleDocumentSettings();
            }


            HotDocs.Server.AnswerCollection ansColl = new HotDocs.Server.AnswerCollection();
            ansColl.OverlayXMLAnswers(answers == null ? "" : answers.ReadToEnd());
            HotDocs.Server.OutputOptions outputOptions = ConvertOutputOptions(settings.OutputOptions);

            string docPath = CreateTempDocDirAndPath(template, settings.Format);

            _app.AssembleDocument(
                template.GetFullPath(),                //Template path
                hdsi.HDAssemblyOptions.asmOptMarkupView,
                ansColl,
                docPath,
                outputOptions);

            //Prepare the post-assembly answer set.
            HotDocs.Sdk.AnswerCollection resultAnsColl = new AnswerCollection();
            resultAnsColl.ReadXml(new StringReader(ansColl.XmlAnswers));
            if (!settings.RetainTransientAnswers && _app.PendingAssemblyCmdLineStrings.Count == 0)
            {
                // Create a list of all "transient" answers to remove.
                IEnumerable <Answer> transAnswers    = from a in resultAnsColl where !a.Save select a;
                List <string>        answersToRemove = new List <string>();
                foreach (Answer ans in transAnswers)
                {
                    answersToRemove.Add(ans.Name);
                }

                // Iterate through the list of answers to remove and remove them from the result answer collection.
                // This is done as a separate step so we are not modifying the collecion over which we are iterating.
                foreach (string s in answersToRemove)
                {
                    resultAnsColl.RemoveAnswer(s);
                }
            }

            //Build the list of pending assemblies.
            List <Template> pendingAssemblies = new List <Template>();

            for (int i = 0; i < _app.PendingAssemblyCmdLineStrings.Count; i++)
            {
                string cmdLine = _app.PendingAssemblyCmdLineStrings[i];
                string path, switches;
                Util.ParseHdAsmCmdLine(cmdLine, out path, out switches);
                pendingAssemblies.Add(new Template(Path.GetFileName(path), template.Location.Duplicate(), switches));
            }

            //Prepare the document stream and image information for the browser.
            DocumentType       docType         = settings.Format;
            List <NamedStream> supportingFiles = new List <NamedStream>();
            MemoryStream       docStream;

            if (docType == DocumentType.Native)
            {
                docType   = Document.GetDocumentType(docPath);
                docStream = LoadFileIntoMemStream(docPath);
            }
            else if (docType == DocumentType.HTMLwDataURIs)
            {
                //If the consumer requested both HTML and HTMLwDataURIs, they'll only get the latter.
                string content = Util.EmbedImagesInURIs(docPath);
                docStream = new MemoryStream(Encoding.UTF8.GetBytes(content));
            }
            else if (docType == DocumentType.MHTML)
            {
                string content = Util.HtmlToMultiPartMime(docPath);
                docStream = new MemoryStream(Encoding.UTF8.GetBytes(content));
            }
            else if (docType == DocumentType.HTML)
            {
                string targetFilenameNoExtention = Path.GetFileNameWithoutExtension(docPath);
                foreach (string img in Directory.EnumerateFiles(Path.GetDirectoryName(docPath)))
                {
                    string ext = Path.GetExtension(img).ToLower();
                    if (Path.GetFileName(img).StartsWith(targetFilenameNoExtention) && (ext == ".jpg" || ext == ".jpeg" || ext == ".gif" || ext == ".png" || ext == ".bmp"))
                    {
                        supportingFiles.Add(LoadFileIntoNamedStream(img));
                    }
                }

                docStream = LoadFileIntoMemStream(docPath);
            }
            else
            {
                docStream = LoadFileIntoMemStream(docPath);
            }

            //Now that we've loaded all of the assembly results into memory, remove the assembly files.
            FreeTempDocDir(docPath);

            //Return the results.
            Document document             = new Document(template, docStream, docType, supportingFiles.ToArray(), _app.UnansweredVariablesList.ToArray());
            AssembleDocumentResult result = new AssembleDocumentResult(document, resultAnsColl.XmlAnswers, pendingAssemblies.ToArray(), _app.UnansweredVariablesList.ToArray());

            return(result);
        }
示例#6
0
        public AssembleDocumentResult AssembleDocument(Template template, TextReader answers,
                                                       AssembleDocumentSettings settings, string logRef)
        {
            using (var client = new HttpClient())
            {
                AssembleDocumentResult adr     = null;
                var    stringContent           = new StringContent(answers.ReadToEnd());
                var    packageTemplateLocation = (PackageTemplateLocation)template.Location;
                string packageId = packageTemplateLocation.PackageID;

                OutputFormat of = ConvertFormat(settings.Format);

                var urlBuilder =
                    new StringBuilder(string.Format(HostAddress + "/assemble/0/{0}/{1}?format={2}&encodefilenames={3}", packageId,
                                                    HttpUtility.UrlEncode(template.FileName), of, true));

                if (settings.Settings != null)
                {
                    foreach (var kv in settings.Settings)
                    {
                        urlBuilder.AppendFormat("&{0}={1}", kv.Key, kv.Value ?? "");
                    }
                }

                HttpResponseMessage result = client.PostAsync(urlBuilder.ToString(), stringContent).Result;

                var _parser = new MultipartMimeParser();

                HandleErrorStream(result, result.IsSuccessStatusCode);
                Stream streamResult = result.Content.ReadAsStreamAsync().Result;

                string outputDir = Path.GetTempPath();
                Directory.CreateDirectory(outputDir);
                using (var resultsStream = new MemoryStream())
                {
                    // Each part is written to a file whose name is specified in the content-disposition
                    // header, except for the AssemblyResult part, which has a file name of "meta0.xml",
                    // and is parsed into an AssemblyResult object.
                    _parser.WritePartsToStreams(
                        streamResult,
                        h =>
                    {
                        string fileName = GetFileNameFromHeaders(h);
                        if (fileName != null)
                        {
                            if (fileName.Equals("meta0.xml", StringComparison.OrdinalIgnoreCase))
                            {
                                return(resultsStream);
                            }

                            return(new FileStream(Path.Combine(outputDir, fileName), FileMode.Create));
                        }
                        return(Stream.Null);
                    },
                        (new ContentType(result.Content.Headers.ContentType.ToString())).Boundary);

                    if (resultsStream.Position > 0)
                    {
                        resultsStream.Position = 0;
                        var serializer = new XmlSerializer(typeof(AssemblyResult));
                        var asmResult  = (AssemblyResult)serializer.Deserialize(resultsStream);
                        if (asmResult != null)
                        {
                            adr = Util.ConvertAssemblyResult(template, asmResult, settings.Format);
                        }
                    }
                }
                return(adr);
            }
        }