Esempio n. 1
0
 /// <summary>
 /// Creates a WorkSession object that a host application can use to step through the process of presenting
 /// all the interviews and assembling all the documents that may result from the given template.
 ///
 /// Allows the default interview settings to be specified instead of being read from config file
 /// </summary>
 /// <param name="service">An object implementing the IServices interface, encapsulating the instance of
 /// HotDocs Server with which the host app is communicating.</param>
 /// <param name="template">The template upon which this WorkSession is based. The initial interview and/or
 /// document work items in the WorkSession will be based on this template (including its Switches property).</param>
 /// <param name="answers">A collection of XML answers to use as a starting point for the work session.
 /// The initial interview (if any) will be pre-populated with these answers, and the subsequent generation
 /// of documents will have access to these answers as well.</param>
 /// <param name="defaultInterviewSettings">The default interview settings to be used throughout the session</param>
 public WorkSession(IServices service, Template template, TextReader answers, InterviewSettings defaultInterviewSettings)
 {
     _service         = service;
     AnswerCollection = new AnswerCollection();
     if (answers != null)
     {
         AnswerCollection.ReadXml(answers);
     }
     DefaultAssemblySettings = new AssembleDocumentSettings();
     if (defaultInterviewSettings != null)
     {
         DefaultInterviewSettings = defaultInterviewSettings;
     }
     else
     {
         DefaultInterviewSettings = new InterviewSettings();
     }
     // add the work items
     _workItems = new List <WorkItem>();
     if (template.HasInterview)
     {
         _workItems.Add(new InterviewWorkItem(template));
     }
     if (template.GeneratesDocument)
     {
         _workItems.Add(new DocumentWorkItem(template));
     }
 }
Esempio n. 2
0
        internal static string GetInterviewDefinitionUrl(InterviewSettings settings, Template template)
        {
            // Start with the base InterviewFilesUrl and see if it already has a query string.
            //  If so, we will just be adding parameters. Otherwise, we will be appending a new query string to the base url.
            string url = settings.InterviewFilesUrl;

            url += url.Contains("?") ? "&" : "?";
            url += ("loc=" + template.CreateLocator());
            return(url);
        }
Esempio n. 3
0
        /// <summary>
        /// Returns the current interview with the given settings
        /// </summary>
        /// <param name="settings">Settings to use with the interview.</param>
        /// <param name="markedVariables">A list of variable names whose prompts should be "marked" in the interview.</param>
        /// <include file="../Shared/Help.xml" path="Help/string/param[@name='logRef']"/>
        /// <returns>An <c>InterviewResult</c> containing the HTML fragment and other supporting files for the interview.</returns>
        public InterviewResult GetCurrentInterview(InterviewSettings settings, IEnumerable <string> markedVariables, string logRef = "")
        {
            WorkItem   currentWorkItem = CurrentWorkItem;
            TextReader answers         = new StringReader(AnswerCollection.XmlAnswers);


            settings.Title = settings.Title ?? CurrentWorkItem.Template.Title;

            return(_service.GetInterview(currentWorkItem.Template, answers, settings, markedVariables, logRef));
        }
Esempio n. 4
0
        private static InterviewSettings GetInterviewSettings()
        {
            string postInterviewUrl       = "";
            string interviewRuntimeUrl    = "http://localhost/HDServerFiles/js";
            string interviewStylesheetUrl = "http://localhost/HDServerFiles/stylesheets";
            string interviewFileUrl       = "";

            var interviewSettings = new InterviewSettings(postInterviewUrl, interviewRuntimeUrl, interviewStylesheetUrl, interviewFileUrl);

            return(interviewSettings);
        }
Esempio n. 5
0
        /// <summary>
        /// This constructor accepts a value for the interview format in case the host application wants to have more
        /// control over which format to use other than the one format specified in web.config. For example, the host
        /// application can detect whether or not the user's browser has Silverlight installed, and if not, it can choose
        /// to fall back to JavaScript interviews even if its normal preference is Silverlight.
        /// </summary>
        /// <param name="format">The format (Silverlight or JavaScript) of interview being requested.</param>
        /// <returns>An <c>InterviewResult</c>, containing the HTML fragment and any other supporting files required by the interview.</returns>
        public InterviewResult GetCurrentInterview(Contracts.InterviewFormat format)
        {
            InterviewSettings s = DefaultInterviewSettings;

            // If a format was specified (e.g., it is not "Unspecified") then use the format provided.
            if (format != Contracts.InterviewFormat.Unspecified)
            {
                s.Format = format;
            }

            return(GetCurrentInterview(s, null));
        }
Esempio n. 6
0
        }                                                // null by default
        #endregion

        #region Public IServices Members

        /// <summary>
        /// Returns an HTML fragment suitable for inclusion in any standards-mode web page, which embeds a HotDocs interview
        /// directly in that web page.
        /// </summary>
        /// <param name="template">The template for which the interview will be requested.</param>
        /// <param name="answers">The initial set of answers to include in the interview.</param>
        /// <param name="settings">Settings that define various interview behavior.</param>
        /// <param name="markedVariables">A collection of variables that should be marked with special formatting in the interview.</param>
        /// <param name="logRef">A string to display in logs related to this request.</param>
        /// <returns>An object which contains an HTML fragment to be inserted in a web page to display the interview.</returns>
        public InterviewResult GetInterview(Template template, TextReader answers, InterviewSettings settings, IEnumerable <string> markedVariables, 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.GetInterview: the ""template"" parameter passed in was null, logRef: {0}", logStr));
            }

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

            // Configure interview settings
            settings.Settings["OmitImages"]       = "true";       // Instructs HDS not to return images used by the interview; we'll get them ourselves from the template location. (See GetInterviewFile below.)
            settings.Settings["OmitDefinitions"]  = "true";       // Instructs HDS not to return interview definitions; we'll get them ourselves from the template location. (See GetInterviewFile below.)
            settings.Settings["TempInterviewUrl"] = Util.GetInterviewImageUrl(settings, template);
            settings.Settings["InterviewDefUrl"]  = Util.GetInterviewDefinitionUrl(settings, template);
            settings.MarkedVariables = (string[])(markedVariables ?? new string[0]);

            // Get the interview.
            InterviewResult result = new InterviewResult();

            BinaryObject[] interviewFiles = null;
            using (var client = new SoapClient(_subscriberID, _signingKey, HostAddress, ProxyAddress))
            {
                interviewFiles = client.GetInterview(
                    template,
                    answers == null ? "" : answers.ReadToEnd(),
                    settings,
                    logRef
                    );

                // Throw an exception if we do not have exactly one interview file.
                // Although interviewFiles could potentially contain more than one item, the only one we care about is the
                // first one, which is the HTML fragment. All other items, such as interview definitions (.JS and .DLL files)
                // or dialog element images are not needed, because we can get them out of the package file instead.
                // We enforce this by setting the OmitImages and OmitDefinitions values above, so we will always have exactly one item here.
                if (interviewFiles.Length != 1)
                {
                    throw new Exception();
                }

                StringBuilder htmlFragment = new StringBuilder(Util.ExtractString(interviewFiles[0]));

                Util.AppendSdkScriptBlock(htmlFragment, template, settings);
                result.HtmlFragment = htmlFragment.ToString();
            }

            return(result);
        }
Esempio n. 7
0
        private static InterviewSettings GetInterviewSettings(string templateLocation)
        {
            string postInterviewUrl       = "Home/PostInterviewProcessing";
            string interviewRuntimeUrl    = "http://localhost/HDServerFiles/js";
            string interviewStylesheetUrl = "http://localhost/HDServerFiles/stylesheets";
            string interviewFileUrl       = HttpUtility.UrlEncode("/Home/GetInterviewFile?templatelocater=" + templateLocation);

            var interviewSettings = new InterviewSettings(postInterviewUrl, interviewRuntimeUrl, interviewStylesheetUrl, interviewFileUrl)
            {
                RoundTripUnusedAnswers = true
            };

            return(interviewSettings);
        }
Esempio n. 8
0
        private static InterviewSettings GetInterviewSettings()
        {
            string postInterviewUrl       = "Home/PostInterviewProcessing";
            string interviewRuntimeUrl    = "http://localhost/HDServerFiles/js";
            string interviewStylesheetUrl = "http://localhost/HDServerFiles/stylesheets";
            string interviewFileUrl       = "Home/GetInterviewFile";

            var interviewSettings = new InterviewSettings(postInterviewUrl, interviewRuntimeUrl, interviewStylesheetUrl, interviewFileUrl)
            {
                RoundTripUnusedAnswers = true
            };

            return(interviewSettings);
        }
Esempio n. 9
0
        private void GetInterview(IServices svc, string logRef)
        {
            // Set up the InterviewOptions for the test.
            Template tmp = Util.OpenTemplate("d1f7cade-cb74-4457-a9a0-27d94f5c2d5b");
            string postInterviewUrl = "PostInterview.aspx";
            string styleSheetUrl = "HDServerFiles/Stylesheets";
            string runtimeUrl = "HDServerFiles/js";
            string interviewDefUrl = "GetInterviewFile.ashx";
            //string interviewImgUrl = "GetInterviewFile.ashx";
            InterviewSettings settings = new InterviewSettings(postInterviewUrl, runtimeUrl, styleSheetUrl, interviewDefUrl);

            // Set up the Marked Variables for the test.
            string[] markedVars = null; // new string[] { };

            InterviewResult result;

            // Make sure that the parameters are being validated correctly.
            try
            {
                svc.GetInterview(null, null, null, null, null);
                Assert.Fail(); // If we get here then the exceptions were not fired as they should have been with all null parameters.
            }
            catch (ArgumentNullException ex)
            {
                Assert.IsTrue(ex.Message.IndexOf(": template") > 0);
            }
            catch (Exception)
            {
                Assert.Fail(); // Not expecting a generic exception.
            }

            result = svc.GetInterview(tmp, null, settings, markedVars, logRef);
            Assert.AreNotEqual(result.HtmlFragment, "");
            Assert.IsTrue(result.HtmlFragment.Contains(settings.PostInterviewUrl));
            Assert.IsTrue(result.HtmlFragment.Contains(runtimeUrl));
            Assert.IsTrue(result.HtmlFragment.Contains(styleSheetUrl));
            Assert.IsTrue(result.HtmlFragment.Contains(interviewDefUrl));
            //Assert.IsTrue(result.HtmlFragment.Contains(interviewImgUrl));
            Assert.IsTrue(result.HtmlFragment.Contains("hdMainDiv"));
            Assert.IsFalse(result.HtmlFragment.Contains("Employee Name\": { t: \"TX\", m:true")); // Employee Name should not be "marked"

            // Now get another interview, but this time specify a url for doc preview and save answers.
            settings.DocumentPreviewUrl = "DocPreview.aspx";
            settings.SaveAnswersUrl = "SaveAnswers.aspx";
            settings.Format = InterviewFormat.JavaScript; // explicitly set format to JS.
            result = svc.GetInterview(tmp, null, settings, markedVars, logRef);
            Assert.IsTrue(result.HtmlFragment.Contains(settings.DocumentPreviewUrl));
            Assert.IsTrue(result.HtmlFragment.Contains(settings.SaveAnswersUrl));
            Assert.IsTrue(result.HtmlFragment.Contains("HDJavaScriptInterview"));

            // Now get another interview, but this time do the following:
            // 1. Disable the doc preview and save answers urls.
            // 2. Do not include the hdMainDiv.
            // 3. "Mark" the Employee Name variable.
            // 4. Set the interview format to Silverlight.
            settings.DisableDocumentPreview = true;
            settings.DisableSaveAnswers = true;
            settings.AddHdMainDiv = Tristate.False;
            settings.Format = InterviewFormat.Silverlight;
            markedVars = new string[] { "Employee Name" };
            result = svc.GetInterview(tmp, null, settings, markedVars, logRef);
            Assert.IsFalse(result.HtmlFragment.Contains(settings.DocumentPreviewUrl));
            Assert.IsFalse(result.HtmlFragment.Contains(settings.SaveAnswersUrl), "No Save Ans Url because it is disabled");
            Assert.IsTrue(result.HtmlFragment.Contains("Employee Name\": { t: \"TX\", m:true")); // This interview does "mark" Employee Name.
            Assert.IsTrue(result.HtmlFragment.Contains("HDSilverlightInterview"));

            // Only HotDocs Cloud Services honors the AddHdMainDiv property of InterviewSettings, so only bother checking it if we are running a test against cloud services.
            if (svc is HotDocs.Sdk.Server.Cloud.Services)
                Assert.IsFalse(result.HtmlFragment.Contains("hdMainDiv"));

            // Now try once more with a null value for settings to allow the default settings to be used.
            // Also, in this test we are using an actual answer file so that we can test using answers.
            TextReader answers = Util.GetTestFile("Freddy.xml");
            result = svc.GetInterview(tmp, answers, null, markedVars, logRef);
            Assert.IsTrue(result.HtmlFragment.Contains("Freddy"));
        }
Esempio n. 10
0
 /// <summary>
 /// Gets an interview for the specified template.
 /// </summary>
 /// <param name="template">The template to use with the request.</param>
 /// <param name="answers">The answers to use with the request.</param>
 /// <param name="settings">The settings to use when getting an interview.</param>
 /// <param name="billingRef">This parameter lets you specify information that will be included in usage logs for this call. For example, you can use a string to uniquely identify the end user that initiated the request and/or the context in which the call was made. When you review usage logs, you can then see which end users initiated each request. That information could then be used to pass costs on to those end users if desired.</param>
 /// <returns>An <c>BinaryObject</c> array, which contains the HTML fragment and any dialog element images required by the requested interview.</returns>
 public BinaryObject[] GetInterview(Template template, string answers = null, InterviewSettings settings = null, string billingRef = null)
 {
     return((BinaryObject[])TryWithoutAndWithPackage(
                uploadPackage => GetInterviewImpl(template, answers, settings, billingRef, uploadPackage)));
 }
Esempio n. 11
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="template"></param>
 /// <param name="answers"></param>
 /// <param name="settings"></param>
 /// <param name="billingRef">This parameter lets you specify information that will be included in usage logs for this call. For example, you can use a string to uniquely identify the end user that initiated the request and/or the context in which the call was made. When you review usage logs, you can then see which end users initiated each request. That information could then be used to pass costs on to those end users if desired.</param>
 /// <param name="uploadPackage">Indicates if the package should be uploaded (forcefully) or not. This should only be true if the package does not already exist in the Cloud Services cache.</param>
 /// <returns></returns>
 protected internal abstract BinaryObject[] GetInterviewImpl(
     Template template,
     string answers,
     InterviewSettings settings,
     string billingRef,
     bool uploadPackage);
        ///<summary>
        ///	GetInterview returns an HTML fragment suitable for inclusion in any standards-mode web page, which embeds a HotDocs interview
        ///	directly in that web page.
        ///</summary>
        /// <param name="template">The template for which to return an interview.</param>
        /// <param name="answers">The answers to use when building an interview.</param>
        /// <param name="settings">The <see cref="InterviewSettings"/> to use when building an interview.</param>
        /// <param name="markedVariables">The variables to highlight to the user as needing special attention.
        ///     This is usually populated with <see cref="AssembleDocumentResult.UnansweredVariables" />
        ///     from <see cref="AssembleDocument" />.</param>
        /// <include file="../Shared/Help.xml" path="Help/string/param[@name='logRef']"/>
        /// <returns>Returns the results of building the interview as an <see cref="InterviewResult"/> object.</returns>
        public InterviewResult GetInterview(Template template, TextReader answers, InterviewSettings settings, IEnumerable <string> markedVariables, 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.GetInterview: the ""template"" parameter passed in was null, logRef: {0}", logStr));
            }

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

            // HotDocs Server reads the following settings out of the registry all the time; therefore these items are ignored when running against Server:
            //		settings.AddHdMainDiv
            //		settings.AnswerSummary.*
            //		settings.DefaultDateFormat
            //		settings.DefaultUnansweredFormat
            //		settings.HonorCmpUnansweredFormat
            //		settings.DisableAnswerSummary

            // HotDocs Server does not include the following settings in its .NET or COM APIs, so Util.AppendSdkScriptBlock (below)
            // includes them with the interview script block:
            //		settings.Locale
            //		settings.NextFollowsOutline
            //		settings.ShowAllResourceButtons

            hdsi.interviewFormat fmt;
            switch (settings.Format)
            {
            case InterviewFormat.JavaScript:
                fmt = hdsi.interviewFormat.javascript;
                break;

            case InterviewFormat.Silverlight:
                fmt = hdsi.interviewFormat.Silverlight;
                break;

            default:
                fmt = hdsi.interviewFormat.Unspecified;
                break;
            }

            // Configure the interview options
            hdsi.HDInterviewOptions itvOpts = hdsi.HDInterviewOptions.intOptNoImages;             // Instructs HDS not to return images used by the interview; we'll get them ourselves from the template folder.

            if (settings.DisableDocumentPreview)
            {
                itvOpts |= hdsi.HDInterviewOptions.intOptNoPreview;                 // Disables (omits) the Document Preview button on the interview toolbar.
            }
            if (settings.DisableSaveAnswers)
            {
                itvOpts |= hdsi.HDInterviewOptions.intOptNoSave;                 // Disables (omits) the Save Answers button on the interview toolbar.
            }
            if (settings.RoundTripUnusedAnswers)
            {
                itvOpts |= hdsi.HDInterviewOptions.intOptStateless;                 // Prevents original answer file from being encrypted and sent to the interview and then posted back at the end.
            }
            // Get the interview.
            InterviewResult result = new InterviewResult();

            StringBuilder htmlFragment;

            using (var ansColl = new HotDocs.Server.AnswerCollection())
            {
                if (answers != null)
                {
                    if (answers.Peek() == 0xFEFF)
                    {
                        answers.Read();                         // discard BOM if present
                    }
                    ansColl.XmlAnswers = answers.ReadToEnd();
                }

                if (markedVariables == null)
                {
                    _app.UnansweredVariablesList = new string[0];
                }
                else
                {
                    _app.UnansweredVariablesList = markedVariables;
                }

                htmlFragment = new StringBuilder(
                    _app.GetInterview(
                        template.GetFullPath(),
                        template.Key,
                        fmt,
                        itvOpts,
                        settings.InterviewRuntimeUrl,
                        settings.StyleSheetUrl + "/" + settings.ThemeName + ".css",
                        ansColl,
                        settings.PostInterviewUrl,
                        settings.Title,
                        Util.GetInterviewDefinitionUrl(settings, template),
                        null,                         // the path to which HDS should copy interview images; also the path that may become part of the DocumentPreviewStateString & passed to document preview handler
                        Util.GetInterviewImageUrl(settings, template),
                        settings.SaveAnswersUrl,
                        settings.DocumentPreviewUrl)
                    );
            }
            Util.AppendSdkScriptBlock(htmlFragment, template, settings);

            result.HtmlFragment = htmlFragment.ToString();
            return(result);
        }
Esempio n. 13
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="template"></param>
        /// <param name="answers"></param>
        /// <param name="settings"></param>
        /// <param name="billingRef">This parameter lets you specify information that will be included in usage logs for this call. For example, you can use a string to uniquely identify the end user that initiated the request and/or the context in which the call was made. When you review usage logs, you can then see which end users initiated each request. That information could then be used to pass costs on to those end users if desired.</param>
        /// <param name="uploadPackage">Indicates if the package should be uploaded (forcefully) or not. This should only be true if the package does not already exist in the Cloud Services cache.</param>
        /// <returns></returns>
        protected internal override BinaryObject[] GetInterviewImpl(
            Template template,
            string answers,
            InterviewSettings settings,
            string billingRef,
            bool uploadPackage)
        {
            if (!(template.Location is PackageTemplateLocation))
            {
                throw new Exception("HotDocs Cloud Services requires the use of template packages. Please use a PackageTemplateLocation derivative.");
            }
            PackageTemplateLocation packageTemplateLocation = (PackageTemplateLocation)template.Location;

            if (uploadPackage)
            {
                UploadPackage(packageTemplateLocation.PackageID, billingRef, packageTemplateLocation.GetPackageStream());
            }

            var timestamp = DateTime.UtcNow;

            string interviewImageUrl = string.Empty;

            if (settings != null)
            {
                settings.Settings.TryGetValue("TempInterviewUrl", out interviewImageUrl);
            }
            else
            {
                settings = new InterviewSettings();
            }

            string hmac = HMAC.CalculateHMAC(
                SigningKey,
                timestamp,
                SubscriberId,
                packageTemplateLocation.PackageID,
                template.FileName,
                false,
                billingRef,
                settings.Format,
                interviewImageUrl,
                settings.Settings);

            StringBuilder urlBuilder = new StringBuilder(string.Format(
                                                             "{0}/interview/{1}/{2}/{3}?format={4}&markedvariables={5}&tempimageurl={6}&billingref={7}",
                                                             EndpointAddress, SubscriberId, packageTemplateLocation.PackageID, template.FileName, settings.Format.ToString(),
                                                             settings.MarkedVariables != null ? string.Join(",", settings.MarkedVariables) : null, interviewImageUrl, billingRef));

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

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlBuilder.ToString());

            request.Method               = "POST";
            request.ContentType          = "text/xml";
            request.Headers["x-hd-date"] = timestamp.ToString("r");
            request.Headers[HttpRequestHeader.Authorization] = hmac;
            request.ContentLength = answers != null ? answers.Length : 0L;

            if (!string.IsNullOrEmpty(ProxyServerAddress))
            {
                request.Proxy = new WebProxy(ProxyServerAddress);
            }

            using (Stream stream = request.GetRequestStream())
            {
                if (answers != null)
                {
                    byte[] data = Encoding.UTF8.GetBytes(answers);
                    stream.Write(data, 0, data.Length);
                }
            }

            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                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 BinaryObject[] part, which has a file name of "meta0.xml",
                    // and is parsed into an BinaryObject[] object.
                    _parser.WritePartsToStreams(
                        response.GetResponseStream(),
                        h =>
                    {
                        string id = GetFileNameFromHeaders(h);
                        if (id != null)
                        {
                            if (id.Equals("meta0.xml", StringComparison.OrdinalIgnoreCase))
                            {
                                return(resultsStream);
                            }

                            // The following stream will be closed by the parser
                            return(new FileStream(Path.Combine(OutputDir, id), FileMode.Create));
                        }
                        return(Stream.Null);
                    },
                        (new ContentType(response.ContentType)).Boundary);

                    if (resultsStream.Position > 0)
                    {
                        resultsStream.Position = 0;
                        var serializer = new XmlSerializer(typeof(BinaryObject[]));
                        return((BinaryObject[])serializer.Deserialize(resultsStream));
                    }
                    return(null);
                }
            }
        }
Esempio n. 14
0
        ///<summary>
        ///	GetInterview returns an HTML fragment suitable for inclusion in any standards-mode web page, which embeds a HotDocs interview
        ///	directly in that web page.
        ///</summary>
        /// <param name="template">The template for which to return an interview.</param>
        /// <param name="answers">The answers to use when building an interview.</param>
        /// <param name="settings">The <see cref="InterviewSettings"/> to use when building an interview.</param>
        /// <param name="markedVariables">The variables to highlight to the user as needing special attention.
        /// 	This is usually populated with <see cref="AssembleDocumentResult.UnansweredVariables" />
        /// 	from <see cref="AssembleDocument" />.</param>
        /// <include file="../Shared/Help.xml" path="Help/string/param[@name='logRef']"/>
        /// <returns>Returns the results of building the interview as an <see cref="InterviewResult"/> object.</returns>
        public InterviewResult GetInterview(Template template, TextReader answers, InterviewSettings settings, IEnumerable<string> markedVariables, 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.GetInterview: the ""template"" parameter passed in was null, logRef: {0}", logStr));

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

            // HotDocs Server reads the following settings out of the registry all the time; therefore these items are ignored when running against Server:
            //		settings.AddHdMainDiv
            //		settings.AnswerSummary.*
            //		settings.DefaultDateFormat
            //		settings.DefaultUnansweredFormat
            //		settings.HonorCmpUnansweredFormat
            //		settings.DisableAnswerSummary

            // HotDocs Server does not include the following settings in its .NET or COM APIs, so Util.AppendSdkScriptBlock (below)
            // includes them with the interview script block:
            //		settings.Locale
            //		settings.NextFollowsOutline
            //		settings.ShowAllResourceButtons

            hdsi.interviewFormat fmt;
            switch (settings.Format)
            {
                case InterviewFormat.JavaScript:
                    fmt = hdsi.interviewFormat.javascript;
                    break;
                case InterviewFormat.Silverlight:
                    fmt = hdsi.interviewFormat.Silverlight;
                    break;
                default:
                    fmt = hdsi.interviewFormat.Unspecified;
                    break;
            }

            // Configure the interview options
            hdsi.HDInterviewOptions itvOpts = hdsi.HDInterviewOptions.intOptNoImages; // Instructs HDS not to return images used by the interview; we'll get them ourselves from the template folder.

            if (settings.DisableDocumentPreview)
                itvOpts |= hdsi.HDInterviewOptions.intOptNoPreview; // Disables (omits) the Document Preview button on the interview toolbar.
            if (settings.DisableSaveAnswers)
                itvOpts |= hdsi.HDInterviewOptions.intOptNoSave; // Disables (omits) the Save Answers button on the interview toolbar.
            if (settings.RoundTripUnusedAnswers)
                itvOpts |= hdsi.HDInterviewOptions.intOptStateless; // Prevents original answer file from being encrypted and sent to the interview and then posted back at the end.

            // Get the interview.
            InterviewResult result = new InterviewResult();

            StringBuilder htmlFragment;
            using (var ansColl = new HotDocs.Server.AnswerCollection())
            {
                if (answers != null)
                {
                    if (answers.Peek() == 0xFEFF)
                        answers.Read(); // discard BOM if present
                    ansColl.XmlAnswers = answers.ReadToEnd();
                }

                if (markedVariables == null)
                    _app.UnansweredVariablesList = new string[0];
                else
                    _app.UnansweredVariablesList = markedVariables;

                htmlFragment = new StringBuilder(
                    _app.GetInterview(
                        template.GetFullPath(),
                        template.Key,
                        fmt,
                        itvOpts,
                        settings.InterviewRuntimeUrl,
                        settings.StyleSheetUrl + "/" + settings.ThemeName + ".css",
                        ansColl,
                        settings.PostInterviewUrl,
                        settings.Title,
                        Util.GetInterviewDefinitionUrl(settings, template),
                        null, // the path to which HDS should copy interview images; also the path that may become part of the DocumentPreviewStateString & passed to document preview handler
                        Util.GetInterviewImageUrl(settings, template),
                        settings.SaveAnswersUrl,
                        settings.DocumentPreviewUrl)
                    );
            }
            Util.AppendSdkScriptBlock(htmlFragment, template, settings);

            result.HtmlFragment = htmlFragment.ToString();
            return result;
        }
Esempio n. 15
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="template"></param>
 /// <param name="answers"></param>
 /// <param name="settings"></param>
 /// <param name="billingRef">This parameter lets you specify information that will be included in usage logs for this call. For example, you can use a string to uniquely identify the end user that initiated the request and/or the context in which the call was made. When you review usage logs, you can then see which end users initiated each request. That information could then be used to pass costs on to those end users if desired.</param>
 /// <param name="uploadPackage">Indicates if the package should be uploaded (forcefully) or not. This should only be true if the package does not already exist in the Cloud Services cache.</param>
 /// <returns></returns>
 protected internal abstract BinaryObject[] GetInterviewImpl(
     Template template,
     string answers,
     InterviewSettings settings,
     string billingRef,
     bool uploadPackage);
Esempio n. 16
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="template"></param>
        /// <param name="answers"></param>
        /// <param name="settings"></param>
        /// <param name="billingRef">This parameter lets you specify information that will be included in usage logs for this call. For example, you can use a string to uniquely identify the end user that initiated the request and/or the context in which the call was made. When you review usage logs, you can then see which end users initiated each request. That information could then be used to pass costs on to those end users if desired.</param>
        /// <param name="uploadPackage">Indicates if the package should be uploaded (forcefully) or not. This should only be true if the package does not already exist in the Cloud Services cache.</param>
        /// <returns></returns>
        protected internal override BinaryObject[] GetInterviewImpl(
            Template template,
            string answers,
            InterviewSettings settings,
            string billingRef,
            bool uploadPackage)
        {
            if (!(template.Location is PackageTemplateLocation))
                throw new Exception("HotDocs Cloud Services requires the use of template packages. Please use a PackageTemplateLocation derivative.");
            PackageTemplateLocation packageTemplateLocation = (PackageTemplateLocation)template.Location;

            if (uploadPackage)
            {
                UploadPackage(packageTemplateLocation.PackageID, billingRef, packageTemplateLocation.GetPackageStream());
            }

            var timestamp = DateTime.UtcNow;

            string interviewImageUrl = string.Empty;
            settings.Settings.TryGetValue("TempInterviewUrl", out interviewImageUrl);

            string hmac = HMAC.CalculateHMAC(
                SigningKey,
                timestamp,
                SubscriberId,
                packageTemplateLocation.PackageID,
                template.FileName,
                false,
                billingRef,
                settings.Format,
                interviewImageUrl,
                settings.Settings);

            StringBuilder urlBuilder = new StringBuilder(string.Format(
                "{0}/RestfulSvc.svc/interview/{1}/{2}/{3}?format={4}&markedvariables={5}&tempimageurl={6}&billingref={7}",
                EndpointAddress, SubscriberId, packageTemplateLocation.PackageID, template.FileName, settings.Format.ToString(),
                settings.MarkedVariables != null ? string.Join(",", settings.MarkedVariables) : null, interviewImageUrl, billingRef));

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

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlBuilder.ToString());
            request.Method = "POST";
            request.ContentType = "text/xml";
            request.Headers["x-hd-date"] = timestamp.ToString("r");
            request.Headers[HttpRequestHeader.Authorization] = hmac;
            request.ContentLength = answers != null ? answers.Length : 0L;

            if (!string.IsNullOrEmpty(ProxyServerAddress))
            {
                request.Proxy = new WebProxy(ProxyServerAddress);
            }

            using (Stream stream = request.GetRequestStream())
            {
                if (answers != null)
                {
                    byte[] data = Encoding.UTF8.GetBytes(answers);
                    stream.Write(data, 0, data.Length);
                }
            }

            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                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 BinaryObject[] part, which has a file name of "meta0.xml",
                    // and is parsed into an BinaryObject[] object.
                    _parser.WritePartsToStreams(
                        response.GetResponseStream(),
                        h =>
                        {
                            string id = GetFileNameFromHeaders(h);
                            if (id != null)
                            {
                                if (id.Equals("meta0.xml", StringComparison.OrdinalIgnoreCase))
                                {
                                    return resultsStream;
                                }

                                // The following stream will be closed by the parser
                                return new FileStream(Path.Combine(OutputDir, id), FileMode.Create);
                            }
                            return Stream.Null;
                        },
                        (new ContentType(response.ContentType)).Boundary);

                    if (resultsStream.Position > 0)
                    {
                        resultsStream.Position = 0;
                        var serializer = new XmlSerializer(typeof(BinaryObject[]));
                        return (BinaryObject[])serializer.Deserialize(resultsStream);
                    }
                    return null;
                }
            }
        }
Esempio n. 17
0
        /// <summary>
        /// Returns an HTML fragment suitable for inclusion in any standards-mode web page, which embeds a HotDocs interview
        /// directly in that web page.
        /// </summary>
        /// <param name="template">The template for which the interview will be requested.</param>
        /// <param name="answers">The initial set of answers to include in the interview.</param>
        /// <param name="settings">Settings that define various interview behavior.</param>
        /// <param name="markedVariables">A collection of variables that should be marked with special formatting in the interview.</param>
        /// <param name="logRef">A string to display in logs related to this request.</param>
        /// <returns>An object which contains an HTML fragment to be inserted in a web page to display the interview.</returns>
        public InterviewResult GetInterview(Template template, TextReader answers, InterviewSettings settings, IEnumerable<string> markedVariables, 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.GetInterview: the ""template"" parameter passed in was null, logRef: {0}", logStr));

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

            // Configure interview settings
            settings.Settings["OmitImages"] = "true"; // Instructs HDS not to return images used by the interview; we'll get them ourselves from the template folder.
            settings.Settings["OmitDefinitions"] = "true"; // Instructs HDS not to return interview definitions; we'll get them ourselves from the template folder.
            settings.Settings["TempInterviewUrl"] = Util.GetInterviewImageUrl(settings, template);
            settings.Settings["InterviewDefUrl"] = Util.GetInterviewDefinitionUrl(settings, template);
            settings.MarkedVariables = (string[])(markedVariables ?? new string[0]);

            // Get the interview.
            InterviewResult result = new InterviewResult();
            BinaryObject[] interviewFiles = null;
            using (var client = new SoapClient(_subscriberID, _signingKey, HostAddress, ProxyAddress))
            {
                interviewFiles = client.GetInterview(
                    template,
                    answers == null ? "" : answers.ReadToEnd(),
                    settings,
                    logRef
                );

                // Throw an exception if we do not have exactly one interview file.
                // Although interviewFiles could potentially contain more than one item, the only one we care about is the
                // first one, which is the HTML fragment. All other items, such as interview definitions (.JS and .DLL files)
                // or dialog element images are not needed, because we can get them out of the package file instead.
                // We enforce this by setting the OmitImages and OmitDefinitions values above, so we will always have exactly one item here.
                if (interviewFiles.Length != 1)
                    throw new Exception();

                StringBuilder htmlFragment = new StringBuilder(Util.ExtractString(interviewFiles[0]));

                Util.AppendSdkScriptBlock(htmlFragment, template, settings);
                result.HtmlFragment = htmlFragment.ToString();
            }

            return result;
        }
Esempio n. 18
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="template">The template for which the interview is being requested.</param>
        /// <param name="answers">The answers to use with the interview.</param>
        /// <param name="settings">The settings to use when requesting the interview.</param>
        /// <param name="billingRef">This parameter lets you specify information that will be included in usage logs for this call. For example, you can use a string to uniquely identify the end user that initiated the request and/or the context in which the call was made. When you review usage logs, you can then see which end users initiated each request. That information could then be used to pass costs on to those end users if desired.</param>
        /// <param name="uploadPackage">Indicates if the package should be uploaded (forcefully) or not. This should only be true if the package does not already exist in the Cloud Services cache.</param>
        /// <returns></returns>
        protected internal override BinaryObject[] GetInterviewImpl(
			Template template,
			string answers,
			InterviewSettings settings,
			string billingRef,
			bool uploadPackage)
        {
            var timestamp = DateTime.UtcNow;
            if (!(template.Location is PackageTemplateLocation))
                throw new Exception("HotDocs Cloud Services requires the use of template packages. Please use a PackageTemplateLocation derivative.");
            PackageTemplateLocation packageTemplateLocation = (PackageTemplateLocation)template.Location;

            string interviewImageUrl = string.Empty;
            if (settings != null)
            {
                settings.Settings.TryGetValue("TempInterviewUrl", out interviewImageUrl);
            }
            else
            {
                settings = new InterviewSettings();
            }

            Dictionary<string, string> settingsDict = new Dictionary<string, string>(settings.Settings);

            // Workaround for bug in server that does not honor the Disable settings, so we have to just clear the url instead.
            // To do this, we make a copy of the settings that were given to us, modify them, and then use the modified version
            // in the call to Cloud Services.
            // TODO: After TFS #5598 is fixed, we can remove this workaround.
            // Note: TFS #5598 has been fixed, but the cloud implememntation does not pass those values through
            // to the cloud implmementation of HotDocs Server, so for now we leave these next 4 lines here that provide
            // equivalent functionality:
            if (settings.DisableDocumentPreview)
                settingsDict.Remove("DocPreviewUrl");
            if (settings.DisableSaveAnswers)
                settingsDict.Remove("SaveAnswersPageUrl");

            string hmac = HMAC.CalculateHMAC(
                SigningKey,
                timestamp,
                SubscriberId,
                packageTemplateLocation.PackageID,
                template.FileName,
                uploadPackage,
                billingRef,
                settings.Format,
                interviewImageUrl,
                settingsDict);

            return _proxy.GetInterview(
                SubscriberId,
                packageTemplateLocation.PackageID,
                template.FileName,
                GetBinaryObjectArrayFromString(answers),
                settings.Format,
                settings.MarkedVariables.ToArray<string>(),
                interviewImageUrl,
                settingsDict,
                billingRef,
                timestamp,
                GetPackageIfNeeded(packageTemplateLocation, uploadPackage),
                hmac);
        }
Esempio n. 19
0
        /// <summary>
        /// Returns the current interview with the given settings
        /// </summary>
        /// <param name="settings">Settings to use with the interview.</param>
        /// <param name="markedVariables">A list of variable names whose prompts should be "marked" in the interview.</param>
        /// <include file="../Shared/Help.xml" path="Help/string/param[@name='logRef']"/>
        /// <returns>An <c>InterviewResult</c> containing the HTML fragment and other supporting files for the interview.</returns>
        public InterviewResult GetCurrentInterview(InterviewSettings settings, IEnumerable<string> markedVariables, string logRef = "")
        {
            WorkItem currentWorkItem = CurrentWorkItem;
            TextReader answers = new StringReader(AnswerCollection.XmlAnswers);

            settings.Title = settings.Title ?? CurrentWorkItem.Template.Title;

            return _service.GetInterview(currentWorkItem.Template, answers, settings, markedVariables, logRef);
        }
Esempio n. 20
0
 internal static string GetInterviewImageUrl(InterviewSettings settings, Template template)
 {
     // This is the same as the interview definition URL, but we also add the type and template parameters to the query string.
     return(GetInterviewDefinitionUrl(settings, template) + "&type=img&template=");
 }
Esempio n. 21
0
 /// <summary>
 /// Creates a WorkSession object that a host application can use to step through the process of presenting
 /// all the interviews and assembling all the documents that may result from the given template.
 /// </summary>
 /// <param name="service">An object implementing the IServices interface, encapsulating the instance of
 /// HotDocs Server with which the host app is communicating.</param>
 /// <param name="template">The template upon which this WorkSession is based. The initial interview and/or
 /// document work items in the WorkSession will be based on this template (including its Switches property).</param>
 /// <param name="answers">A collection of XML answers to use as a starting point for the work session.
 /// The initial interview (if any) will be pre-populated with these answers, and the subsequent generation
 /// of documents will have access to these answers as well.</param>
 public WorkSession(IServices service, Template template, TextReader answers)
 {
     _service = service;
     AnswerCollection = new AnswerCollection();
     if (answers != null)
         AnswerCollection.ReadXml(answers);
     DefaultAssemblySettings = new AssembleDocumentSettings();
     DefaultInterviewSettings = new InterviewSettings();
     // add the work items
     _workItems = new List<WorkItem>();
     if (template.HasInterview)
         _workItems.Add(new InterviewWorkItem(template));
     if (template.GeneratesDocument)
         _workItems.Add(new DocumentWorkItem(template));
 }
Esempio n. 22
0
        internal static void AppendSdkScriptBlock(StringBuilder interview, Template template, InterviewSettings settings)
        {
            // Append the SDK specific script block begin
            interview.AppendLine();
            interview.AppendLine("<script type=\"text/javascript\">");

            // Append the template locator variable.
            interview.AppendFormat("HDTemplateLocator=\"{0}\";", template.CreateLocator());
            interview.AppendLine();

            // Append the interview locale (if the host app has overridden the server default)
            if (!String.IsNullOrEmpty(settings.Locale))
            {
                interview.AppendFormat("HDInterviewLocale=\"{0}\";", settings.Locale);
                interview.AppendLine();
            }
            // Append the "Next follows outline" setting (if the host app has overridden the server default)
            if (settings.NextFollowsOutline != Tristate.Default)
            {
                interview.AppendFormat("HDOutlineInOrder={0};", settings.NextFollowsOutline == Tristate.True ? "true" : "false");
                interview.AppendLine();
            }
            // Append the "Show all resource buttons" setting (if the host app has overridden the server default)
            if (settings.ShowAllResourceButtons != Tristate.Default)
            {
                interview.AppendFormat("HDShowAllResourceBtns={0};", settings.ShowAllResourceButtons == Tristate.True ? "true" : "false");
                interview.AppendLine();
            }

            if ((!string.IsNullOrEmpty(settings.AnswerFileDataServiceUrl) || (settings.CustomDataSources != null)))
            {
                // The SDK user has configured some data sources addresses to send down to the browser interview. Append a table
                // that maps data source names to data service addresses so that the browser will know how to request data for
                // a data source.

                // Get the data sources used by the template and all its dependencies.
                TemplateManifest templateManifest = template.GetManifest(ManifestParseFlags.ParseDataSources | ManifestParseFlags.ParseRecursively);

                Dictionary <string, string> dataSourceDict = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);
                string address;
                foreach (DataSource dataSource in templateManifest.DataSources)
                {
                    address = null;
                    switch (dataSource.Type)
                    {
                    case DataSourceType.AnswerFile:
                    {
                        address = settings.AnswerFileDataServiceUrl;
                        break;
                    }

                    case DataSourceType.Custom:
                    {
                        if (settings.CustomDataSources != null)
                        {
                            settings.CustomDataSources.TryGetValue(dataSource.Name, out address);
                        }
                        break;
                    }
                    }

                    if ((address != null) && !dataSourceDict.ContainsKey(dataSource.Name))
                    {
                        dataSourceDict.Add(dataSource.Name, address);
                    }
                }

                // Now write out all unique data sources.
                interview.AppendLine("HDDataSources=[");

                int i = 0;
                foreach (var dataSource in dataSourceDict)
                {
                    interview.AppendFormat("\t{{Name:\"{0}\", Address:\"{1}\"", dataSource.Key, dataSource.Value);
                    interview.AppendLine((i++ < dataSourceDict.Count - 1) ? "}," : "}");
                }

                interview.AppendLine("];");
            }

            // Append the SDK specific script block end
            interview.AppendLine("</script>");
        }
Esempio n. 23
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="template">The template for which the interview is being requested.</param>
        /// <param name="answers">The answers to use with the interview.</param>
        /// <param name="settings">The settings to use when requesting the interview.</param>
        /// <param name="billingRef">This parameter lets you specify information that will be included in usage logs for this call. For example, you can use a string to uniquely identify the end user that initiated the request and/or the context in which the call was made. When you review usage logs, you can then see which end users initiated each request. That information could then be used to pass costs on to those end users if desired.</param>
        /// <param name="uploadPackage">Indicates if the package should be uploaded (forcefully) or not. This should only be true if the package does not already exist in the Cloud Services cache.</param>
        /// <returns></returns>
        protected internal override BinaryObject[] GetInterviewImpl(
            Template template,
            string answers,
            InterviewSettings settings,
            string billingRef,
            bool uploadPackage)
        {
            var timestamp = DateTime.UtcNow;

            if (!(template.Location is PackageTemplateLocation))
            {
                throw new Exception("HotDocs Cloud Services requires the use of template packages. Please use a PackageTemplateLocation derivative.");
            }
            PackageTemplateLocation packageTemplateLocation = (PackageTemplateLocation)template.Location;

            string interviewImageUrl = string.Empty;

            if (settings != null)
            {
                settings.Settings.TryGetValue("TempInterviewUrl", out interviewImageUrl);
            }
            else
            {
                settings = new InterviewSettings();
            }

            Dictionary <string, string> settingsDict = new Dictionary <string, string>(settings.Settings);

            // Workaround for bug in server that does not honor the Disable settings, so we have to just clear the url instead.
            // To do this, we make a copy of the settings that were given to us, modify them, and then use the modified version
            // in the call to Cloud Services.
            // TODO: After TFS #5598 is fixed, we can remove this workaround.
            // Note: TFS #5598 has been fixed, but the cloud implememntation does not pass those values through
            // to the cloud implmementation of HotDocs Server, so for now we leave these next 4 lines here that provide
            // equivalent functionality:
            if (settings.DisableDocumentPreview)
            {
                settingsDict.Remove("DocPreviewUrl");
            }
            if (settings.DisableSaveAnswers)
            {
                settingsDict.Remove("SaveAnswersPageUrl");
            }

            string hmac = HMAC.CalculateHMAC(
                SigningKey,
                timestamp,
                SubscriberId,
                packageTemplateLocation.PackageID,
                template.FileName,
                uploadPackage,
                billingRef,
                settings.Format,
                interviewImageUrl,
                settingsDict);

            return(_proxy.GetInterview(
                       SubscriberId,
                       packageTemplateLocation.PackageID,
                       template.FileName,
                       GetBinaryObjectArrayFromString(answers),
                       settings.Format,
                       settings.MarkedVariables.ToArray <string>(),
                       interviewImageUrl,
                       settingsDict,
                       billingRef,
                       timestamp,
                       GetPackageIfNeeded(packageTemplateLocation, uploadPackage),
                       hmac));
        }
        /// <summary>
        /// <c>GetInterview</c> returns an HTML fragment suitable for inclusion in any standards-mode web page, which embeds a HotDocs interview
        /// directly in that web page.
        /// </summary>
        /// <param name="template">An instance of the Template class, for which the interview will be requested.</param>
        /// <param name="answers">The initial set of answers to include in the interview.</param>
        /// <param name="settings">Settings that define various interview behaviors.</param>
        /// <param name="markedVariables">A collection of variables that should be marked with special formatting in the interview.</param>
        /// <param name="logRef">A string to display in logs related to this request.</param>
        /// <returns>An object which contains an HTML fragment to be inserted in a web page to display the interview.</returns>
        public InterviewResult GetInterview(Template template, TextReader answers, InterviewSettings settings, IEnumerable <string> markedVariables, 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(@"WebServices.Services.GetInterview: the ""template"" parameter passed in was null, logRef: {0}", logStr));
            }

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

            // Configure interview options
            InterviewOptions itvOpts = InterviewOptions.OmitImages;             // Instructs HDS not to return images used by the interview; we'll get them ourselves from the template folder.

            if (settings.DisableDocumentPreview)
            {
                itvOpts |= InterviewOptions.NoPreview;                 // Disables (omits) the Document Preview button on the interview toolbar.
            }
            if (settings.DisableSaveAnswers)
            {
                itvOpts |= InterviewOptions.NoSave;                 // Disables (omits) the Save Answers button on the interview toolbar.
            }
            if (!settings.RoundTripUnusedAnswers)
            {
                itvOpts |= InterviewOptions.ExcludeStateFromOutput;                 // Prevents original answer file from being encrypted and sent to the interview and then posted back at the end.
            }
            // Get the interview.
            InterviewResult result = new InterviewResult();

            BinaryObject[] interviewFiles = null;

            using (Proxy client = new Proxy(_endPointName))
            {
                string fileName = GetRelativePath(template.GetFullPath());
                interviewFiles = client.GetInterview(
                    fileName,
                    answers == null ? null : new BinaryObject[] { Util.GetBinaryObjectFromTextReader(answers) },                     // answers
                    settings.Format,
                    itvOpts,
                    markedVariables != null ? markedVariables.ToArray <string>() : null, // variables to highlight as unanswered
                    settings.PostInterviewUrl,                                           // page to which interview will submit its answers
                    settings.InterviewRuntimeUrl,                                        // location (under this app's domain name) where HotDocs Server JS files are available
                    settings.StyleSheetUrl + "/" + settings.ThemeName + ".css",          // URL of CSS stylesheet (typically called hdsuser.css).  hdssystem.css must exist in same directory.
                    Util.GetInterviewImageUrl(settings, template),                       // interview images will be requested from GetInterviewFile.ashx, which will stream them from the template directory
                    !settings.DisableSaveAnswers ? settings.SaveAnswersUrl : "",         //for the save answers button; if this is null the "Save Answers" button does not appear
                    !settings.DisableDocumentPreview ? settings.DocumentPreviewUrl : "", // document previews will be requested from here; if null the "Document Preview" button does not appear
                    Util.GetInterviewDefinitionUrl(settings, template));                 // Interview definitions (Silverlight or JavaScript) will be requested from here -- careful with relative URLs!!
                if (interviewFiles != null)
                {
                    StringBuilder interview = new StringBuilder(Util.ExtractString(interviewFiles[0]));
                    Util.AppendSdkScriptBlock(interview, template, settings);
                    result.HtmlFragment = interview.ToString();

                    // The Web Services do not have a way to set the title of the template--it always uses the title from the component file.
                    // So here we are replacing the title that was put in the html fragment with the template's title, which may have
                    // been set later and does not match its component file.
                    result.HtmlFragment = Regex.Replace(result.HtmlFragment, "HDTemplateName=\\\".+?\"", "HDTemplateName=\"" + settings.Title + "\"");
                }
                SafeCloseClient(client, logRef);
            }
            return(result);
        }
        /// <summary>
        /// <c>GetInterview</c> returns an HTML fragment suitable for inclusion in any standards-mode web page, which embeds a HotDocs interview
        /// directly in that web page.
        /// </summary>
        /// <param name="template">An instance of the Template class, for which the interview will be requested.</param>
        /// <param name="answers">The initial set of answers to include in the interview.</param>
        /// <param name="settings">Settings that define various interview behaviors.</param>
        /// <param name="markedVariables">A collection of variables that should be marked with special formatting in the interview.</param>
        /// <param name="logRef">A string to display in logs related to this request.</param>
        /// <returns>An object which contains an HTML fragment to be inserted in a web page to display the interview.</returns>
        public InterviewResult GetInterview(Template template, TextReader answers, InterviewSettings settings, IEnumerable<string> markedVariables, 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(@"WebServices.Services.GetInterview: The ""template"" parameter passed in was null, logRef: {0}.", logStr));

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

            // Configure interview options
            InterviewOptions itvOpts = InterviewOptions.OmitImages; // Instructs HDS not to return images used by the interview; we'll get them ourselves from the template folder.
            if (settings.DisableDocumentPreview)
                itvOpts |= InterviewOptions.NoPreview; // Disables (omits) the Document Preview button on the interview toolbar.
            if (settings.DisableSaveAnswers)
                itvOpts |= InterviewOptions.NoSave; // Disables (omits) the Save Answers button on the interview toolbar.
            if (!settings.RoundTripUnusedAnswers)
                itvOpts |= InterviewOptions.ExcludeStateFromOutput; // Prevents original answer file from being encrypted and sent to the interview and then posted back at the end.

            // Get the interview.
            InterviewResult result = new InterviewResult();
            BinaryObject[] interviewFiles = null;

            using (Proxy client = GetProxy())
            {
                string fileName = GetRelativePath(template.GetFullPath());
                interviewFiles = client.GetInterview(
                    fileName,
                    answers == null ? null : new BinaryObject[] { Util.GetBinaryObjectFromTextReader(answers) }, // answers
                    settings.Format,
                    itvOpts,
                    markedVariables != null ? markedVariables.ToArray<string>() : null, // variables to highlight as unanswered
                    settings.PostInterviewUrl, // page to which interview will submit its answers
                    settings.InterviewRuntimeUrl, // location (under this app's domain name) where HotDocs Server JS files are available
                    settings.StyleSheetUrl + "/" + settings.ThemeName + ".css", // URL of CSS stylesheet (typically called hdsuser.css).  hdssystem.css must exist in same directory.
                    Util.GetInterviewImageUrl(settings, template), // interview images will be requested from GetInterviewFile.ashx, which will stream them from the template directory
                    !settings.DisableSaveAnswers ? settings.SaveAnswersUrl : "", //for the save answers button; if this is null the "Save Answers" button does not appear
                    !settings.DisableDocumentPreview ? settings.DocumentPreviewUrl : "", // document previews will be requested from here; if null the "Document Preview" button does not appear
                    Util.GetInterviewDefinitionUrl(settings, template)); // Interview definitions (Silverlight or JavaScript) will be requested from here -- careful with relative URLs!!
                if (interviewFiles != null)
                {
                    StringBuilder interview = new StringBuilder(Util.ExtractString(interviewFiles[0]));
                    Util.AppendSdkScriptBlock(interview, template, settings);
                    result.HtmlFragment = interview.ToString();

                    // The Web Services do not have a way to set the title of the template--it always uses the title from the component file.
                    // So here we are replacing the title that was put in the html fragment with the template's title, which may have
                    // been set later and does not match its component file.
                    result.HtmlFragment = Regex.Replace(result.HtmlFragment, "HDTemplateName=\\\".+?\"", "HDTemplateName=\"" + settings.Title + "\"");

                }
                SafeCloseClient(client, logRef);
            }
            return result;
        }
        public InterviewResult GetInterview(Template template, TextReader answers, InterviewSettings settings, IEnumerable<string> markedVariables, string logRef)
        {
            using (var client = new HttpClient())
            {
                var packageTemplateLocation = (PackageTemplateLocation)template.Location;
                var packageId = packageTemplateLocation.PackageID;

                var urlBuilder = new StringBuilder(string.Format(
                    HostAddress +
                    "/interview/0/{0}/?templatename={1}&format={2}&markedvariables{3}&tempimageurl={4}",
                    packageId, HttpUtility.UrlEncode(template.FileName), settings.Format,
                    markedVariables != null ? "=" + string.Join(",", settings.MarkedVariables) : null, settings.InterviewFilesUrl));

                foreach (KeyValuePair<string, string> kv in settings.Settings)
                {
                    urlBuilder.AppendFormat("&{0}={1}", kv.Key, kv.Value ?? "");
                }

                StringContent stringContent = answers == null ? new StringContent(String.Empty) : new StringContent(answers.ReadToEnd());

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

                HandleErrorStream(result, result.IsSuccessStatusCode);
                var streamResult = result.Content.ReadAsStreamAsync().Result;
                if (!result.IsSuccessStatusCode)
                {
                    using (var streamReader = new StreamReader(streamResult))
                    {
                        string error = streamReader.ReadToEnd();
                        throw new Exception(error);
                    }
                }

                var parser = new MultipartMimeParser();
                var 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 BinaryObject[] part, which has a file name of "meta0.xml",
                    // and is parsed into an BinaryObject[] object.
                    parser.WritePartsToStreams(
                        streamResult,
                        h =>
                        {
                            string fileName = GetFileNameFromHeaders(h);

                            if (!string.IsNullOrEmpty(fileName))
                            {
                                if (fileName.Equals("meta0.xml", StringComparison.OrdinalIgnoreCase))
                                {
                                    return resultsStream;
                                }
                                // The following stream will be closed by the parser
                                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(BinaryObject[]));
                        var binObjects = (BinaryObject[])serializer.Deserialize(resultsStream);
                        var interviewContent = Util.ExtractString(binObjects[0]);
                        return new InterviewResult { HtmlFragment = interviewContent };
                    }
                    return null;
                }
            }
        }
Esempio n. 27
0
 /// <summary>
 /// Gets an interview for the specified template.
 /// </summary>
 /// <param name="template">The template to use with the request.</param>
 /// <param name="answers">The answers to use with the request.</param>
 /// <param name="settings">The settings to use when getting an interview.</param>
 /// <param name="billingRef">This parameter lets you specify information that will be included in usage logs for this call. For example, you can use a string to uniquely identify the end user that initiated the request and/or the context in which the call was made. When you review usage logs, you can then see which end users initiated each request. That information could then be used to pass costs on to those end users if desired.</param>
 /// <returns>An <c>BinaryObject</c> array, which contains the HTML fragment and any dialog element images required by the requested interview.</returns>
 public BinaryObject[] GetInterview(Template template, string answers=null, InterviewSettings settings=null, string billingRef=null)
 {
     return (BinaryObject[])TryWithoutAndWithPackage(
         uploadPackage => GetInterviewImpl(template, answers, settings, billingRef, uploadPackage));
 }
        /// <summary>
        ///     GetInterview returns an HTML fragment suitable for inclusion in any standards-mode web page, which embeds a HotDocs
        ///     interview
        ///     directly in that web page.
        /// </summary>
        /// <param name="template">The template for which to return an interview.</param>
        /// <param name="answers">The answers to use when building an interview.</param>
        /// <param name="settings">The <see cref="InterviewSettings" /> to use when building an interview.</param>
        /// <param name="markedVariables">
        ///     The variables to highlight to the user as needing special attention.
        ///     This is usually populated with <see cref="AssembleDocumentResult.UnansweredVariables" />
        ///     from <see cref="AssembleDocument" />.
        /// </param>
        /// <include file="../Shared/Help.xml" path="Help/string/param[@name='logRef']" />
        /// <returns>Returns the results of building the interview as an <see cref="InterviewResult" /> object.</returns>
        public InterviewResult GetInterview(Template template, TextReader answers, InterviewSettings settings,
                                            IEnumerable <string> markedVariables, string logRef = "")
        {
            if (template == null)
            {
                throw new ArgumentNullException("template");
            }

            if (settings == null)
            {
                throw new ArgumentNullException("settings");
            }

            using (var client = new HttpClient())
            {
                var packageTemplateLocation = (PackageTemplateLocation)template.Location;
                var packageId = packageTemplateLocation.PackageID;
                var timestamp = DateTime.UtcNow;

                var hmac = HMAC.CalculateHMAC(
                    SigningKey,
                    timestamp,
                    SubscriberId,
                    packageId,
                    template.FileName,
                    false,
                    logRef,
                    settings.Format,
                    settings.InterviewFilesUrl,
                    settings.Settings);

                var urlBuilder = new StringBuilder().AppendFormat("{0}/interview/{1}/{2}/{3}?" +
                                                                  "format={4}&" +
                                                                  "markedvariables{5}&" +
                                                                  "tempimageurl={6}&" +
                                                                  "encodeFileNames={7}&" +
                                                                  "billingref={8}" +
                                                                  "{9}",
                                                                  HostAddress, SubscriberId, packageId, Uri.EscapeDataString(template.FileName),
                                                                  settings.Format,
                                                                  markedVariables != null && markedVariables.Any()
                        ? "=" + Uri.EscapeDataString(string.Join(",", settings.MarkedVariables))
                        : null,
                                                                  Uri.EscapeDataString(settings.InterviewFilesUrl),
                                                                  true,
                                                                  Uri.EscapeDataString(logRef),
                                                                  GetRetrieveFromHubParam());

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

                var request = new HttpRequestMessage
                {
                    RequestUri = new Uri(urlBuilder.ToString()),
                    Method     = HttpMethod.Post
                };

                request.Headers.Add("x-hd-date", timestamp.ToString("yyyy-MM-ddTHH:mm:ssZ"));
                request.Headers.Authorization = new AuthenticationHeaderValue("basic", hmac);

                var stringContent = answers == null
                    ? new StringContent(string.Empty)
                    : new StringContent(answers.ReadToEnd());

                request.Content = stringContent;

                var result = client.SendAsync(request).Result;

                HandleStatusCode(result);

                var streamResult = result.Content.ReadAsStreamAsync().Result;

                var parser    = new MultipartMimeParser();
                var outputDir = Path.GetTempPath();
                Directory.CreateDirectory(outputDir);
                var streams = new List <MemoryStream>();

                using (var resultsStream = new MemoryStream())
                {
                    // Each part is written to a file whose name is specified in the content-disposition
                    // header, except for the BinaryObject[] part, which has a file name of "meta0.xml",
                    // and is parsed into an BinaryObject[] object.
                    parser.WritePartsToStreams(
                        streamResult,
                        h =>
                    {
                        var fileName = GetFileNameFromHeaders(h);

                        if (string.IsNullOrEmpty(fileName))
                        {
                            return(Stream.Null);
                        }

                        if (fileName.Equals("meta0.xml", StringComparison.OrdinalIgnoreCase))
                        {
                            return(resultsStream);
                        }

                        // The following stream will be closed by the parser
                        var stream = new MemoryStream();
                        streams.Add(stream);
                        return(stream);
                    },
                        (new ContentType(result.Content.Headers.ContentType.ToString())).Boundary);

                    if (resultsStream.Position <= 0)
                    {
                        return(null);
                    }

                    resultsStream.Position = 0;
                    var serializer = new XmlSerializer(typeof(BinaryObject[]));
                    var binObjects = (BinaryObject[])serializer.Deserialize(resultsStream);

                    for (var i = 0; i < binObjects.Length; i++)
                    {
                        binObjects[i].Data = streams[i].ToArray();
                        streams[i].Dispose();
                    }

                    var interviewContent = Util.ExtractString(binObjects[0]);
                    return(new InterviewResult {
                        HtmlFragment = interviewContent
                    });
                }
            }
        }
Esempio n. 29
0
        public InterviewResult GetInterview(Template template, TextReader answers, InterviewSettings settings,
                                            IEnumerable <string> markedVariables, string logRef)
        {
            using (var client = new HttpClient())
            {
                var    packageTemplateLocation = (PackageTemplateLocation)template.Location;
                string packageId = packageTemplateLocation.PackageID;

                var urlBuilder = new StringBuilder(string.Format(
                                                       HostAddress +
                                                       "/interview/0/{0}/{1}?format={2}&markedvariables{3}&tempimageurl={4}&encodeFileNames={5}",
                                                       packageId, HttpUtility.UrlEncode(template.FileName), settings.Format,
                                                       markedVariables != null
                        ? "=" + HttpUtility.UrlEncode(string.Join(",", settings.MarkedVariables))
                        : null, HttpUtility.UrlEncode(settings.InterviewFilesUrl), true));

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

                StringContent stringContent = answers == null
                    ? new StringContent(String.Empty)
                    : new StringContent(answers.ReadToEnd());

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

                HandleErrorStream(result, result.IsSuccessStatusCode);
                Stream streamResult = result.Content.ReadAsStreamAsync().Result;
                if (!result.IsSuccessStatusCode)
                {
                    using (var streamReader = new StreamReader(streamResult))
                    {
                        string error = streamReader.ReadToEnd();
                        throw new Exception(error);
                    }
                }

                var    parser    = new MultipartMimeParser();
                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 BinaryObject[] part, which has a file name of "meta0.xml",
                    // and is parsed into an BinaryObject[] object.
                    parser.WritePartsToStreams(
                        streamResult,
                        h =>
                    {
                        string fileName = GetFileNameFromHeaders(h);

                        if (!string.IsNullOrEmpty(fileName))
                        {
                            if (fileName.Equals("meta0.xml", StringComparison.OrdinalIgnoreCase))
                            {
                                return(resultsStream);
                            }
                            // The following stream will be closed by the parser
                            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(BinaryObject[]));
                        var    binObjects       = (BinaryObject[])serializer.Deserialize(resultsStream);
                        string interviewContent = Util.ExtractString(binObjects[0]);
                        return(new InterviewResult {
                            HtmlFragment = interviewContent
                        });
                    }
                    return(null);
                }
            }
        }
Esempio n. 30
0
        private void GetInterview(IServices svc, string logRef)
        {
            // Set up the InterviewOptions for the test.
            Template tmp = Util.OpenTemplate("d1f7cade-cb74-4457-a9a0-27d94f5c2d5b");
            string   postInterviewUrl = "PostInterview.aspx";
            string   styleSheetUrl    = "HDServerFiles/Stylesheets";
            string   runtimeUrl       = "HDServerFiles/js";
            string   interviewDefUrl  = "GetInterviewFile.ashx";
            //string interviewImgUrl = "GetInterviewFile.ashx";
            InterviewSettings settings = new InterviewSettings(postInterviewUrl, runtimeUrl, styleSheetUrl, interviewDefUrl);

            // Set up the Marked Variables for the test.
            string[] markedVars = null;             // new string[] { };

            InterviewResult result;

            // Make sure that the parameters are being validated correctly.
            try
            {
                svc.GetInterview(null, null, null, null, null);
                Assert.Fail();                 // If we get here then the exceptions were not fired as they should have been with all null parameters.
            }
            catch (ArgumentNullException ex)
            {
                Assert.IsTrue(ex.Message.IndexOf(": template") > 0);
            }
            catch (Exception)
            {
                Assert.Fail();                 // Not expecting a generic exception.
            }

            result = svc.GetInterview(tmp, null, settings, markedVars, logRef);
            Assert.AreNotEqual(result.HtmlFragment, "");
            Assert.IsTrue(result.HtmlFragment.Contains(settings.PostInterviewUrl));
            Assert.IsTrue(result.HtmlFragment.Contains(runtimeUrl));
            Assert.IsTrue(result.HtmlFragment.Contains(styleSheetUrl));
            Assert.IsTrue(result.HtmlFragment.Contains(interviewDefUrl));
            //Assert.IsTrue(result.HtmlFragment.Contains(interviewImgUrl));
            Assert.IsTrue(result.HtmlFragment.Contains("hdMainDiv"));
            Assert.IsFalse(result.HtmlFragment.Contains("Employee Name\": { t: \"TX\", m:true"));             // Employee Name should not be "marked"

            // Now get another interview, but this time specify a url for doc preview and save answers.
            settings.DocumentPreviewUrl = "DocPreview.aspx";
            settings.SaveAnswersUrl     = "SaveAnswers.aspx";
            settings.Format             = InterviewFormat.JavaScript; // explicitly set format to JS.
            result = svc.GetInterview(tmp, null, settings, markedVars, logRef);
            Assert.IsTrue(result.HtmlFragment.Contains(settings.DocumentPreviewUrl));
            Assert.IsTrue(result.HtmlFragment.Contains(settings.SaveAnswersUrl));
            Assert.IsTrue(result.HtmlFragment.Contains("HDJavaScriptInterview"));

            // Now get another interview, but this time do the following:
            // 1. Disable the doc preview and save answers urls.
            // 2. Do not include the hdMainDiv.
            // 3. "Mark" the Employee Name variable.
            // 4. Set the interview format to Silverlight.
            settings.DisableDocumentPreview = true;
            settings.DisableSaveAnswers     = true;
            settings.AddHdMainDiv           = Tristate.False;
            settings.Format = InterviewFormat.Silverlight;
            markedVars      = new string[] { "Employee Name" };
            result          = svc.GetInterview(tmp, null, settings, markedVars, logRef);
            Assert.IsFalse(result.HtmlFragment.Contains(settings.DocumentPreviewUrl));
            Assert.IsFalse(result.HtmlFragment.Contains(settings.SaveAnswersUrl), "No Save Ans Url because it is disabled");
            Assert.IsTrue(result.HtmlFragment.Contains("Employee Name\": { t: \"TX\", m:true"));             // This interview does "mark" Employee Name.
            Assert.IsTrue(result.HtmlFragment.Contains("HDSilverlightInterview"));

            // Only HotDocs Cloud Services honors the AddHdMainDiv property of InterviewSettings, so only bother checking it if we are running a test against cloud services.
            if (svc is HotDocs.Sdk.Server.Cloud.Services)
            {
                Assert.IsFalse(result.HtmlFragment.Contains("hdMainDiv"));
            }

            // Now try once more with a null value for settings to allow the default settings to be used.
            // Also, in this test we are using an actual answer file so that we can test using answers.
            TextReader answers = Util.GetTestFile("Freddy.xml");

            result = svc.GetInterview(tmp, answers, null, markedVars, logRef);
            Assert.IsTrue(result.HtmlFragment.Contains("Freddy"));
        }